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
, IDBAccessObject
{
40 /** @var MapCacheLRU|null */
41 private static $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 * Flag for use with factory methods like newFromLinkTarget() that have
58 * a $forceClone parameter. If set, the method must return a new instance.
59 * Without this flag, some factory methods may return existing instances.
61 const NEW_CLONE
= 'clone';
64 * @name Private member variables
65 * Please use the accessor functions instead.
70 /** @var string Text form (spaces not underscores) of the main part */
71 public $mTextform = '';
73 /** @var string URL-encoded form of the main part */
74 public $mUrlform = '';
76 /** @var string Main part with underscores */
77 public $mDbkeyform = '';
79 /** @var string Database key with the initial letter in the case specified by the user */
80 protected $mUserCaseDBKey;
82 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
83 public $mNamespace = NS_MAIN
;
85 /** @var string Interwiki prefix */
86 public $mInterwiki = '';
88 /** @var bool Was this Title created from a string with a local interwiki prefix? */
89 private $mLocalInterwiki = false;
91 /** @var string Title fragment (i.e. the bit after the #) */
92 public $mFragment = '';
94 /** @var int Article ID, fetched from the link cache on demand */
95 public $mArticleID = -1;
97 /** @var bool|int ID of most recent revision */
98 protected $mLatestID = false;
101 * @var bool|string ID of the page's content model, i.e. one of the
102 * CONTENT_MODEL_XXX constants
104 private $mContentModel = false;
107 * @var bool If a content model was forced via setContentModel()
108 * this will be true to avoid having other code paths reset it
110 private $mForcedContentModel = false;
112 /** @var int Estimated number of revisions; null of not loaded */
113 private $mEstimateRevisions;
115 /** @var array Array of groups allowed to edit this article */
116 public $mRestrictions = [];
119 * @var string|bool Comma-separated set of permission keys
120 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
121 * Edit and move sections are separated by a colon
122 * Example: "edit=autoconfirmed,sysop:move=sysop"
124 protected $mOldRestrictions = false;
126 /** @var bool Cascade restrictions on this page to included templates and images? */
127 public $mCascadeRestriction;
129 /** Caching the results of getCascadeProtectionSources */
130 public $mCascadingRestrictions;
132 /** @var array When do the restrictions on this page expire? */
133 protected $mRestrictionsExpiry = [];
135 /** @var bool Are cascading restrictions in effect on this page? */
136 protected $mHasCascadingRestrictions;
138 /** @var array Where are the cascading restrictions coming from on this page? */
139 public $mCascadeSources;
141 /** @var bool Boolean for initialisation on demand */
142 public $mRestrictionsLoaded = false;
145 * Text form including namespace/interwiki, initialised on demand
147 * Only public to share cache with TitleFormatter
152 public $prefixedText = null;
154 /** @var mixed Cached value for getTitleProtection (create protection) */
155 public $mTitleProtection;
158 * @var int Namespace index when there is no namespace. Don't change the
159 * following default, NS_MAIN is hardcoded in several places. See T2696.
160 * Zero except in {{transclusion}} tags.
162 public $mDefaultNamespace = NS_MAIN
;
164 /** @var int The page length, 0 for special pages */
165 protected $mLength = -1;
167 /** @var null Is the article at this title a redirect? */
168 public $mRedirect = null;
170 /** @var array Associative array of user ID -> timestamp/false */
171 private $mNotificationTimestamp = [];
173 /** @var bool Whether a page has any subpages */
174 private $mHasSubpages;
176 /** @var bool The (string) language code of the page's language and content code. */
177 private $mPageLanguage = false;
179 /** @var string|bool|null The page language code from the database, null if not saved in
180 * the database or false if not loaded, yet. */
181 private $mDbPageLanguage = false;
183 /** @var TitleValue|null A corresponding TitleValue object */
184 private $mTitleValue = null;
186 /** @var bool|null Would deleting this page be a big deletion? */
187 private $mIsBigDeletion = null;
191 * B/C kludge: provide a TitleParser for use by Title.
192 * Ideally, Title would have no methods that need this.
193 * Avoid usage of this singleton by using TitleValue
194 * and the associated services when possible.
196 * @return TitleFormatter
198 private static function getTitleFormatter() {
199 return MediaWikiServices
::getInstance()->getTitleFormatter();
203 * B/C kludge: provide an InterwikiLookup for use by Title.
204 * Ideally, Title would have no methods that need this.
205 * Avoid usage of this singleton by using TitleValue
206 * and the associated services when possible.
208 * @return InterwikiLookup
210 private static function getInterwikiLookup() {
211 return MediaWikiServices
::getInstance()->getInterwikiLookup();
217 function __construct() {
221 * Create a new Title from a prefixed DB key
223 * @param string $key The database key, which has underscores
224 * instead of spaces, possibly including namespace and
226 * @return Title|null Title, or null on an error
228 public static function newFromDBkey( $key ) {
230 $t->mDbkeyform
= $key;
233 $t->secureAndSplit();
235 } catch ( MalformedTitleException
$ex ) {
241 * Returns a Title given a TitleValue.
242 * If the given TitleValue is already a Title instance, that instance is returned,
243 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
244 * is already a Title instance, that instance is copied using the clone operator.
246 * @param TitleValue $titleValue Assumed to be safe.
247 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
251 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
252 return self
::newFromLinkTarget( $titleValue, $forceClone );
256 * Returns a Title given a LinkTarget.
257 * If the given LinkTarget is already a Title instance, that instance is returned,
258 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
259 * is already a Title instance, that instance is copied using the clone operator.
261 * @param LinkTarget $linkTarget Assumed to be safe.
262 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
266 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
267 if ( $linkTarget instanceof Title
) {
268 // Special case if it's already a Title object
269 if ( $forceClone === self
::NEW_CLONE
) {
270 return clone $linkTarget;
275 return self
::makeTitle(
276 $linkTarget->getNamespace(),
277 $linkTarget->getText(),
278 $linkTarget->getFragment(),
279 $linkTarget->getInterwiki()
284 * Create a new Title from text, such as what one would find in a link. De-
285 * codes any HTML entities in the text.
287 * Title objects returned by this method are guaranteed to be valid, and
288 * thus return true from the isValid() method.
290 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
291 * It may instead be a cached instance created previously, with references to it remaining
294 * @param string|int|null $text The link text; spaces, prefixes, and an
295 * initial ':' indicating the main namespace are accepted.
296 * @param int $defaultNamespace The namespace to use if none is specified
297 * by a prefix. If you want to force a specific namespace even if
298 * $text might begin with a namespace prefix, use makeTitle() or
300 * @throws InvalidArgumentException
301 * @return Title|null Title or null on an error.
303 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
304 // DWIM: Integers can be passed in here when page titles are used as array keys.
305 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
306 throw new InvalidArgumentException( '$text must be a string.' );
308 if ( $text === null ) {
313 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
314 } catch ( MalformedTitleException
$ex ) {
320 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
321 * rather than returning null.
323 * The exception subclasses encode detailed information about why the title is invalid.
325 * Title objects returned by this method are guaranteed to be valid, and
326 * thus return true from the isValid() method.
328 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
329 * It may instead be a cached instance created previously, with references to it remaining
332 * @see Title::newFromText
335 * @param string $text Title text to check
336 * @param int $defaultNamespace
337 * @throws MalformedTitleException If the title is invalid
340 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
341 if ( is_object( $text ) ) {
342 throw new MWException( '$text must be a string, given an object' );
343 } elseif ( $text === null ) {
344 // Legacy code relies on MalformedTitleException being thrown in this case
345 // (happens when URL with no title in it is parsed). TODO fix
346 throw new MalformedTitleException( 'title-invalid-empty' );
349 $titleCache = self
::getTitleCache();
351 // Wiki pages often contain multiple links to the same page.
352 // Title normalization and parsing can become expensive on pages with many
353 // links, so we can save a little time by caching them.
354 // In theory these are value objects and won't get changed...
355 if ( $defaultNamespace == NS_MAIN
) {
356 $t = $titleCache->get( $text );
362 // Convert things like é ā or 〗 into normalized (T16952) text
363 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
366 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
367 $t->mDefaultNamespace
= (int)$defaultNamespace;
369 $t->secureAndSplit();
370 if ( $defaultNamespace == NS_MAIN
) {
371 $titleCache->set( $text, $t );
377 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
379 * Example of wrong and broken code:
380 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
382 * Example of right code:
383 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
385 * Create a new Title from URL-encoded text. Ensures that
386 * the given title's length does not exceed the maximum.
388 * @param string $url The title, as might be taken from a URL
389 * @return Title|null The new object, or null on an error
391 public static function newFromURL( $url ) {
394 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
395 # but some URLs used it as a space replacement and they still come
396 # from some external search tools.
397 if ( strpos( self
::legalChars(), '+' ) === false ) {
398 $url = strtr( $url, '+', ' ' );
401 $t->mDbkeyform
= strtr( $url, ' ', '_' );
404 $t->secureAndSplit();
406 } catch ( MalformedTitleException
$ex ) {
412 * @return MapCacheLRU
414 private static function getTitleCache() {
415 if ( self
::$titleCache === null ) {
416 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
418 return self
::$titleCache;
422 * Returns a list of fields that are to be selected for initializing Title
423 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
424 * whether to include page_content_model.
428 protected static function getSelectFields() {
429 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
432 'page_namespace', 'page_title', 'page_id',
433 'page_len', 'page_is_redirect', 'page_latest',
436 if ( $wgContentHandlerUseDB ) {
437 $fields[] = 'page_content_model';
440 if ( $wgPageLanguageUseDB ) {
441 $fields[] = 'page_lang';
448 * Create a new Title from an article ID
450 * @param int $id The page_id corresponding to the Title to create
451 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
452 * @return Title|null The new object, or null on an error
454 public static function newFromID( $id, $flags = 0 ) {
455 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
456 $row = $db->selectRow(
458 self
::getSelectFields(),
459 [ 'page_id' => $id ],
462 if ( $row !== false ) {
463 $title = self
::newFromRow( $row );
472 * Make an array of titles from an array of IDs
474 * @param int[] $ids Array of IDs
475 * @return Title[] Array of Titles
477 public static function newFromIDs( $ids ) {
478 if ( !count( $ids ) ) {
481 $dbr = wfGetDB( DB_REPLICA
);
485 self
::getSelectFields(),
486 [ 'page_id' => $ids ],
491 foreach ( $res as $row ) {
492 $titles[] = self
::newFromRow( $row );
498 * Make a Title object from a DB row
500 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
501 * @return Title Corresponding Title
503 public static function newFromRow( $row ) {
504 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
505 $t->loadFromRow( $row );
510 * Load Title object fields from a DB row.
511 * If false is given, the title will be treated as non-existing.
513 * @param stdClass|bool $row Database row
515 public function loadFromRow( $row ) {
516 if ( $row ) { // page found
517 if ( isset( $row->page_id
) ) {
518 $this->mArticleID
= (int)$row->page_id
;
520 if ( isset( $row->page_len
) ) {
521 $this->mLength
= (int)$row->page_len
;
523 if ( isset( $row->page_is_redirect
) ) {
524 $this->mRedirect
= (bool)$row->page_is_redirect
;
526 if ( isset( $row->page_latest
) ) {
527 $this->mLatestID
= (int)$row->page_latest
;
529 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
530 $this->mContentModel
= (string)$row->page_content_model
;
531 } elseif ( !$this->mForcedContentModel
) {
532 $this->mContentModel
= false; # initialized lazily in getContentModel()
534 if ( isset( $row->page_lang
) ) {
535 $this->mDbPageLanguage
= (string)$row->page_lang
;
537 if ( isset( $row->page_restrictions
) ) {
538 $this->mOldRestrictions
= $row->page_restrictions
;
540 } else { // page not found
541 $this->mArticleID
= 0;
543 $this->mRedirect
= false;
544 $this->mLatestID
= 0;
545 if ( !$this->mForcedContentModel
) {
546 $this->mContentModel
= false; # initialized lazily in getContentModel()
552 * Create a new Title from a namespace index and a DB key.
554 * It's assumed that $ns and $title are safe, for instance when
555 * they came directly from the database or a special page name,
556 * not from user input.
558 * No validation is applied. For convenience, spaces are normalized
559 * to underscores, so that e.g. user_text fields can be used directly.
561 * @note This method may return Title objects that are "invalid"
562 * according to the isValid() method. This is usually caused by
563 * configuration changes: e.g. a namespace that was once defined is
564 * no longer configured, or a character that was once allowed in
565 * titles is now forbidden.
567 * @param int $ns The namespace of the article
568 * @param string $title The unprefixed database key form
569 * @param string $fragment The link fragment (after the "#")
570 * @param string $interwiki The interwiki prefix
571 * @return Title The new object
573 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
575 $t->mInterwiki
= $interwiki;
576 $t->mFragment
= $fragment;
577 $t->mNamespace
= $ns = (int)$ns;
578 $t->mDbkeyform
= strtr( $title, ' ', '_' );
579 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
580 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
581 $t->mTextform
= strtr( $title, '_', ' ' );
582 $t->mContentModel
= false; # initialized lazily in getContentModel()
587 * Create a new Title from a namespace index and a DB key.
588 * The parameters will be checked for validity, which is a bit slower
589 * than makeTitle() but safer for user-provided data.
591 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
592 * that is, they return true from the isValid() method. If no valid Title
593 * can be constructed from the input, this method returns null.
595 * @param int $ns The namespace of the article
596 * @param string $title Database key form
597 * @param string $fragment The link fragment (after the "#")
598 * @param string $interwiki Interwiki prefix
599 * @return Title|null The new object, or null on an error
601 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
602 // NOTE: ideally, this would just call makeTitle() and then isValid(),
603 // but presently, that means more overhead on a potential performance hotspot.
605 if ( !MWNamespace
::exists( $ns ) ) {
610 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
613 $t->secureAndSplit();
615 } catch ( MalformedTitleException
$ex ) {
621 * Create a new Title for the Main Page
623 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
624 * It may instead be a cached instance created previously, with references to it remaining
627 * @return Title The new object
629 public static function newMainPage() {
630 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
631 // Don't give fatal errors if the message is broken
633 $title = self
::newFromText( 'Main Page' );
639 * Get the prefixed DB key associated with an ID
641 * @param int $id The page_id of the article
642 * @return Title|null An object representing the article, or null if no such article was found
644 public static function nameOf( $id ) {
645 $dbr = wfGetDB( DB_REPLICA
);
647 $s = $dbr->selectRow(
649 [ 'page_namespace', 'page_title' ],
650 [ 'page_id' => $id ],
653 if ( $s === false ) {
657 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
662 * Get a regex character class describing the legal characters in a link
664 * @return string The list of characters, not delimited
666 public static function legalChars() {
667 global $wgLegalTitleChars;
668 return $wgLegalTitleChars;
672 * Utility method for converting a character sequence from bytes to Unicode.
674 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
675 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
677 * @param string $byteClass
680 public static function convertByteClassToUnicodeClass( $byteClass ) {
681 $length = strlen( $byteClass );
683 $x0 = $x1 = $x2 = '';
685 $d0 = $d1 = $d2 = '';
686 // Decoded integer codepoints
687 $ord0 = $ord1 = $ord2 = 0;
689 $r0 = $r1 = $r2 = '';
693 $allowUnicode = false;
694 for ( $pos = 0; $pos < $length; $pos++
) {
695 // Shift the queues down
704 // Load the current input token and decoded values
705 $inChar = $byteClass[$pos];
706 if ( $inChar == '\\' ) {
707 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
708 $x0 = $inChar . $m[0];
709 $d0 = chr( hexdec( $m[1] ) );
710 $pos +
= strlen( $m[0] );
711 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
712 $x0 = $inChar . $m[0];
713 $d0 = chr( octdec( $m[0] ) );
714 $pos +
= strlen( $m[0] );
715 } elseif ( $pos +
1 >= $length ) {
718 $d0 = $byteClass[$pos +
1];
726 // Load the current re-encoded value
727 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
728 $r0 = sprintf( '\x%02x', $ord0 );
729 } elseif ( $ord0 >= 0x80 ) {
730 // Allow unicode if a single high-bit character appears
731 $r0 = sprintf( '\x%02x', $ord0 );
732 $allowUnicode = true;
733 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
739 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
741 if ( $ord2 > $ord0 ) {
743 } elseif ( $ord0 >= 0x80 ) {
745 $allowUnicode = true;
746 if ( $ord2 < 0x80 ) {
747 // Keep the non-unicode section of the range
754 // Reset state to the initial value
755 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
756 } elseif ( $ord2 < 0x80 ) {
761 if ( $ord1 < 0x80 ) {
764 if ( $ord0 < 0x80 ) {
767 if ( $allowUnicode ) {
768 $out .= '\u0080-\uFFFF';
774 * Make a prefixed DB key from a DB key and a namespace index
776 * @param int $ns Numerical representation of the namespace
777 * @param string $title The DB key form the title
778 * @param string $fragment The link fragment (after the "#")
779 * @param string $interwiki The interwiki prefix
780 * @param bool $canonicalNamespace If true, use the canonical name for
781 * $ns instead of the localized version.
782 * @return string The prefixed form of the title
784 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
785 $canonicalNamespace = false
787 if ( $canonicalNamespace ) {
788 $namespace = MWNamespace
::getCanonicalName( $ns );
790 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
792 $name = $namespace == '' ?
$title : "$namespace:$title";
793 if ( strval( $interwiki ) != '' ) {
794 $name = "$interwiki:$name";
796 if ( strval( $fragment ) != '' ) {
797 $name .= '#' . $fragment;
803 * Callback for usort() to do title sorts by (namespace, title)
805 * @param LinkTarget $a
806 * @param LinkTarget $b
808 * @return int Result of string comparison, or namespace comparison
810 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
811 return $a->getNamespace() <=> $b->getNamespace()
812 ?
: strcmp( $a->getText(), $b->getText() );
816 * Returns true if the title is valid, false if it is invalid.
818 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
819 * Invalid titles may get returned from makeTitle(), and it may be useful to
820 * allow them to exist, e.g. in order to process log entries about pages in
821 * namespaces that belong to extensions that are no longer installed.
823 * @note This method is relatively expensive. When constructing Title
824 * objects that need to be valid, use an instantiator method that is guaranteed
825 * to return valid titles, such as makeTitleSafe() or newFromText().
829 public function isValid() {
830 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
835 $parser = MediaWikiServices
::getInstance()->getTitleParser();
836 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
838 } catch ( MalformedTitleException
$ex ) {
844 * Determine whether the object refers to a page within
845 * this project (either this wiki or a wiki with a local
846 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
848 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
850 public function isLocal() {
851 if ( $this->isExternal() ) {
852 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
854 return $iw->isLocal();
861 * Is this Title interwiki?
865 public function isExternal() {
866 return $this->mInterwiki
!== '';
870 * Get the interwiki prefix
872 * Use Title::isExternal to check if a interwiki is set
874 * @return string Interwiki prefix
876 public function getInterwiki() {
877 return $this->mInterwiki
;
881 * Was this a local interwiki link?
885 public function wasLocalInterwiki() {
886 return $this->mLocalInterwiki
;
890 * Determine whether the object refers to a page within
891 * this project and is transcludable.
893 * @return bool True if this is transcludable
895 public function isTrans() {
896 if ( !$this->isExternal() ) {
900 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
904 * Returns the DB name of the distant wiki which owns the object.
906 * @return string|false The DB name
908 public function getTransWikiID() {
909 if ( !$this->isExternal() ) {
913 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
917 * Get a TitleValue object representing this Title.
919 * @note Not all valid Titles have a corresponding valid TitleValue
920 * (e.g. TitleValues cannot represent page-local links that have a
921 * fragment but no title text).
923 * @return TitleValue|null
925 public function getTitleValue() {
926 if ( $this->mTitleValue
=== null ) {
928 $this->mTitleValue
= new TitleValue(
934 } catch ( InvalidArgumentException
$ex ) {
935 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
936 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
940 return $this->mTitleValue
;
944 * Get the text form (spaces not underscores) of the main part
946 * @return string Main part of the title
948 public function getText() {
949 return $this->mTextform
;
953 * Get the URL-encoded form of the main part
955 * @return string Main part of the title, URL-encoded
957 public function getPartialURL() {
958 return $this->mUrlform
;
962 * Get the main part with underscores
964 * @return string Main part of the title, with underscores
966 public function getDBkey() {
967 return $this->mDbkeyform
;
971 * Get the DB key with the initial letter case as specified by the user
972 * @deprecated since 1.33; please use Title::getDBKey() instead
974 * @return string DB key
976 function getUserCaseDBKey() {
977 if ( !is_null( $this->mUserCaseDBKey
) ) {
978 return $this->mUserCaseDBKey
;
980 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
981 return $this->mDbkeyform
;
986 * Get the namespace index, i.e. one of the NS_xxxx constants.
988 * @return int Namespace index
990 public function getNamespace() {
991 return $this->mNamespace
;
995 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
997 * @todo Deprecate this in favor of SlotRecord::getModel()
999 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1000 * @return string Content model id
1002 public function getContentModel( $flags = 0 ) {
1003 if ( !$this->mForcedContentModel
1004 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1005 && $this->getArticleID( $flags )
1007 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1008 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1009 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1012 if ( !$this->mContentModel
) {
1013 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1016 return $this->mContentModel
;
1020 * Convenience method for checking a title's content model name
1022 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1023 * @return bool True if $this->getContentModel() == $id
1025 public function hasContentModel( $id ) {
1026 return $this->getContentModel() == $id;
1030 * Set a proposed content model for the page for permissions
1031 * checking. This does not actually change the content model
1034 * Additionally, you should make sure you've checked
1035 * ContentHandler::canBeUsedOn() first.
1038 * @param string $model CONTENT_MODEL_XXX constant
1040 public function setContentModel( $model ) {
1041 $this->mContentModel
= $model;
1042 $this->mForcedContentModel
= true;
1046 * Get the namespace text
1048 * @return string|false Namespace text
1050 public function getNsText() {
1051 if ( $this->isExternal() ) {
1052 // This probably shouldn't even happen, except for interwiki transclusion.
1053 // If possible, use the canonical name for the foreign namespace.
1054 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1055 if ( $nsText !== false ) {
1061 $formatter = self
::getTitleFormatter();
1062 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1063 } catch ( InvalidArgumentException
$ex ) {
1064 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1070 * Get the namespace text of the subject (rather than talk) page
1072 * @return string Namespace text
1074 public function getSubjectNsText() {
1075 return MediaWikiServices
::getInstance()->getContentLanguage()->
1076 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1080 * Get the namespace text of the talk page
1082 * @return string Namespace text
1084 public function getTalkNsText() {
1085 return MediaWikiServices
::getInstance()->getContentLanguage()->
1086 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1090 * Can this title have a corresponding talk page?
1092 * @see MWNamespace::hasTalkNamespace
1095 * @return bool True if this title either is a talk page or can have a talk page associated.
1097 public function canHaveTalkPage() {
1098 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1102 * Is this in a namespace that allows actual pages?
1106 public function canExist() {
1107 return $this->mNamespace
>= NS_MAIN
;
1111 * Can this title be added to a user's watchlist?
1115 public function isWatchable() {
1116 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1120 * Returns true if this is a special page.
1124 public function isSpecialPage() {
1125 return $this->mNamespace
== NS_SPECIAL
;
1129 * Returns true if this title resolves to the named special page
1131 * @param string $name The special page name
1134 public function isSpecial( $name ) {
1135 if ( $this->isSpecialPage() ) {
1136 list( $thisName, /* $subpage */ ) =
1137 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1138 resolveAlias( $this->mDbkeyform
);
1139 if ( $name == $thisName ) {
1147 * If the Title refers to a special page alias which is not the local default, resolve
1148 * the alias, and localise the name as necessary. Otherwise, return $this
1152 public function fixSpecialName() {
1153 if ( $this->isSpecialPage() ) {
1154 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1155 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1156 if ( $canonicalName ) {
1157 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1158 if ( $localName != $this->mDbkeyform
) {
1159 return self
::makeTitle( NS_SPECIAL
, $localName );
1167 * Returns true if the title is inside the specified namespace.
1169 * Please make use of this instead of comparing to getNamespace()
1170 * This function is much more resistant to changes we may make
1171 * to namespaces than code that makes direct comparisons.
1172 * @param int $ns The namespace
1176 public function inNamespace( $ns ) {
1177 return MWNamespace
::equals( $this->mNamespace
, $ns );
1181 * Returns true if the title is inside one of the specified namespaces.
1183 * @param int|int[] $namespaces,... The namespaces to check for
1187 public function inNamespaces( /* ... */ ) {
1188 $namespaces = func_get_args();
1189 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1190 $namespaces = $namespaces[0];
1193 foreach ( $namespaces as $ns ) {
1194 if ( $this->inNamespace( $ns ) ) {
1203 * Returns true if the title has the same subject namespace as the
1204 * namespace specified.
1205 * For example this method will take NS_USER and return true if namespace
1206 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1207 * as their subject namespace.
1209 * This is MUCH simpler than individually testing for equivalence
1210 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1215 public function hasSubjectNamespace( $ns ) {
1216 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1220 * Is this Title in a namespace which contains content?
1221 * In other words, is this a content page, for the purposes of calculating
1226 public function isContentPage() {
1227 return MWNamespace
::isContent( $this->mNamespace
);
1231 * Would anybody with sufficient privileges be able to move this page?
1232 * Some pages just aren't movable.
1236 public function isMovable() {
1237 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1238 // Interwiki title or immovable namespace. Hooks don't get to override here
1243 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1248 * Is this the mainpage?
1249 * @note Title::newFromText seems to be sufficiently optimized by the title
1250 * cache that we don't need to over-optimize by doing direct comparisons and
1251 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1252 * ends up reporting something differently than $title->isMainPage();
1257 public function isMainPage() {
1258 return $this->equals( self
::newMainPage() );
1262 * Is this a subpage?
1266 public function isSubpage() {
1267 return MWNamespace
::hasSubpages( $this->mNamespace
)
1268 ?
strpos( $this->getText(), '/' ) !== false
1273 * Is this a conversion table for the LanguageConverter?
1277 public function isConversionTable() {
1278 // @todo ConversionTable should become a separate content model.
1280 return $this->mNamespace
== NS_MEDIAWIKI
&&
1281 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1285 * Does that page contain wikitext, or it is JS, CSS or whatever?
1289 public function isWikitextPage() {
1290 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1294 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1295 * global UI. This is generally true for pages in the MediaWiki namespace having
1296 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1298 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1301 * Note that this method should not return true for pages that contain and show
1302 * "inactive" CSS, JSON, or JS.
1307 public function isSiteConfigPage() {
1309 $this->isSiteCssConfigPage()
1310 ||
$this->isSiteJsonConfigPage()
1311 ||
$this->isSiteJsConfigPage()
1316 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1321 public function isUserConfigPage() {
1323 $this->isUserCssConfigPage()
1324 ||
$this->isUserJsonConfigPage()
1325 ||
$this->isUserJsConfigPage()
1330 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1332 * @return string Containing skin name from .css, .json, or .js subpage title
1335 public function getSkinFromConfigSubpage() {
1336 $subpage = explode( '/', $this->mTextform
);
1337 $subpage = $subpage[count( $subpage ) - 1];
1338 $lastdot = strrpos( $subpage, '.' );
1339 if ( $lastdot === false ) {
1340 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1342 return substr( $subpage, 0, $lastdot );
1346 * Is this a CSS "config" sub-page of a user page?
1351 public function isUserCssConfigPage() {
1353 NS_USER
== $this->mNamespace
1354 && $this->isSubpage()
1355 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1360 * Is this a JSON "config" sub-page of a user page?
1365 public function isUserJsonConfigPage() {
1367 NS_USER
== $this->mNamespace
1368 && $this->isSubpage()
1369 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1374 * Is this a JS "config" sub-page of a user page?
1379 public function isUserJsConfigPage() {
1381 NS_USER
== $this->mNamespace
1382 && $this->isSubpage()
1383 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1388 * Is this a sitewide CSS "config" page?
1393 public function isSiteCssConfigPage() {
1395 NS_MEDIAWIKI
== $this->mNamespace
1397 $this->hasContentModel( CONTENT_MODEL_CSS
)
1398 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1399 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1400 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1406 * Is this a sitewide JSON "config" page?
1411 public function isSiteJsonConfigPage() {
1413 NS_MEDIAWIKI
== $this->mNamespace
1415 $this->hasContentModel( CONTENT_MODEL_JSON
)
1416 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1417 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1418 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1424 * Is this a sitewide JS "config" page?
1429 public function isSiteJsConfigPage() {
1431 NS_MEDIAWIKI
== $this->mNamespace
1433 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1434 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1435 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1436 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1442 * Is this a message which can contain raw HTML?
1447 public function isRawHtmlMessage() {
1448 global $wgRawHtmlMessages;
1450 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1453 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1454 return in_array( $message, $wgRawHtmlMessages, true );
1458 * Is this a talk page of some sort?
1462 public function isTalkPage() {
1463 return MWNamespace
::isTalk( $this->mNamespace
);
1467 * Get a Title object associated with the talk page of this article
1469 * @return Title The object for the talk page
1471 public function getTalkPage() {
1472 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1476 * Get a Title object associated with the talk page of this article,
1477 * if such a talk page can exist.
1481 * @return Title|null The object for the talk page,
1482 * or null if no associated talk page can exist, according to canHaveTalkPage().
1484 public function getTalkPageIfDefined() {
1485 if ( !$this->canHaveTalkPage() ) {
1489 return $this->getTalkPage();
1493 * Get a title object associated with the subject page of this
1496 * @return Title The object for the subject page
1498 public function getSubjectPage() {
1499 // Is this the same title?
1500 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1501 if ( $this->mNamespace
== $subjectNS ) {
1504 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1508 * Get the other title for this page, if this is a subject page
1509 * get the talk page, if it is a subject page get the talk page
1512 * @throws MWException If the page doesn't have an other page
1515 public function getOtherPage() {
1516 if ( $this->isSpecialPage() ) {
1517 throw new MWException( 'Special pages cannot have other pages' );
1519 if ( $this->isTalkPage() ) {
1520 return $this->getSubjectPage();
1522 if ( !$this->canHaveTalkPage() ) {
1523 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1525 return $this->getTalkPage();
1530 * Get the default namespace index, for when there is no namespace
1532 * @return int Default namespace index
1534 public function getDefaultNamespace() {
1535 return $this->mDefaultNamespace
;
1539 * Get the Title fragment (i.e.\ the bit after the #) in text form
1541 * Use Title::hasFragment to check for a fragment
1543 * @return string Title fragment
1545 public function getFragment() {
1546 return $this->mFragment
;
1550 * Check if a Title fragment is set
1555 public function hasFragment() {
1556 return $this->mFragment
!== '';
1560 * Get the fragment in URL form, including the "#" character if there is one
1562 * @return string Fragment in URL form
1564 public function getFragmentForURL() {
1565 if ( !$this->hasFragment() ) {
1567 } elseif ( $this->isExternal() ) {
1568 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1569 // so we treat it like a local interwiki.
1570 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1571 if ( $interwiki && !$interwiki->isLocal() ) {
1572 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1576 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1580 * Set the fragment for this title. Removes the first character from the
1581 * specified fragment before setting, so it assumes you're passing it with
1584 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1585 * or Title::createFragmentTarget().
1586 * Still in active use privately.
1589 * @param string $fragment Text
1591 public function setFragment( $fragment ) {
1592 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1596 * Creates a new Title for a different fragment of the same page.
1599 * @param string $fragment
1602 public function createFragmentTarget( $fragment ) {
1603 return self
::makeTitle(
1612 * Prefix some arbitrary text with the namespace or interwiki prefix
1615 * @param string $name The text
1616 * @return string The prefixed text
1618 private function prefix( $name ) {
1620 if ( $this->isExternal() ) {
1621 $p = $this->mInterwiki
. ':';
1624 if ( $this->mNamespace
!= 0 ) {
1625 $nsText = $this->getNsText();
1627 if ( $nsText === false ) {
1628 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1629 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1630 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1633 $p .= $nsText . ':';
1639 * Get the prefixed database key form
1641 * @return string The prefixed title, with underscores and
1642 * any interwiki and namespace prefixes
1644 public function getPrefixedDBkey() {
1645 $s = $this->prefix( $this->mDbkeyform
);
1646 $s = strtr( $s, ' ', '_' );
1651 * Get the prefixed title with spaces.
1652 * This is the form usually used for display
1654 * @return string The prefixed title, with spaces
1656 public function getPrefixedText() {
1657 if ( $this->prefixedText
=== null ) {
1658 $s = $this->prefix( $this->mTextform
);
1659 $s = strtr( $s, '_', ' ' );
1660 $this->prefixedText
= $s;
1662 return $this->prefixedText
;
1666 * Return a string representation of this title
1668 * @return string Representation of this title
1670 public function __toString() {
1671 return $this->getPrefixedText();
1675 * Get the prefixed title with spaces, plus any fragment
1676 * (part beginning with '#')
1678 * @return string The prefixed title, with spaces and the fragment, including '#'
1680 public function getFullText() {
1681 $text = $this->getPrefixedText();
1682 if ( $this->hasFragment() ) {
1683 $text .= '#' . $this->mFragment
;
1689 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1693 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1697 * @return string Root name
1700 public function getRootText() {
1701 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1702 return $this->getText();
1705 return strtok( $this->getText(), '/' );
1709 * Get the root page name title, i.e. the leftmost part before any slashes
1713 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1714 * # returns: Title{User:Foo}
1717 * @return Title Root title
1720 public function getRootTitle() {
1721 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1725 * Get the base page name without a namespace, i.e. the part before the subpage name
1729 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1730 * # returns: 'Foo/Bar'
1733 * @return string Base name
1735 public function getBaseText() {
1736 $text = $this->getText();
1737 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1741 $lastSlashPos = strrpos( $text, '/' );
1742 // Don't discard the real title if there's no subpage involved
1743 if ( $lastSlashPos === false ) {
1747 return substr( $text, 0, $lastSlashPos );
1751 * Get the base page name title, i.e. the part before the subpage name
1755 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1756 * # returns: Title{User:Foo/Bar}
1759 * @return Title Base title
1762 public function getBaseTitle() {
1763 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1767 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1771 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1775 * @return string Subpage name
1777 public function getSubpageText() {
1778 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1779 return $this->mTextform
;
1781 $parts = explode( '/', $this->mTextform
);
1782 return $parts[count( $parts ) - 1];
1786 * Get the title for a subpage of the current page
1790 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1791 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1794 * @param string $text The subpage name to add to the title
1795 * @return Title|null Subpage title, or null on an error
1798 public function getSubpage( $text ) {
1799 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1803 * Get a URL-encoded form of the subpage text
1805 * @return string URL-encoded subpage name
1807 public function getSubpageUrlForm() {
1808 $text = $this->getSubpageText();
1809 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1814 * Get a URL-encoded title (not an actual URL) including interwiki
1816 * @return string The URL-encoded form
1818 public function getPrefixedURL() {
1819 $s = $this->prefix( $this->mDbkeyform
);
1820 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1825 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1826 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1827 * second argument named variant. This was deprecated in favor
1828 * of passing an array of option with a "variant" key
1829 * Once $query2 is removed for good, this helper can be dropped
1830 * and the wfArrayToCgi moved to getLocalURL();
1832 * @since 1.19 (r105919)
1833 * @param array|string $query
1834 * @param string|string[]|bool $query2
1837 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1838 if ( $query2 !== false ) {
1839 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1840 "method called with a second parameter is deprecated. Add your " .
1841 "parameter to an array passed as the first parameter.", "1.19" );
1843 if ( is_array( $query ) ) {
1844 $query = wfArrayToCgi( $query );
1847 if ( is_string( $query2 ) ) {
1848 // $query2 is a string, we will consider this to be
1849 // a deprecated $variant argument and add it to the query
1850 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1852 $query2 = wfArrayToCgi( $query2 );
1854 // If we have $query content add a & to it first
1858 // Now append the queries together
1865 * Get a real URL referring to this title, with interwiki link and
1868 * @see self::getLocalURL for the arguments.
1870 * @param string|string[] $query
1871 * @param string|string[]|bool $query2
1872 * @param string|int|null $proto Protocol type to use in URL
1873 * @return string The URL
1875 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1876 $query = self
::fixUrlQueryArgs( $query, $query2 );
1878 # Hand off all the decisions on urls to getLocalURL
1879 $url = $this->getLocalURL( $query );
1881 # Expand the url to make it a full url. Note that getLocalURL has the
1882 # potential to output full urls for a variety of reasons, so we use
1883 # wfExpandUrl instead of simply prepending $wgServer
1884 $url = wfExpandUrl( $url, $proto );
1886 # Finally, add the fragment.
1887 $url .= $this->getFragmentForURL();
1888 // Avoid PHP 7.1 warning from passing $this by reference
1890 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1895 * Get a url appropriate for making redirects based on an untrusted url arg
1897 * This is basically the same as getFullUrl(), but in the case of external
1898 * interwikis, we send the user to a landing page, to prevent possible
1899 * phishing attacks and the like.
1901 * @note Uses current protocol by default, since technically relative urls
1902 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1903 * places where the url gets cached, as might pollute between
1904 * https and non-https users.
1905 * @see self::getLocalURL for the arguments.
1906 * @param array|string $query
1907 * @param string $proto Protocol type to use in URL
1908 * @return string A url suitable to use in an HTTP location header.
1910 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1912 if ( $this->isExternal() ) {
1913 $target = SpecialPage
::getTitleFor(
1915 $this->getPrefixedDBkey()
1918 return $target->getFullURL( $query, false, $proto );
1922 * Get a URL with no fragment or server name (relative URL) from a Title object.
1923 * If this page is generated with action=render, however,
1924 * $wgServer is prepended to make an absolute URL.
1926 * @see self::getFullURL to always get an absolute URL.
1927 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1928 * valid to link, locally, to the current Title.
1929 * @see self::newFromText to produce a Title object.
1931 * @param string|string[] $query An optional query string,
1932 * not used for interwiki links. Can be specified as an associative array as well,
1933 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1934 * Some query patterns will trigger various shorturl path replacements.
1935 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1936 * be an array. If a string is passed it will be interpreted as a deprecated
1937 * variant argument and urlencoded into a variant= argument.
1938 * This second query argument will be added to the $query
1939 * The second parameter is deprecated since 1.19. Pass it as a key,value
1940 * pair in the first parameter array instead.
1942 * @return string String of the URL.
1944 public function getLocalURL( $query = '', $query2 = false ) {
1945 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1947 $query = self
::fixUrlQueryArgs( $query, $query2 );
1949 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1951 $namespace = $this->getNsText();
1952 if ( $namespace != '' ) {
1953 # Can this actually happen? Interwikis shouldn't be parsed.
1954 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1957 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1958 $url = wfAppendQuery( $url, $query );
1960 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1961 if ( $query == '' ) {
1962 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1963 // Avoid PHP 7.1 warning from passing $this by reference
1965 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1967 global $wgVariantArticlePath, $wgActionPaths;
1971 if ( !empty( $wgActionPaths )
1972 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1974 $action = urldecode( $matches[2] );
1975 if ( isset( $wgActionPaths[$action] ) ) {
1976 $query = $matches[1];
1977 if ( isset( $matches[4] ) ) {
1978 $query .= $matches[4];
1980 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1981 if ( $query != '' ) {
1982 $url = wfAppendQuery( $url, $query );
1988 && $wgVariantArticlePath
1989 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1990 && $this->getPageLanguage()->equals(
1991 MediaWikiServices
::getInstance()->getContentLanguage() )
1992 && $this->getPageLanguage()->hasVariants()
1994 $variant = urldecode( $matches[1] );
1995 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1996 // Only do the variant replacement if the given variant is a valid
1997 // variant for the page's language.
1998 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1999 $url = str_replace( '$1', $dbkey, $url );
2003 if ( $url === false ) {
2004 if ( $query == '-' ) {
2007 $url = "{$wgScript}?title={$dbkey}&{$query}";
2010 // Avoid PHP 7.1 warning from passing $this by reference
2012 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2014 // @todo FIXME: This causes breakage in various places when we
2015 // actually expected a local URL and end up with dupe prefixes.
2016 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2017 $url = $wgServer . $url;
2020 // Avoid PHP 7.1 warning from passing $this by reference
2022 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2027 * Get a URL that's the simplest URL that will be valid to link, locally,
2028 * to the current Title. It includes the fragment, but does not include
2029 * the server unless action=render is used (or the link is external). If
2030 * there's a fragment but the prefixed text is empty, we just return a link
2033 * The result obviously should not be URL-escaped, but does need to be
2034 * HTML-escaped if it's being output in HTML.
2036 * @param string|string[] $query
2037 * @param bool $query2
2038 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2039 * or false (default) for no expansion
2040 * @see self::getLocalURL for the arguments.
2041 * @return string The URL
2043 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2044 if ( $this->isExternal() ||
$proto !== false ) {
2045 $ret = $this->getFullURL( $query, $query2, $proto );
2046 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2047 $ret = $this->getFragmentForURL();
2049 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2055 * Get the URL form for an internal link.
2056 * - Used in various CDN-related code, in case we have a different
2057 * internal hostname for the server from the exposed one.
2059 * This uses $wgInternalServer to qualify the path, or $wgServer
2060 * if $wgInternalServer is not set. If the server variable used is
2061 * protocol-relative, the URL will be expanded to http://
2063 * @see self::getLocalURL for the arguments.
2064 * @param string $query
2065 * @param string|bool $query2
2066 * @return string The URL
2068 public function getInternalURL( $query = '', $query2 = false ) {
2069 global $wgInternalServer, $wgServer;
2070 $query = self
::fixUrlQueryArgs( $query, $query2 );
2071 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2072 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2073 // Avoid PHP 7.1 warning from passing $this by reference
2075 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2080 * Get the URL for a canonical link, for use in things like IRC and
2081 * e-mail notifications. Uses $wgCanonicalServer and the
2082 * GetCanonicalURL hook.
2084 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2086 * @see self::getLocalURL for the arguments.
2087 * @param string $query
2088 * @param string|bool $query2
2089 * @return string The URL
2092 public function getCanonicalURL( $query = '', $query2 = false ) {
2093 $query = self
::fixUrlQueryArgs( $query, $query2 );
2094 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2095 // Avoid PHP 7.1 warning from passing $this by reference
2097 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2102 * Get the edit URL for this Title
2104 * @return string The URL, or a null string if this is an interwiki link
2106 public function getEditURL() {
2107 if ( $this->isExternal() ) {
2110 $s = $this->getLocalURL( 'action=edit' );
2116 * Can $user perform $action on this page?
2117 * This skips potentially expensive cascading permission checks
2118 * as well as avoids expensive error formatting
2120 * Suitable for use for nonessential UI controls in common cases, but
2121 * _not_ for functional access control.
2123 * May provide false positives, but should never provide a false negative.
2125 * @param string $action Action that permission needs to be checked for
2126 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2129 public function quickUserCan( $action, $user = null ) {
2130 return $this->userCan( $action, $user, false );
2134 * Can $user perform $action on this page?
2136 * @param string $action Action that permission needs to be checked for
2137 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2139 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2142 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2143 if ( !$user instanceof User
) {
2148 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2152 * Can $user perform $action on this page?
2154 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2156 * @param string $action Action that permission needs to be checked for
2157 * @param User $user User to check
2158 * @param string $rigor One of (quick,full,secure)
2159 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2160 * - full : does cheap and expensive checks possibly from a replica DB
2161 * - secure : does cheap and expensive checks, using the master as needed
2162 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2163 * whose corresponding errors may be ignored.
2164 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2166 public function getUserPermissionsErrors(
2167 $action, $user, $rigor = 'secure', $ignoreErrors = []
2169 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2171 // Remove the errors being ignored.
2172 foreach ( $errors as $index => $error ) {
2173 $errKey = is_array( $error ) ?
$error[0] : $error;
2175 if ( in_array( $errKey, $ignoreErrors ) ) {
2176 unset( $errors[$index] );
2178 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2179 unset( $errors[$index] );
2187 * Permissions checks that fail most often, and which are easiest to test.
2189 * @param string $action The action to check
2190 * @param User $user User to check
2191 * @param array $errors List of current errors
2192 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2193 * @param bool $short Short circuit on first error
2195 * @return array List of errors
2197 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2198 if ( !Hooks
::run( 'TitleQuickPermissions',
2199 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2204 if ( $action == 'create' ) {
2206 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2207 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2209 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2211 } elseif ( $action == 'move' ) {
2212 if ( !$user->isAllowed( 'move-rootuserpages' )
2213 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2214 // Show user page-specific message only if the user can move other pages
2215 $errors[] = [ 'cant-move-user-page' ];
2218 // Check if user is allowed to move files if it's a file
2219 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2220 $errors[] = [ 'movenotallowedfile' ];
2223 // Check if user is allowed to move category pages if it's a category page
2224 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2225 $errors[] = [ 'cant-move-category-page' ];
2228 if ( !$user->isAllowed( 'move' ) ) {
2229 // User can't move anything
2230 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2231 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2232 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2233 // custom message if logged-in users without any special rights can move
2234 $errors[] = [ 'movenologintext' ];
2236 $errors[] = [ 'movenotallowed' ];
2239 } elseif ( $action == 'move-target' ) {
2240 if ( !$user->isAllowed( 'move' ) ) {
2241 // User can't move anything
2242 $errors[] = [ 'movenotallowed' ];
2243 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2244 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2245 // Show user page-specific message only if the user can move other pages
2246 $errors[] = [ 'cant-move-to-user-page' ];
2247 } elseif ( !$user->isAllowed( 'move-categorypages' )
2248 && $this->mNamespace
== NS_CATEGORY
) {
2249 // Show category page-specific message only if the user can move other pages
2250 $errors[] = [ 'cant-move-to-category-page' ];
2252 } elseif ( !$user->isAllowed( $action ) ) {
2253 $errors[] = $this->missingPermissionError( $action, $short );
2260 * Add the resulting error code to the errors array
2262 * @param array $errors List of current errors
2263 * @param array $result Result of errors
2265 * @return array List of errors
2267 private function resultToError( $errors, $result ) {
2268 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2269 // A single array representing an error
2270 $errors[] = $result;
2271 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2272 // A nested array representing multiple errors
2273 $errors = array_merge( $errors, $result );
2274 } elseif ( $result !== '' && is_string( $result ) ) {
2275 // A string representing a message-id
2276 $errors[] = [ $result ];
2277 } elseif ( $result instanceof MessageSpecifier
) {
2278 // A message specifier representing an error
2279 $errors[] = [ $result ];
2280 } elseif ( $result === false ) {
2281 // a generic "We don't want them to do that"
2282 $errors[] = [ 'badaccess-group0' ];
2288 * Check various permission hooks
2290 * @param string $action The action to check
2291 * @param User $user User to check
2292 * @param array $errors List of current errors
2293 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2294 * @param bool $short Short circuit on first error
2296 * @return array List of errors
2298 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2299 // Use getUserPermissionsErrors instead
2301 // Avoid PHP 7.1 warning from passing $this by reference
2303 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2304 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2306 // Check getUserPermissionsErrors hook
2307 // Avoid PHP 7.1 warning from passing $this by reference
2309 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2310 $errors = $this->resultToError( $errors, $result );
2312 // Check getUserPermissionsErrorsExpensive hook
2315 && !( $short && count( $errors ) > 0 )
2316 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2318 $errors = $this->resultToError( $errors, $result );
2325 * Check permissions on special pages & namespaces
2327 * @param string $action The action to check
2328 * @param User $user User to check
2329 * @param array $errors List of current errors
2330 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2331 * @param bool $short Short circuit on first error
2333 * @return array List of errors
2335 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2336 # Only 'createaccount' can be performed on special pages,
2337 # which don't actually exist in the DB.
2338 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2339 $errors[] = [ 'ns-specialprotected' ];
2342 # Check $wgNamespaceProtection for restricted namespaces
2343 if ( $this->isNamespaceProtected( $user ) ) {
2344 $ns = $this->mNamespace
== NS_MAIN ?
2345 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2346 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2347 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2354 * Check sitewide CSS/JSON/JS permissions
2356 * @param string $action The action to check
2357 * @param User $user User to check
2358 * @param array $errors List of current errors
2359 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2360 * @param bool $short Short circuit on first error
2362 * @return array List of errors
2364 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2365 if ( $action != 'patrol' ) {
2367 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2368 // editinterface right. That's implemented as a restriction so no check needed here.
2369 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2370 $error = [ 'sitecssprotected', $action ];
2371 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2372 $error = [ 'sitejsonprotected', $action ];
2373 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2374 $error = [ 'sitejsprotected', $action ];
2375 } elseif ( $this->isRawHtmlMessage() ) {
2376 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2377 if ( !$user->isAllowed( 'editsitejs' ) ) {
2378 $error = [ 'sitejsprotected', $action ];
2379 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2380 $error = [ 'sitecssprotected', $action ];
2385 if ( $user->isAllowed( 'editinterface' ) ) {
2386 // Most users / site admins will probably find out about the new, more restrictive
2387 // permissions by failing to edit something. Give them more info.
2388 // TODO remove this a few release cycles after 1.32
2389 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2399 * Check CSS/JSON/JS sub-page permissions
2401 * @param string $action The action to check
2402 * @param User $user User to check
2403 * @param array $errors List of current errors
2404 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2405 * @param bool $short Short circuit on first error
2407 * @return array List of errors
2409 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2410 # Protect css/json/js subpages of user pages
2411 # XXX: this might be better using restrictions
2413 if ( $action === 'patrol' ) {
2417 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2418 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2420 $this->isUserCssConfigPage()
2421 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2423 $errors[] = [ 'mycustomcssprotected', $action ];
2425 $this->isUserJsonConfigPage()
2426 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2428 $errors[] = [ 'mycustomjsonprotected', $action ];
2430 $this->isUserJsConfigPage()
2431 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2433 $errors[] = [ 'mycustomjsprotected', $action ];
2436 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2437 // deletion/suppression which cannot be used for attacks and we want to avoid the
2438 // situation where an unprivileged user can post abusive content on their subpages
2439 // and only very highly privileged users could remove it.
2440 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2442 $this->isUserCssConfigPage()
2443 && !$user->isAllowed( 'editusercss' )
2445 $errors[] = [ 'customcssprotected', $action ];
2447 $this->isUserJsonConfigPage()
2448 && !$user->isAllowed( 'edituserjson' )
2450 $errors[] = [ 'customjsonprotected', $action ];
2452 $this->isUserJsConfigPage()
2453 && !$user->isAllowed( 'edituserjs' )
2455 $errors[] = [ 'customjsprotected', $action ];
2464 * Check against page_restrictions table requirements on this
2465 * page. The user must possess all required rights for this
2468 * @param string $action The action to check
2469 * @param User $user User to check
2470 * @param array $errors List of current errors
2471 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2472 * @param bool $short Short circuit on first error
2474 * @return array List of errors
2476 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2477 foreach ( $this->getRestrictions( $action ) as $right ) {
2478 // Backwards compatibility, rewrite sysop -> editprotected
2479 if ( $right == 'sysop' ) {
2480 $right = 'editprotected';
2482 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2483 if ( $right == 'autoconfirmed' ) {
2484 $right = 'editsemiprotected';
2486 if ( $right == '' ) {
2489 if ( !$user->isAllowed( $right ) ) {
2490 $errors[] = [ 'protectedpagetext', $right, $action ];
2491 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2492 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2500 * Check restrictions on cascading pages.
2502 * @param string $action The action to check
2503 * @param User $user User to check
2504 * @param array $errors List of current errors
2505 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2506 * @param bool $short Short circuit on first error
2508 * @return array List of errors
2510 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2511 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2512 # We /could/ use the protection level on the source page, but it's
2513 # fairly ugly as we have to establish a precedence hierarchy for pages
2514 # included by multiple cascade-protected pages. So just restrict
2515 # it to people with 'protect' permission, as they could remove the
2516 # protection anyway.
2517 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2518 # Cascading protection depends on more than this page...
2519 # Several cascading protected pages may include this page...
2520 # Check each cascading level
2521 # This is only for protection restrictions, not for all actions
2522 if ( isset( $restrictions[$action] ) ) {
2523 foreach ( $restrictions[$action] as $right ) {
2524 // Backwards compatibility, rewrite sysop -> editprotected
2525 if ( $right == 'sysop' ) {
2526 $right = 'editprotected';
2528 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2529 if ( $right == 'autoconfirmed' ) {
2530 $right = 'editsemiprotected';
2532 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2534 foreach ( $cascadingSources as $page ) {
2535 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2537 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2547 * Check action permissions not already checked in checkQuickPermissions
2549 * @param string $action The action to check
2550 * @param User $user User to check
2551 * @param array $errors List of current errors
2552 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2553 * @param bool $short Short circuit on first error
2555 * @return array List of errors
2557 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2558 global $wgDeleteRevisionsLimit, $wgLang;
2560 if ( $action == 'protect' ) {
2561 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2562 // If they can't edit, they shouldn't protect.
2563 $errors[] = [ 'protect-cantedit' ];
2565 } elseif ( $action == 'create' ) {
2566 $title_protection = $this->getTitleProtection();
2567 if ( $title_protection ) {
2568 if ( $title_protection['permission'] == ''
2569 ||
!$user->isAllowed( $title_protection['permission'] )
2573 User
::whoIs( $title_protection['user'] ),
2574 $title_protection['reason']
2578 } elseif ( $action == 'move' ) {
2579 // Check for immobile pages
2580 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2581 // Specific message for this case
2582 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2583 } elseif ( !$this->isMovable() ) {
2584 // Less specific message for rarer cases
2585 $errors[] = [ 'immobile-source-page' ];
2587 } elseif ( $action == 'move-target' ) {
2588 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2589 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2590 } elseif ( !$this->isMovable() ) {
2591 $errors[] = [ 'immobile-target-page' ];
2593 } elseif ( $action == 'delete' ) {
2594 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2595 if ( !$tempErrors ) {
2596 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2597 $user, $tempErrors, $rigor, true );
2599 if ( $tempErrors ) {
2600 // If protection keeps them from editing, they shouldn't be able to delete.
2601 $errors[] = [ 'deleteprotected' ];
2603 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2604 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2606 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2608 } elseif ( $action === 'undelete' ) {
2609 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2610 // Undeleting implies editing
2611 $errors[] = [ 'undelete-cantedit' ];
2613 if ( !$this->exists()
2614 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2616 // Undeleting where nothing currently exists implies creating
2617 $errors[] = [ 'undelete-cantcreate' ];
2624 * Check that the user isn't blocked from editing.
2626 * @param string $action The action to check
2627 * @param User $user User to check
2628 * @param array $errors List of current errors
2629 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2630 * @param bool $short Short circuit on first error
2632 * @return array List of errors
2634 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2635 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2636 // Account creation blocks handled at userlogin.
2637 // Unblocking handled in SpecialUnblock
2638 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2642 // Optimize for a very common case
2643 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2647 if ( $wgEmailConfirmToEdit
2648 && !$user->isEmailConfirmed()
2649 && $action === 'edit'
2651 $errors[] = [ 'confirmedittext' ];
2654 $useReplica = ( $rigor !== 'secure' );
2655 $block = $user->getBlock( $useReplica );
2657 // If the user does not have a block, or the block they do have explicitly
2658 // allows the action (like "read" or "upload").
2659 if ( !$block ||
$block->appliesToRight( $action ) === false ) {
2663 // Determine if the user is blocked from this action on this page.
2664 // What gets passed into this method is a user right, not an action name.
2665 // There is no way to instantiate an action by restriction. However, this
2666 // will get the action where the restriction is the same. This may result
2667 // in actions being blocked that shouldn't be.
2669 if ( Action
::exists( $action ) ) {
2670 // Clone the title to prevent mutations to this object which is done
2671 // by Title::loadFromRow() in WikiPage::loadFromRow().
2672 $page = WikiPage
::factory( clone $this );
2673 // Creating an action will perform several database queries to ensure that
2674 // the action has not been overridden by the content type.
2675 // @todo FIXME: Pass the relevant context into this function.
2676 $actionObj = Action
::factory( $action, $page, RequestContext
::getMain() );
2677 // Ensure that the retrieved action matches the restriction.
2678 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
2683 // If no action object is returned, assume that the action requires unblock
2684 // which is the default.
2685 if ( !$actionObj ||
$actionObj->requiresUnblock() ) {
2686 if ( $user->isBlockedFrom( $this, $useReplica ) ) {
2687 // @todo FIXME: Pass the relevant context into this function.
2688 $errors[] = $block->getPermissionsError( RequestContext
::getMain() );
2696 * Check that the user is allowed to read this page.
2698 * @param string $action The action to check
2699 * @param User $user User to check
2700 * @param array $errors List of current errors
2701 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2702 * @param bool $short Short circuit on first error
2704 * @return array List of errors
2706 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2707 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2709 $whitelisted = false;
2710 if ( User
::isEveryoneAllowed( 'read' ) ) {
2711 # Shortcut for public wikis, allows skipping quite a bit of code
2712 $whitelisted = true;
2713 } elseif ( $user->isAllowed( 'read' ) ) {
2714 # If the user is allowed to read pages, he is allowed to read all pages
2715 $whitelisted = true;
2716 } elseif ( $this->isSpecial( 'Userlogin' )
2717 ||
$this->isSpecial( 'PasswordReset' )
2718 ||
$this->isSpecial( 'Userlogout' )
2720 # Always grant access to the login page.
2721 # Even anons need to be able to log in.
2722 $whitelisted = true;
2723 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2724 # Time to check the whitelist
2725 # Only do these checks is there's something to check against
2726 $name = $this->getPrefixedText();
2727 $dbName = $this->getPrefixedDBkey();
2729 // Check for explicit whitelisting with and without underscores
2730 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2731 $whitelisted = true;
2732 } elseif ( $this->mNamespace
== NS_MAIN
) {
2733 # Old settings might have the title prefixed with
2734 # a colon for main-namespace pages
2735 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2736 $whitelisted = true;
2738 } elseif ( $this->isSpecialPage() ) {
2739 # If it's a special page, ditch the subpage bit and check again
2740 $name = $this->mDbkeyform
;
2741 list( $name, /* $subpage */ ) =
2742 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
2743 resolveAlias( $name );
2745 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2746 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2747 $whitelisted = true;
2753 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2754 $name = $this->getPrefixedText();
2755 // Check for regex whitelisting
2756 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2757 if ( preg_match( $listItem, $name ) ) {
2758 $whitelisted = true;
2764 if ( !$whitelisted ) {
2765 # If the title is not whitelisted, give extensions a chance to do so...
2766 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2767 if ( !$whitelisted ) {
2768 $errors[] = $this->missingPermissionError( $action, $short );
2776 * Get a description array when the user doesn't have the right to perform
2777 * $action (i.e. when User::isAllowed() returns false)
2779 * @param string $action The action to check
2780 * @param bool $short Short circuit on first error
2781 * @return array Array containing an error message key and any parameters
2783 private function missingPermissionError( $action, $short ) {
2784 // We avoid expensive display logic for quickUserCan's and such
2786 return [ 'badaccess-group0' ];
2789 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2793 * Can $user perform $action on this page? This is an internal function,
2794 * with multiple levels of checks depending on performance needs; see $rigor below.
2795 * It does not check wfReadOnly().
2797 * @param string $action Action that permission needs to be checked for
2798 * @param User $user User to check
2799 * @param string $rigor One of (quick,full,secure)
2800 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2801 * - full : does cheap and expensive checks possibly from a replica DB
2802 * - secure : does cheap and expensive checks, using the master as needed
2803 * @param bool $short Set this to true to stop after the first permission error.
2804 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2806 protected function getUserPermissionsErrorsInternal(
2807 $action, $user, $rigor = 'secure', $short = false
2809 if ( $rigor === true ) {
2810 $rigor = 'secure'; // b/c
2811 } elseif ( $rigor === false ) {
2812 $rigor = 'quick'; // b/c
2813 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2814 throw new Exception( "Invalid rigor parameter '$rigor'." );
2817 # Read has special handling
2818 if ( $action == 'read' ) {
2820 'checkPermissionHooks',
2821 'checkReadPermissions',
2822 'checkUserBlock', // for wgBlockDisablesLogin
2824 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2825 # or checkUserConfigPermissions here as it will lead to duplicate
2826 # error messages. This is okay to do since anywhere that checks for
2827 # create will also check for edit, and those checks are called for edit.
2828 } elseif ( $action == 'create' ) {
2830 'checkQuickPermissions',
2831 'checkPermissionHooks',
2832 'checkPageRestrictions',
2833 'checkCascadingSourcesRestrictions',
2834 'checkActionPermissions',
2839 'checkQuickPermissions',
2840 'checkPermissionHooks',
2841 'checkSpecialsAndNSPermissions',
2842 'checkSiteConfigPermissions',
2843 'checkUserConfigPermissions',
2844 'checkPageRestrictions',
2845 'checkCascadingSourcesRestrictions',
2846 'checkActionPermissions',
2852 foreach ( $checks as $method ) {
2853 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2855 if ( $short && $errors !== [] ) {
2864 * Get a filtered list of all restriction types supported by this wiki.
2865 * @param bool $exists True to get all restriction types that apply to
2866 * titles that do exist, False for all restriction types that apply to
2867 * titles that do not exist
2870 public static function getFilteredRestrictionTypes( $exists = true ) {
2871 global $wgRestrictionTypes;
2872 $types = $wgRestrictionTypes;
2874 # Remove the create restriction for existing titles
2875 $types = array_diff( $types, [ 'create' ] );
2877 # Only the create and upload restrictions apply to non-existing titles
2878 $types = array_intersect( $types, [ 'create', 'upload' ] );
2884 * Returns restriction types for the current Title
2886 * @return array Applicable restriction types
2888 public function getRestrictionTypes() {
2889 if ( $this->isSpecialPage() ) {
2893 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2895 if ( $this->mNamespace
!= NS_FILE
) {
2896 # Remove the upload restriction for non-file titles
2897 $types = array_diff( $types, [ 'upload' ] );
2900 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2902 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2903 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2909 * Is this title subject to title protection?
2910 * Title protection is the one applied against creation of such title.
2912 * @return array|bool An associative array representing any existent title
2913 * protection, or false if there's none.
2915 public function getTitleProtection() {
2916 $protection = $this->getTitleProtectionInternal();
2917 if ( $protection ) {
2918 if ( $protection['permission'] == 'sysop' ) {
2919 $protection['permission'] = 'editprotected'; // B/C
2921 if ( $protection['permission'] == 'autoconfirmed' ) {
2922 $protection['permission'] = 'editsemiprotected'; // B/C
2929 * Fetch title protection settings
2931 * To work correctly, $this->loadRestrictions() needs to have access to the
2932 * actual protections in the database without munging 'sysop' =>
2933 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2934 * callers probably want $this->getTitleProtection() instead.
2936 * @return array|bool
2938 protected function getTitleProtectionInternal() {
2939 // Can't protect pages in special namespaces
2940 if ( $this->mNamespace
< 0 ) {
2944 // Can't protect pages that exist.
2945 if ( $this->exists() ) {
2949 if ( $this->mTitleProtection
=== null ) {
2950 $dbr = wfGetDB( DB_REPLICA
);
2951 $commentStore = CommentStore
::getStore();
2952 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2953 $res = $dbr->select(
2954 [ 'protected_titles' ] +
$commentQuery['tables'],
2956 'user' => 'pt_user',
2957 'expiry' => 'pt_expiry',
2958 'permission' => 'pt_create_perm'
2959 ] +
$commentQuery['fields'],
2960 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2963 $commentQuery['joins']
2966 // fetchRow returns false if there are no rows.
2967 $row = $dbr->fetchRow( $res );
2969 $this->mTitleProtection
= [
2970 'user' => $row['user'],
2971 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2972 'permission' => $row['permission'],
2973 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2976 $this->mTitleProtection
= false;
2979 return $this->mTitleProtection
;
2983 * Remove any title protection due to page existing
2985 public function deleteTitleProtection() {
2986 $dbw = wfGetDB( DB_MASTER
);
2990 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2993 $this->mTitleProtection
= false;
2997 * Is this page "semi-protected" - the *only* protection levels are listed
2998 * in $wgSemiprotectedRestrictionLevels?
3000 * @param string $action Action to check (default: edit)
3003 public function isSemiProtected( $action = 'edit' ) {
3004 global $wgSemiprotectedRestrictionLevels;
3006 $restrictions = $this->getRestrictions( $action );
3007 $semi = $wgSemiprotectedRestrictionLevels;
3008 if ( !$restrictions ||
!$semi ) {
3009 // Not protected, or all protection is full protection
3013 // Remap autoconfirmed to editsemiprotected for BC
3014 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3015 $semi[$key] = 'editsemiprotected';
3017 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3018 $restrictions[$key] = 'editsemiprotected';
3021 return !array_diff( $restrictions, $semi );
3025 * Does the title correspond to a protected article?
3027 * @param string $action The action the page is protected from,
3028 * by default checks all actions.
3031 public function isProtected( $action = '' ) {
3032 global $wgRestrictionLevels;
3034 $restrictionTypes = $this->getRestrictionTypes();
3036 # Special pages have inherent protection
3037 if ( $this->isSpecialPage() ) {
3041 # Check regular protection levels
3042 foreach ( $restrictionTypes as $type ) {
3043 if ( $action == $type ||
$action == '' ) {
3044 $r = $this->getRestrictions( $type );
3045 foreach ( $wgRestrictionLevels as $level ) {
3046 if ( in_array( $level, $r ) && $level != '' ) {
3057 * Determines if $user is unable to edit this page because it has been protected
3058 * by $wgNamespaceProtection.
3060 * @param User $user User object to check permissions
3063 public function isNamespaceProtected( User
$user ) {
3064 global $wgNamespaceProtection;
3066 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3067 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3068 if ( $right != '' && !$user->isAllowed( $right ) ) {
3077 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3079 * @return bool If the page is subject to cascading restrictions.
3081 public function isCascadeProtected() {
3082 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3083 return ( $sources > 0 );
3087 * Determines whether cascading protection sources have already been loaded from
3090 * @param bool $getPages True to check if the pages are loaded, or false to check
3091 * if the status is loaded.
3092 * @return bool Whether or not the specified information has been loaded
3095 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3096 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3100 * Cascading protection: Get the source of any cascading restrictions on this page.
3102 * @param bool $getPages Whether or not to retrieve the actual pages
3103 * that the restrictions have come from and the actual restrictions
3105 * @return array Two elements: First is an array of Title objects of the
3106 * pages from which cascading restrictions have come, false for
3107 * none, or true if such restrictions exist but $getPages was not
3108 * set. Second is an array like that returned by
3109 * Title::getAllRestrictions(), or an empty array if $getPages is
3112 public function getCascadeProtectionSources( $getPages = true ) {
3113 $pagerestrictions = [];
3115 if ( $this->mCascadeSources
!== null && $getPages ) {
3116 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3117 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3118 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3121 $dbr = wfGetDB( DB_REPLICA
);
3123 if ( $this->mNamespace
== NS_FILE
) {
3124 $tables = [ 'imagelinks', 'page_restrictions' ];
3126 'il_to' => $this->mDbkeyform
,
3131 $tables = [ 'templatelinks', 'page_restrictions' ];
3133 'tl_namespace' => $this->mNamespace
,
3134 'tl_title' => $this->mDbkeyform
,
3141 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3142 'pr_expiry', 'pr_type', 'pr_level' ];
3143 $where_clauses[] = 'page_id=pr_page';
3146 $cols = [ 'pr_expiry' ];
3149 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3151 $sources = $getPages ?
[] : false;
3152 $now = wfTimestampNow();
3154 foreach ( $res as $row ) {
3155 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3156 if ( $expiry > $now ) {
3158 $page_id = $row->pr_page
;
3159 $page_ns = $row->page_namespace
;
3160 $page_title = $row->page_title
;
3161 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3162 # Add groups needed for each restriction type if its not already there
3163 # Make sure this restriction type still exists
3165 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3166 $pagerestrictions[$row->pr_type
] = [];
3170 isset( $pagerestrictions[$row->pr_type
] )
3171 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3173 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3182 $this->mCascadeSources
= $sources;
3183 $this->mCascadingRestrictions
= $pagerestrictions;
3185 $this->mHasCascadingRestrictions
= $sources;
3188 return [ $sources, $pagerestrictions ];
3192 * Accessor for mRestrictionsLoaded
3194 * @return bool Whether or not the page's restrictions have already been
3195 * loaded from the database
3198 public function areRestrictionsLoaded() {
3199 return $this->mRestrictionsLoaded
;
3203 * Accessor/initialisation for mRestrictions
3205 * @param string $action Action that permission needs to be checked for
3206 * @return array Restriction levels needed to take the action. All levels are
3207 * required. Note that restriction levels are normally user rights, but 'sysop'
3208 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3209 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3211 public function getRestrictions( $action ) {
3212 if ( !$this->mRestrictionsLoaded
) {
3213 $this->loadRestrictions();
3215 return $this->mRestrictions
[$action] ??
[];
3219 * Accessor/initialisation for mRestrictions
3221 * @return array Keys are actions, values are arrays as returned by
3222 * Title::getRestrictions()
3225 public function getAllRestrictions() {
3226 if ( !$this->mRestrictionsLoaded
) {
3227 $this->loadRestrictions();
3229 return $this->mRestrictions
;
3233 * Get the expiry time for the restriction against a given action
3235 * @param string $action
3236 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3237 * or not protected at all, or false if the action is not recognised.
3239 public function getRestrictionExpiry( $action ) {
3240 if ( !$this->mRestrictionsLoaded
) {
3241 $this->loadRestrictions();
3243 return $this->mRestrictionsExpiry
[$action] ??
false;
3247 * Returns cascading restrictions for the current article
3251 function areRestrictionsCascading() {
3252 if ( !$this->mRestrictionsLoaded
) {
3253 $this->loadRestrictions();
3256 return $this->mCascadeRestriction
;
3260 * Compiles list of active page restrictions from both page table (pre 1.10)
3261 * and page_restrictions table for this existing page.
3262 * Public for usage by LiquidThreads.
3264 * @param array $rows Array of db result objects
3265 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3266 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3267 * Edit and move sections are separated by a colon
3268 * Example: "edit=autoconfirmed,sysop:move=sysop"
3270 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3271 // This function will only read rows from a table that we migrated away
3272 // from before adding READ_LATEST support to loadRestrictions, so we
3273 // don't need to support reading from DB_MASTER here.
3274 $dbr = wfGetDB( DB_REPLICA
);
3276 $restrictionTypes = $this->getRestrictionTypes();
3278 foreach ( $restrictionTypes as $type ) {
3279 $this->mRestrictions
[$type] = [];
3280 $this->mRestrictionsExpiry
[$type] = 'infinity';
3283 $this->mCascadeRestriction
= false;
3285 # Backwards-compatibility: also load the restrictions from the page record (old format).
3286 if ( $oldFashionedRestrictions !== null ) {
3287 $this->mOldRestrictions
= $oldFashionedRestrictions;
3290 if ( $this->mOldRestrictions
=== false ) {
3291 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3292 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3293 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
3296 if ( $this->mOldRestrictions
!= '' ) {
3297 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3298 $temp = explode( '=', trim( $restrict ) );
3299 if ( count( $temp ) == 1 ) {
3300 // old old format should be treated as edit/move restriction
3301 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3302 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3304 $restriction = trim( $temp[1] );
3305 if ( $restriction != '' ) { // some old entries are empty
3306 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3312 if ( count( $rows ) ) {
3313 # Current system - load second to make them override.
3314 $now = wfTimestampNow();
3316 # Cycle through all the restrictions.
3317 foreach ( $rows as $row ) {
3318 // Don't take care of restrictions types that aren't allowed
3319 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3323 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3325 // Only apply the restrictions if they haven't expired!
3326 if ( !$expiry ||
$expiry > $now ) {
3327 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3328 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3330 $this->mCascadeRestriction |
= $row->pr_cascade
;
3335 $this->mRestrictionsLoaded
= true;
3339 * Load restrictions from the page_restrictions table
3341 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3342 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3343 * Edit and move sections are separated by a colon
3344 * Example: "edit=autoconfirmed,sysop:move=sysop"
3345 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3346 * from the master DB.
3348 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3349 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
3350 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
3354 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3355 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3356 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3357 $id = $this->getArticleID();
3359 $fname = __METHOD__
;
3360 $loadRestrictionsFromDb = function ( Database
$dbr ) use ( $fname, $id ) {
3361 return iterator_to_array(
3363 'page_restrictions',
3364 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3365 [ 'pr_page' => $id ],
3371 if ( $readLatest ) {
3372 $dbr = wfGetDB( DB_MASTER
);
3373 $rows = $loadRestrictionsFromDb( $dbr );
3375 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
3376 $rows = $cache->getWithSetCallback(
3377 // Page protections always leave a new null revision
3378 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
3380 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3381 $dbr = wfGetDB( DB_REPLICA
);
3383 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3384 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
3385 if ( $lb->hasOrMadeRecentMasterChanges() ) {
3386 // @TODO: cleanup Title cache and caller assumption mess in general
3387 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
3390 return $loadRestrictionsFromDb( $dbr );
3395 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3397 $title_protection = $this->getTitleProtectionInternal();
3399 if ( $title_protection ) {
3400 $now = wfTimestampNow();
3401 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3403 if ( !$expiry ||
$expiry > $now ) {
3404 // Apply the restrictions
3405 $this->mRestrictionsExpiry
['create'] = $expiry;
3406 $this->mRestrictions
['create'] =
3407 explode( ',', trim( $title_protection['permission'] ) );
3408 } else { // Get rid of the old restrictions
3409 $this->mTitleProtection
= false;
3412 $this->mRestrictionsExpiry
['create'] = 'infinity';
3414 $this->mRestrictionsLoaded
= true;
3419 * Flush the protection cache in this object and force reload from the database.
3420 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3422 public function flushRestrictions() {
3423 $this->mRestrictionsLoaded
= false;
3424 $this->mTitleProtection
= null;
3428 * Purge expired restrictions from the page_restrictions table
3430 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3432 static function purgeExpiredRestrictions() {
3433 if ( wfReadOnly() ) {
3437 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3438 wfGetDB( DB_MASTER
),
3440 function ( IDatabase
$dbw, $fname ) {
3441 $config = MediaWikiServices
::getInstance()->getMainConfig();
3442 $ids = $dbw->selectFieldValues(
3443 'page_restrictions',
3445 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3447 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3450 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3455 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3456 wfGetDB( DB_MASTER
),
3458 function ( IDatabase
$dbw, $fname ) {
3461 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3469 * Does this have subpages? (Warning, usually requires an extra DB query.)
3473 public function hasSubpages() {
3474 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3479 # We dynamically add a member variable for the purpose of this method
3480 # alone to cache the result. There's no point in having it hanging
3481 # around uninitialized in every Title object; therefore we only add it
3482 # if needed and don't declare it statically.
3483 if ( $this->mHasSubpages
=== null ) {
3484 $this->mHasSubpages
= false;
3485 $subpages = $this->getSubpages( 1 );
3486 if ( $subpages instanceof TitleArray
) {
3487 $this->mHasSubpages
= (bool)$subpages->count();
3491 return $this->mHasSubpages
;
3495 * Get all subpages of this page.
3497 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3498 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3499 * doesn't allow subpages
3501 public function getSubpages( $limit = -1 ) {
3502 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3506 $dbr = wfGetDB( DB_REPLICA
);
3507 $conds['page_namespace'] = $this->mNamespace
;
3508 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3510 if ( $limit > -1 ) {
3511 $options['LIMIT'] = $limit;
3513 return TitleArray
::newFromResult(
3514 $dbr->select( 'page',
3515 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3524 * Is there a version of this page in the deletion archive?
3526 * @return int The number of archived revisions
3528 public function isDeleted() {
3529 if ( $this->mNamespace
< 0 ) {
3532 $dbr = wfGetDB( DB_REPLICA
);
3534 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3535 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3538 if ( $this->mNamespace
== NS_FILE
) {
3539 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3540 [ 'fa_name' => $this->mDbkeyform
],
3549 * Is there a version of this page in the deletion archive?
3553 public function isDeletedQuick() {
3554 if ( $this->mNamespace
< 0 ) {
3557 $dbr = wfGetDB( DB_REPLICA
);
3558 $deleted = (bool)$dbr->selectField( 'archive', '1',
3559 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3562 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3563 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3564 [ 'fa_name' => $this->mDbkeyform
],
3572 * Get the article ID for this Title from the link cache,
3573 * adding it if necessary
3575 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3577 * @return int The ID
3579 public function getArticleID( $flags = 0 ) {
3580 if ( $this->mNamespace
< 0 ) {
3581 $this->mArticleID
= 0;
3582 return $this->mArticleID
;
3584 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3585 if ( $flags & self
::GAID_FOR_UPDATE
) {
3586 $oldUpdate = $linkCache->forUpdate( true );
3587 $linkCache->clearLink( $this );
3588 $this->mArticleID
= $linkCache->addLinkObj( $this );
3589 $linkCache->forUpdate( $oldUpdate );
3591 if ( $this->mArticleID
== -1 ) {
3592 $this->mArticleID
= $linkCache->addLinkObj( $this );
3595 return $this->mArticleID
;
3599 * Is this an article that is a redirect page?
3600 * Uses link cache, adding it if necessary
3602 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3605 public function isRedirect( $flags = 0 ) {
3606 if ( !is_null( $this->mRedirect
) ) {
3607 return $this->mRedirect
;
3609 if ( !$this->getArticleID( $flags ) ) {
3610 $this->mRedirect
= false;
3611 return $this->mRedirect
;
3614 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3615 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3616 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3617 if ( $cached === null ) {
3618 # Trust LinkCache's state over our own
3619 # LinkCache is telling us that the page doesn't exist, despite there being cached
3620 # data relating to an existing page in $this->mArticleID. Updaters should clear
3621 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3622 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3623 # LinkCache to refresh its data from the master.
3624 $this->mRedirect
= false;
3625 return $this->mRedirect
;
3628 $this->mRedirect
= (bool)$cached;
3630 return $this->mRedirect
;
3634 * What is the length of this page?
3635 * Uses link cache, adding it if necessary
3637 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3640 public function getLength( $flags = 0 ) {
3641 if ( $this->mLength
!= -1 ) {
3642 return $this->mLength
;
3644 if ( !$this->getArticleID( $flags ) ) {
3646 return $this->mLength
;
3648 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3649 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3650 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3651 if ( $cached === null ) {
3652 # Trust LinkCache's state over our own, as for isRedirect()
3654 return $this->mLength
;
3657 $this->mLength
= intval( $cached );
3659 return $this->mLength
;
3663 * What is the page_latest field for this page?
3665 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3666 * @return int Int or 0 if the page doesn't exist
3668 public function getLatestRevID( $flags = 0 ) {
3669 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3670 return intval( $this->mLatestID
);
3672 if ( !$this->getArticleID( $flags ) ) {
3673 $this->mLatestID
= 0;
3674 return $this->mLatestID
;
3676 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3677 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3678 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3679 if ( $cached === null ) {
3680 # Trust LinkCache's state over our own, as for isRedirect()
3681 $this->mLatestID
= 0;
3682 return $this->mLatestID
;
3685 $this->mLatestID
= intval( $cached );
3687 return $this->mLatestID
;
3691 * This clears some fields in this object, and clears any associated
3692 * keys in the "bad links" section of the link cache.
3694 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3695 * loading of the new page_id. It's also called from
3696 * WikiPage::doDeleteArticleReal()
3698 * @param int $newid The new Article ID
3700 public function resetArticleID( $newid ) {
3701 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3702 $linkCache->clearLink( $this );
3704 if ( $newid === false ) {
3705 $this->mArticleID
= -1;
3707 $this->mArticleID
= intval( $newid );
3709 $this->mRestrictionsLoaded
= false;
3710 $this->mRestrictions
= [];
3711 $this->mOldRestrictions
= false;
3712 $this->mRedirect
= null;
3713 $this->mLength
= -1;
3714 $this->mLatestID
= false;
3715 $this->mContentModel
= false;
3716 $this->mEstimateRevisions
= null;
3717 $this->mPageLanguage
= false;
3718 $this->mDbPageLanguage
= false;
3719 $this->mIsBigDeletion
= null;
3722 public static function clearCaches() {
3723 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3724 $linkCache->clear();
3726 $titleCache = self
::getTitleCache();
3727 $titleCache->clear();
3731 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3733 * @param string $text Containing title to capitalize
3734 * @param int $ns Namespace index, defaults to NS_MAIN
3735 * @return string Containing capitalized title
3737 public static function capitalize( $text, $ns = NS_MAIN
) {
3738 if ( MWNamespace
::isCapitalized( $ns ) ) {
3739 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3746 * Secure and split - main initialisation function for this object
3748 * Assumes that mDbkeyform has been set, and is urldecoded
3749 * and uses underscores, but not otherwise munged. This function
3750 * removes illegal characters, splits off the interwiki and
3751 * namespace prefixes, sets the other forms, and canonicalizes
3754 * @throws MalformedTitleException On invalid titles
3755 * @return bool True on success
3757 private function secureAndSplit() {
3758 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3759 // the parsing code with Title, while avoiding massive refactoring.
3760 // @todo: get rid of secureAndSplit, refactor parsing code.
3761 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3762 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3763 /** @var MediaWikiTitleCodec $titleCodec */
3764 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3765 // MalformedTitleException can be thrown here
3766 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3769 $this->setFragment( '#' . $parts['fragment'] );
3770 $this->mInterwiki
= $parts['interwiki'];
3771 $this->mLocalInterwiki
= $parts['local_interwiki'];
3772 $this->mNamespace
= $parts['namespace'];
3773 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3775 $this->mDbkeyform
= $parts['dbkey'];
3776 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3777 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3779 # We already know that some pages won't be in the database!
3780 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3781 $this->mArticleID
= 0;
3788 * Get an array of Title objects linking to this Title
3789 * Also stores the IDs in the link cache.
3791 * WARNING: do not use this function on arbitrary user-supplied titles!
3792 * On heavily-used templates it will max out the memory.
3794 * @param array $options May be FOR UPDATE
3795 * @param string $table Table name
3796 * @param string $prefix Fields prefix
3797 * @return Title[] Array of Title objects linking here
3799 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3800 if ( count( $options ) > 0 ) {
3801 $db = wfGetDB( DB_MASTER
);
3803 $db = wfGetDB( DB_REPLICA
);
3808 self
::getSelectFields(),
3810 "{$prefix}_from=page_id",
3811 "{$prefix}_namespace" => $this->mNamespace
,
3812 "{$prefix}_title" => $this->mDbkeyform
],
3818 if ( $res->numRows() ) {
3819 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3820 foreach ( $res as $row ) {
3821 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3823 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3824 $retVal[] = $titleObj;
3832 * Get an array of Title objects using this Title as a template
3833 * Also stores the IDs in the link cache.
3835 * WARNING: do not use this function on arbitrary user-supplied titles!
3836 * On heavily-used templates it will max out the memory.
3838 * @param array $options Query option to Database::select()
3839 * @return Title[] Array of Title the Title objects linking here
3841 public function getTemplateLinksTo( $options = [] ) {
3842 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3846 * Get an array of Title objects linked from this Title
3847 * Also stores the IDs in the link cache.
3849 * WARNING: do not use this function on arbitrary user-supplied titles!
3850 * On heavily-used templates it will max out the memory.
3852 * @param array $options Query option to Database::select()
3853 * @param string $table Table name
3854 * @param string $prefix Fields prefix
3855 * @return array Array of Title objects linking here
3857 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3858 $id = $this->getArticleID();
3860 # If the page doesn't exist; there can't be any link from this page
3865 $db = wfGetDB( DB_REPLICA
);
3867 $blNamespace = "{$prefix}_namespace";
3868 $blTitle = "{$prefix}_title";
3870 $pageQuery = WikiPage
::getQueryInfo();
3872 [ $table, 'nestpage' => $pageQuery['tables'] ],
3874 [ $blNamespace, $blTitle ],
3875 $pageQuery['fields']
3877 [ "{$prefix}_from" => $id ],
3882 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3883 ] ] +
$pageQuery['joins']
3887 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3888 foreach ( $res as $row ) {
3889 if ( $row->page_id
) {
3890 $titleObj = self
::newFromRow( $row );
3892 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3893 $linkCache->addBadLinkObj( $titleObj );
3895 $retVal[] = $titleObj;
3902 * Get an array of Title objects used on this Title as a template
3903 * Also stores the IDs in the link cache.
3905 * WARNING: do not use this function on arbitrary user-supplied titles!
3906 * On heavily-used templates it will max out the memory.
3908 * @param array $options May be FOR UPDATE
3909 * @return Title[] Array of Title the Title objects used here
3911 public function getTemplateLinksFrom( $options = [] ) {
3912 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3916 * Get an array of Title objects referring to non-existent articles linked
3919 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3920 * should use redirect table in this case).
3921 * @return Title[] Array of Title the Title objects
3923 public function getBrokenLinksFrom() {
3924 if ( $this->getArticleID() == 0 ) {
3925 # All links from article ID 0 are false positives
3929 $dbr = wfGetDB( DB_REPLICA
);
3930 $res = $dbr->select(
3931 [ 'page', 'pagelinks' ],
3932 [ 'pl_namespace', 'pl_title' ],
3934 'pl_from' => $this->getArticleID(),
3935 'page_namespace IS NULL'
3941 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3947 foreach ( $res as $row ) {
3948 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3954 * Get a list of URLs to purge from the CDN cache when this
3957 * @return string[] Array of String the URLs
3959 public function getCdnUrls() {
3961 $this->getInternalURL(),
3962 $this->getInternalURL( 'action=history' )
3965 $pageLang = $this->getPageLanguage();
3966 if ( $pageLang->hasVariants() ) {
3967 $variants = $pageLang->getVariants();
3968 foreach ( $variants as $vCode ) {
3969 $urls[] = $this->getInternalURL( $vCode );
3973 // If we are looking at a css/js user subpage, purge the action=raw.
3974 if ( $this->isUserJsConfigPage() ) {
3975 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3976 } elseif ( $this->isUserJsonConfigPage() ) {
3977 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3978 } elseif ( $this->isUserCssConfigPage() ) {
3979 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3982 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3987 * Purge all applicable CDN URLs
3989 public function purgeSquid() {
3990 DeferredUpdates
::addUpdate(
3991 new CdnCacheUpdate( $this->getCdnUrls() ),
3992 DeferredUpdates
::PRESEND
3997 * Check whether a given move operation would be valid.
3998 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
4000 * @deprecated since 1.25, use MovePage's methods instead
4001 * @param Title &$nt The new title
4002 * @param bool $auth Whether to check user permissions (uses $wgUser)
4003 * @param string $reason Is the log summary of the move, used for spam checking
4004 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4006 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4009 if ( !( $nt instanceof Title
) ) {
4010 // Normally we'd add this to $errors, but we'll get
4011 // lots of syntax errors if $nt is not an object
4012 return [ [ 'badtitletext' ] ];
4015 $mp = new MovePage( $this, $nt );
4016 $errors = $mp->isValidMove()->getErrorsArray();
4018 $errors = wfMergeErrorArrays(
4020 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4024 return $errors ?
: true;
4028 * Move a title to a new location
4030 * @deprecated since 1.25, use the MovePage class instead
4031 * @param Title &$nt The new title
4032 * @param bool $auth Indicates whether $wgUser's permissions
4034 * @param string $reason The reason for the move
4035 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4036 * Ignored if the user doesn't have the suppressredirect right.
4037 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4038 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4040 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4041 array $changeTags = []
4044 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4045 if ( is_array( $err ) ) {
4046 // Auto-block user's IP if the account was "hard" blocked
4047 $wgUser->spreadAnyEditBlock();
4050 // Check suppressredirect permission
4051 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4052 $createRedirect = true;
4055 $mp = new MovePage( $this, $nt );
4056 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4057 if ( $status->isOK() ) {
4060 return $status->getErrorsArray();
4065 * Move this page's subpages to be subpages of $nt
4067 * @param Title $nt Move target
4068 * @param bool $auth Whether $wgUser's permissions should be checked
4069 * @param string $reason The reason for the move
4070 * @param bool $createRedirect Whether to create redirects from the old subpages to
4071 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4072 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4073 * @return array Array with old page titles as keys, and strings (new page titles) or
4074 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4075 * getUserPermissionsErrors()-like error array with numeric indices if
4076 * no pages were moved
4078 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4079 array $changeTags = []
4081 global $wgMaximumMovedPages;
4082 // Check permissions
4083 if ( !$this->userCan( 'move-subpages' ) ) {
4085 [ 'cant-move-subpages' ],
4088 // Do the source and target namespaces support subpages?
4089 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4091 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4094 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4096 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4100 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4103 foreach ( $subpages as $oldSubpage ) {
4105 if ( $count > $wgMaximumMovedPages ) {
4106 $retval[$oldSubpage->getPrefixedText()] = [
4107 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4112 // We don't know whether this function was called before
4113 // or after moving the root page, so check both
4115 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4116 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4118 // When moving a page to a subpage of itself,
4119 // don't move it twice
4122 $newPageName = preg_replace(
4123 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4124 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4125 $oldSubpage->getDBkey() );
4126 if ( $oldSubpage->isTalkPage() ) {
4127 $newNs = $nt->getTalkPage()->getNamespace();
4129 $newNs = $nt->getSubjectPage()->getNamespace();
4131 # T16385: we need makeTitleSafe because the new page names may
4132 # be longer than 255 characters.
4133 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4135 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4136 if ( $success === true ) {
4137 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4139 $retval[$oldSubpage->getPrefixedText()] = $success;
4146 * Checks if this page is just a one-rev redirect.
4147 * Adds lock, so don't use just for light purposes.
4151 public function isSingleRevRedirect() {
4152 global $wgContentHandlerUseDB;
4154 $dbw = wfGetDB( DB_MASTER
);
4157 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4158 if ( $wgContentHandlerUseDB ) {
4159 $fields[] = 'page_content_model';
4162 $row = $dbw->selectRow( 'page',
4168 # Cache some fields we may want
4169 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4170 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4171 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4172 $this->mContentModel
= $row && isset( $row->page_content_model
)
4173 ?
strval( $row->page_content_model
)
4176 if ( !$this->mRedirect
) {
4179 # Does the article have a history?
4180 $row = $dbw->selectField( [ 'page', 'revision' ],
4182 [ 'page_namespace' => $this->mNamespace
,
4183 'page_title' => $this->mDbkeyform
,
4185 'page_latest != rev_id'
4190 # Return true if there was no history
4191 return ( $row === false );
4195 * Checks if $this can be moved to a given Title
4196 * - Selects for update, so don't call it unless you mean business
4198 * @deprecated since 1.25, use MovePage's methods instead
4199 * @param Title $nt The new title to check
4202 public function isValidMoveTarget( $nt ) {
4203 # Is it an existing file?
4204 if ( $nt->getNamespace() == NS_FILE
) {
4205 $file = wfLocalFile( $nt );
4206 $file->load( File
::READ_LATEST
);
4207 if ( $file->exists() ) {
4208 wfDebug( __METHOD__
. ": file exists\n" );
4212 # Is it a redirect with no history?
4213 if ( !$nt->isSingleRevRedirect() ) {
4214 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4217 # Get the article text
4218 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4219 if ( !is_object( $rev ) ) {
4222 $content = $rev->getContent();
4223 # Does the redirect point to the source?
4224 # Or is it a broken self-redirect, usually caused by namespace collisions?
4225 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4227 if ( $redirTitle ) {
4228 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4229 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4230 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4236 # Fail safe (not a redirect after all. strange.)
4237 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4238 " is a redirect, but it doesn't contain a valid redirect.\n" );
4244 * Get categories to which this Title belongs and return an array of
4245 * categories' names.
4247 * @return array Array of parents in the form:
4248 * $parent => $currentarticle
4250 public function getParentCategories() {
4253 $titleKey = $this->getArticleID();
4255 if ( $titleKey === 0 ) {
4259 $dbr = wfGetDB( DB_REPLICA
);
4261 $res = $dbr->select(
4264 [ 'cl_from' => $titleKey ],
4268 if ( $res->numRows() > 0 ) {
4269 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4270 foreach ( $res as $row ) {
4271 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4272 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4273 $this->getFullText();
4280 * Get a tree of parent categories
4282 * @param array $children Array with the children in the keys, to check for circular refs
4283 * @return array Tree of parent categories
4285 public function getParentCategoryTree( $children = [] ) {
4287 $parents = $this->getParentCategories();
4290 foreach ( $parents as $parent => $current ) {
4291 if ( array_key_exists( $parent, $children ) ) {
4292 # Circular reference
4293 $stack[$parent] = [];
4295 $nt = self
::newFromText( $parent );
4297 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4307 * Get an associative array for selecting this title from
4310 * @return array Array suitable for the $where parameter of DB::select()
4312 public function pageCond() {
4313 if ( $this->mArticleID
> 0 ) {
4314 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4315 return [ 'page_id' => $this->mArticleID
];
4317 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4322 * Get next/previous revision ID relative to another revision ID
4323 * @param int $revId Revision ID. Get the revision that was before this one.
4324 * @param int $flags Title::GAID_FOR_UPDATE
4325 * @param string $dir 'next' or 'prev'
4326 * @return int|bool New revision ID, or false if none exists
4328 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4329 $revId = (int)$revId;
4330 if ( $dir === 'next' ) {
4333 } elseif ( $dir === 'prev' ) {
4337 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4340 if ( $flags & self
::GAID_FOR_UPDATE
) {
4341 $db = wfGetDB( DB_MASTER
);
4343 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4346 // Intentionally not caring if the specified revision belongs to this
4347 // page. We only care about the timestamp.
4348 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4349 if ( $ts === false ) {
4350 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4351 if ( $ts === false ) {
4352 // Or should this throw an InvalidArgumentException or something?
4356 $ts = $db->addQuotes( $ts );
4358 $revId = $db->selectField( 'revision', 'rev_id',
4360 'rev_page' => $this->getArticleID( $flags ),
4361 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4365 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4366 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4370 if ( $revId === false ) {
4373 return intval( $revId );
4378 * Get the revision ID of the previous revision
4380 * @param int $revId Revision ID. Get the revision that was before this one.
4381 * @param int $flags Title::GAID_FOR_UPDATE
4382 * @return int|bool Old revision ID, or false if none exists
4384 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4385 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4389 * Get the revision ID of the next revision
4391 * @param int $revId Revision ID. Get the revision that was after this one.
4392 * @param int $flags Title::GAID_FOR_UPDATE
4393 * @return int|bool Next revision ID, or false if none exists
4395 public function getNextRevisionID( $revId, $flags = 0 ) {
4396 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4400 * Get the first revision of the page
4402 * @param int $flags Title::GAID_FOR_UPDATE
4403 * @return Revision|null If page doesn't exist
4405 public function getFirstRevision( $flags = 0 ) {
4406 $pageId = $this->getArticleID( $flags );
4408 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4409 $revQuery = Revision
::getQueryInfo();
4410 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4411 [ 'rev_page' => $pageId ],
4414 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4415 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4420 return new Revision( $row, 0, $this );
4427 * Get the oldest revision timestamp of this page
4429 * @param int $flags Title::GAID_FOR_UPDATE
4430 * @return string|null MW timestamp
4432 public function getEarliestRevTime( $flags = 0 ) {
4433 $rev = $this->getFirstRevision( $flags );
4434 return $rev ?
$rev->getTimestamp() : null;
4438 * Check if this is a new page
4442 public function isNewPage() {
4443 $dbr = wfGetDB( DB_REPLICA
);
4444 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4448 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4452 public function isBigDeletion() {
4453 global $wgDeleteRevisionsLimit;
4455 if ( !$wgDeleteRevisionsLimit ) {
4459 if ( $this->mIsBigDeletion
=== null ) {
4460 $dbr = wfGetDB( DB_REPLICA
);
4462 $revCount = $dbr->selectRowCount(
4465 [ 'rev_page' => $this->getArticleID() ],
4467 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4470 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4473 return $this->mIsBigDeletion
;
4477 * Get the approximate revision count of this page.
4481 public function estimateRevisionCount() {
4482 if ( !$this->exists() ) {
4486 if ( $this->mEstimateRevisions
=== null ) {
4487 $dbr = wfGetDB( DB_REPLICA
);
4488 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4489 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4492 return $this->mEstimateRevisions
;
4496 * Get the number of revisions between the given revision.
4497 * Used for diffs and other things that really need it.
4499 * @param int|Revision $old Old revision or rev ID (first before range)
4500 * @param int|Revision $new New revision or rev ID (first after range)
4501 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4502 * @return int Number of revisions between these revisions.
4504 public function countRevisionsBetween( $old, $new, $max = null ) {
4505 if ( !( $old instanceof Revision
) ) {
4506 $old = Revision
::newFromTitle( $this, (int)$old );
4508 if ( !( $new instanceof Revision
) ) {
4509 $new = Revision
::newFromTitle( $this, (int)$new );
4511 if ( !$old ||
!$new ) {
4512 return 0; // nothing to compare
4514 $dbr = wfGetDB( DB_REPLICA
);
4516 'rev_page' => $this->getArticleID(),
4517 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4518 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4520 if ( $max !== null ) {
4521 return $dbr->selectRowCount( 'revision', '1',
4524 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4527 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4532 * Get the authors between the given revisions or revision IDs.
4533 * Used for diffs and other things that really need it.
4537 * @param int|Revision $old Old revision or rev ID (first before range by default)
4538 * @param int|Revision $new New revision or rev ID (first after range by default)
4539 * @param int $limit Maximum number of authors
4540 * @param string|array $options (Optional): Single option, or an array of options:
4541 * 'include_old' Include $old in the range; $new is excluded.
4542 * 'include_new' Include $new in the range; $old is excluded.
4543 * 'include_both' Include both $old and $new in the range.
4544 * Unknown option values are ignored.
4545 * @return array|null Names of revision authors in the range; null if not both revisions exist
4547 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4548 if ( !( $old instanceof Revision
) ) {
4549 $old = Revision
::newFromTitle( $this, (int)$old );
4551 if ( !( $new instanceof Revision
) ) {
4552 $new = Revision
::newFromTitle( $this, (int)$new );
4554 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4555 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4556 // in the sanity check below?
4557 if ( !$old ||
!$new ) {
4558 return null; // nothing to compare
4563 $options = (array)$options;
4564 if ( in_array( 'include_old', $options ) ) {
4567 if ( in_array( 'include_new', $options ) ) {
4570 if ( in_array( 'include_both', $options ) ) {
4574 // No DB query needed if $old and $new are the same or successive revisions:
4575 if ( $old->getId() === $new->getId() ) {
4576 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4578 [ $old->getUserText( Revision
::RAW
) ];
4579 } elseif ( $old->getId() === $new->getParentId() ) {
4580 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4581 $authors[] = $old->getUserText( Revision
::RAW
);
4582 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4583 $authors[] = $new->getUserText( Revision
::RAW
);
4585 } elseif ( $old_cmp === '>=' ) {
4586 $authors[] = $old->getUserText( Revision
::RAW
);
4587 } elseif ( $new_cmp === '<=' ) {
4588 $authors[] = $new->getUserText( Revision
::RAW
);
4592 $dbr = wfGetDB( DB_REPLICA
);
4593 $revQuery = Revision
::getQueryInfo();
4594 $authors = $dbr->selectFieldValues(
4595 $revQuery['tables'],
4596 $revQuery['fields']['rev_user_text'],
4598 'rev_page' => $this->getArticleID(),
4599 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4600 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4602 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4609 * Get the number of authors between the given revisions or revision IDs.
4610 * Used for diffs and other things that really need it.
4612 * @param int|Revision $old Old revision or rev ID (first before range by default)
4613 * @param int|Revision $new New revision or rev ID (first after range by default)
4614 * @param int $limit Maximum number of authors
4615 * @param string|array $options (Optional): Single option, or an array of options:
4616 * 'include_old' Include $old in the range; $new is excluded.
4617 * 'include_new' Include $new in the range; $old is excluded.
4618 * 'include_both' Include both $old and $new in the range.
4619 * Unknown option values are ignored.
4620 * @return int Number of revision authors in the range; zero if not both revisions exist
4622 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4623 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4624 return $authors ?
count( $authors ) : 0;
4628 * Compare with another title.
4630 * @param Title $title
4633 public function equals( Title
$title ) {
4634 // Note: === is necessary for proper matching of number-like titles.
4635 return $this->mInterwiki
=== $title->mInterwiki
4636 && $this->mNamespace
== $title->mNamespace
4637 && $this->mDbkeyform
=== $title->mDbkeyform
;
4641 * Check if this title is a subpage of another title
4643 * @param Title $title
4646 public function isSubpageOf( Title
$title ) {
4647 return $this->mInterwiki
=== $title->mInterwiki
4648 && $this->mNamespace
== $title->mNamespace
4649 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4653 * Check if page exists. For historical reasons, this function simply
4654 * checks for the existence of the title in the page table, and will
4655 * thus return false for interwiki links, special pages and the like.
4656 * If you want to know if a title can be meaningfully viewed, you should
4657 * probably call the isKnown() method instead.
4659 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4660 * from master/for update
4663 public function exists( $flags = 0 ) {
4664 $exists = $this->getArticleID( $flags ) != 0;
4665 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4670 * Should links to this title be shown as potentially viewable (i.e. as
4671 * "bluelinks"), even if there's no record by this title in the page
4674 * This function is semi-deprecated for public use, as well as somewhat
4675 * misleadingly named. You probably just want to call isKnown(), which
4676 * calls this function internally.
4678 * (ISSUE: Most of these checks are cheap, but the file existence check
4679 * can potentially be quite expensive. Including it here fixes a lot of
4680 * existing code, but we might want to add an optional parameter to skip
4681 * it and any other expensive checks.)
4685 public function isAlwaysKnown() {
4689 * Allows overriding default behavior for determining if a page exists.
4690 * If $isKnown is kept as null, regular checks happen. If it's
4691 * a boolean, this value is returned by the isKnown method.
4695 * @param Title $title
4696 * @param bool|null $isKnown
4698 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4700 if ( !is_null( $isKnown ) ) {
4704 if ( $this->isExternal() ) {
4705 return true; // any interwiki link might be viewable, for all we know
4708 switch ( $this->mNamespace
) {
4711 // file exists, possibly in a foreign repo
4712 return (bool)wfFindFile( $this );
4714 // valid special page
4715 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4716 exists( $this->mDbkeyform
);
4718 // selflink, possibly with fragment
4719 return $this->mDbkeyform
== '';
4721 // known system message
4722 return $this->hasSourceText() !== false;
4729 * Does this title refer to a page that can (or might) be meaningfully
4730 * viewed? In particular, this function may be used to determine if
4731 * links to the title should be rendered as "bluelinks" (as opposed to
4732 * "redlinks" to non-existent pages).
4733 * Adding something else to this function will cause inconsistency
4734 * since LinkHolderArray calls isAlwaysKnown() and does its own
4735 * page existence check.
4739 public function isKnown() {
4740 return $this->isAlwaysKnown() ||
$this->exists();
4744 * Does this page have source text?
4748 public function hasSourceText() {
4749 if ( $this->exists() ) {
4753 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4754 // If the page doesn't exist but is a known system message, default
4755 // message content will be displayed, same for language subpages-
4756 // Use always content language to avoid loading hundreds of languages
4757 // to get the link color.
4758 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4759 list( $name, ) = MessageCache
::singleton()->figureMessage(
4760 $contLang->lcfirst( $this->getText() )
4762 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4763 return $message->exists();
4770 * Get the default (plain) message contents for an page that overrides an
4771 * interface message key.
4773 * Primary use cases:
4776 * - Show default when viewing the page. The Article::getSubstituteContent
4777 * method displays the default message content, instead of the
4778 * 'noarticletext' placeholder message normally used.
4781 * - Title of edit page. When creating an interface message override,
4782 * the editor is told they are "Editing the page", instead of
4783 * "Creating the page". (EditPage::setHeaders)
4784 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4785 * or editing a an interface message override. (EditPage::showIntro)
4786 * - Opening the editor. The contents of the localisation message are used
4787 * as contents of the editor when creating a new page in the MediaWiki
4788 * namespace. This simplifies the process for editors when "changing"
4789 * an interface message by creating an override. (EditPage::getContentObject)
4790 * - Showing a diff. The left-hand side of a diff when an editor is
4791 * previewing their changes before saving the creation of a page in the
4792 * MediaWiki namespace. (EditPage::showDiff)
4793 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4794 * page with the proposed content matching the interface message default,
4795 * the save is rejected, the same way we disallow blank pages from being
4796 * created. (EditPage::internalAttemptSave)
4799 * - Default content, when using the 'prepend' or 'append' feature.
4802 * - Label the create action as "Edit", if the page can be an override.
4804 * @return string|bool
4806 public function getDefaultMessageText() {
4807 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4811 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4812 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4814 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4816 if ( $message->exists() ) {
4817 return $message->plain();
4824 * Updates page_touched for this page; called from LinksUpdate.php
4826 * @param string|null $purgeTime [optional] TS_MW timestamp
4827 * @return bool True if the update succeeded
4829 public function invalidateCache( $purgeTime = null ) {
4830 if ( wfReadOnly() ) {
4832 } elseif ( $this->mArticleID
=== 0 ) {
4833 return true; // avoid gap locking if we know it's not there
4836 $dbw = wfGetDB( DB_MASTER
);
4837 $dbw->onTransactionPreCommitOrIdle(
4838 function () use ( $dbw ) {
4839 ResourceLoaderWikiModule
::invalidateModuleCache(
4840 $this, null, null, $dbw->getDomainID() );
4845 $conds = $this->pageCond();
4846 DeferredUpdates
::addUpdate(
4847 new AutoCommitUpdate(
4850 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4851 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4854 [ 'page_touched' => $dbTimestamp ],
4855 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4858 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4861 DeferredUpdates
::PRESEND
4868 * Update page_touched timestamps and send CDN purge messages for
4869 * pages linking to this title. May be sent to the job queue depending
4870 * on the number of links. Typically called on create and delete.
4872 public function touchLinks() {
4873 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4874 if ( $this->mNamespace
== NS_CATEGORY
) {
4875 DeferredUpdates
::addUpdate(
4876 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4882 * Get the last touched timestamp
4884 * @param IDatabase|null $db
4885 * @return string|false Last-touched timestamp
4887 public function getTouched( $db = null ) {
4888 if ( $db === null ) {
4889 $db = wfGetDB( DB_REPLICA
);
4891 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4896 * Get the timestamp when this page was updated since the user last saw it.
4898 * @param User|null $user
4899 * @return string|null
4901 public function getNotificationTimestamp( $user = null ) {
4904 // Assume current user if none given
4908 // Check cache first
4909 $uid = $user->getId();
4913 // avoid isset here, as it'll return false for null entries
4914 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4915 return $this->mNotificationTimestamp
[$uid];
4917 // Don't cache too much!
4918 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4919 $this->mNotificationTimestamp
= [];
4922 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4923 $watchedItem = $store->getWatchedItem( $user, $this );
4924 if ( $watchedItem ) {
4925 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4927 $this->mNotificationTimestamp
[$uid] = false;
4930 return $this->mNotificationTimestamp
[$uid];
4934 * Generate strings used for xml 'id' names in monobook tabs
4936 * @param string $prepend Defaults to 'nstab-'
4937 * @return string XML 'id' name
4939 public function getNamespaceKey( $prepend = 'nstab-' ) {
4940 // Gets the subject namespace of this title
4941 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4942 // Prefer canonical namespace name for HTML IDs
4943 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4944 if ( $namespaceKey === false ) {
4945 // Fallback to localised text
4946 $namespaceKey = $this->getSubjectNsText();
4948 // Makes namespace key lowercase
4949 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4951 if ( $namespaceKey == '' ) {
4952 $namespaceKey = 'main';
4954 // Changes file to image for backwards compatibility
4955 if ( $namespaceKey == 'file' ) {
4956 $namespaceKey = 'image';
4958 return $prepend . $namespaceKey;
4962 * Get all extant redirects to this Title
4964 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4965 * @return Title[] Array of Title redirects to this title
4967 public function getRedirectsHere( $ns = null ) {
4970 $dbr = wfGetDB( DB_REPLICA
);
4972 'rd_namespace' => $this->mNamespace
,
4973 'rd_title' => $this->mDbkeyform
,
4976 if ( $this->isExternal() ) {
4977 $where['rd_interwiki'] = $this->mInterwiki
;
4979 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4981 if ( !is_null( $ns ) ) {
4982 $where['page_namespace'] = $ns;
4985 $res = $dbr->select(
4986 [ 'redirect', 'page' ],
4987 [ 'page_namespace', 'page_title' ],
4992 foreach ( $res as $row ) {
4993 $redirs[] = self
::newFromRow( $row );
4999 * Check if this Title is a valid redirect target
5003 public function isValidRedirectTarget() {
5004 global $wgInvalidRedirectTargets;
5006 if ( $this->isSpecialPage() ) {
5007 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5008 if ( $this->isSpecial( 'Userlogout' ) ) {
5012 foreach ( $wgInvalidRedirectTargets as $target ) {
5013 if ( $this->isSpecial( $target ) ) {
5023 * Get a backlink cache object
5025 * @return BacklinkCache
5027 public function getBacklinkCache() {
5028 return BacklinkCache
::get( $this );
5032 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5036 public function canUseNoindex() {
5037 global $wgExemptFromUserRobotsControl;
5039 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
5041 return !in_array( $this->mNamespace
, $bannedNamespaces );
5045 * Returns the raw sort key to be used for categories, with the specified
5046 * prefix. This will be fed to Collation::getSortKey() to get a
5047 * binary sortkey that can be used for actual sorting.
5049 * @param string $prefix The prefix to be used, specified using
5050 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5054 public function getCategorySortkey( $prefix = '' ) {
5055 $unprefixed = $this->getText();
5057 // Anything that uses this hook should only depend
5058 // on the Title object passed in, and should probably
5059 // tell the users to run updateCollations.php --force
5060 // in order to re-sort existing category relations.
5061 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5062 if ( $prefix !== '' ) {
5063 # Separate with a line feed, so the unprefixed part is only used as
5064 # a tiebreaker when two pages have the exact same prefix.
5065 # In UCA, tab is the only character that can sort above LF
5066 # so we strip both of them from the original prefix.
5067 $prefix = strtr( $prefix, "\n\t", ' ' );
5068 return "$prefix\n$unprefixed";
5074 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5075 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5076 * the db, it will return NULL.
5078 * @return string|null|bool
5080 private function getDbPageLanguageCode() {
5081 global $wgPageLanguageUseDB;
5083 // check, if the page language could be saved in the database, and if so and
5084 // the value is not requested already, lookup the page language using LinkCache
5085 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5086 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5087 $linkCache->addLinkObj( $this );
5088 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5091 return $this->mDbPageLanguage
;
5095 * Get the language in which the content of this page is written in
5096 * wikitext. Defaults to content language, but in certain cases it can be
5097 * e.g. $wgLang (such as special pages, which are in the user language).
5102 public function getPageLanguage() {
5103 global $wgLang, $wgLanguageCode;
5104 if ( $this->isSpecialPage() ) {
5105 // special pages are in the user language
5109 // Checking if DB language is set
5110 $dbPageLanguage = $this->getDbPageLanguageCode();
5111 if ( $dbPageLanguage ) {
5112 return wfGetLangObj( $dbPageLanguage );
5115 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5116 // Note that this may depend on user settings, so the cache should
5117 // be only per-request.
5118 // NOTE: ContentHandler::getPageLanguage() may need to load the
5119 // content to determine the page language!
5120 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5122 $contentHandler = ContentHandler
::getForTitle( $this );
5123 $langObj = $contentHandler->getPageLanguage( $this );
5124 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5126 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5133 * Get the language in which the content of this page is written when
5134 * viewed by user. Defaults to content language, but in certain cases it can be
5135 * e.g. $wgLang (such as special pages, which are in the user language).
5140 public function getPageViewLanguage() {
5143 if ( $this->isSpecialPage() ) {
5144 // If the user chooses a variant, the content is actually
5145 // in a language whose code is the variant code.
5146 $variant = $wgLang->getPreferredVariant();
5147 if ( $wgLang->getCode() !== $variant ) {
5148 return Language
::factory( $variant );
5154 // Checking if DB language is set
5155 $dbPageLanguage = $this->getDbPageLanguageCode();
5156 if ( $dbPageLanguage ) {
5157 $pageLang = wfGetLangObj( $dbPageLanguage );
5158 $variant = $pageLang->getPreferredVariant();
5159 if ( $pageLang->getCode() !== $variant ) {
5160 $pageLang = Language
::factory( $variant );
5166 // @note Can't be cached persistently, depends on user settings.
5167 // @note ContentHandler::getPageViewLanguage() may need to load the
5168 // content to determine the page language!
5169 $contentHandler = ContentHandler
::getForTitle( $this );
5170 $pageLang = $contentHandler->getPageViewLanguage( $this );
5175 * Get a list of rendered edit notices for this page.
5177 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5178 * they will already be wrapped in paragraphs.
5181 * @param int $oldid Revision ID that's being edited
5184 public function getEditNotices( $oldid = 0 ) {
5187 // Optional notice for the entire namespace
5188 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5189 $msg = wfMessage( $editnotice_ns );
5190 if ( $msg->exists() ) {
5191 $html = $msg->parseAsBlock();
5192 // Edit notices may have complex logic, but output nothing (T91715)
5193 if ( trim( $html ) !== '' ) {
5194 $notices[$editnotice_ns] = Html
::rawElement(
5198 'mw-editnotice-namespace',
5199 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5206 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5207 // Optional notice for page itself and any parent page
5208 $editnotice_base = $editnotice_ns;
5209 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
5210 $editnotice_base .= '-' . $part;
5211 $msg = wfMessage( $editnotice_base );
5212 if ( $msg->exists() ) {
5213 $html = $msg->parseAsBlock();
5214 if ( trim( $html ) !== '' ) {
5215 $notices[$editnotice_base] = Html
::rawElement(
5219 'mw-editnotice-base',
5220 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5228 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5229 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5230 $msg = wfMessage( $editnoticeText );
5231 if ( $msg->exists() ) {
5232 $html = $msg->parseAsBlock();
5233 if ( trim( $html ) !== '' ) {
5234 $notices[$editnoticeText] = Html
::rawElement(
5238 'mw-editnotice-page',
5239 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5247 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5254 public function __sleep() {
5262 'mDefaultNamespace',
5266 public function __wakeup() {
5267 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5268 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5269 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );