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 */
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 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
117 protected $mOldRestrictions = false;
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
138 * Text form including namespace/interwiki, initialised on demand
140 * Only public to share cache with TitleFormatter
145 public $prefixedText = null;
147 /** @var mixed Cached value for getTitleProtection (create protection) */
148 public $mTitleProtection;
151 * @var int Namespace index when there is no namespace. Don't change the
152 * following default, NS_MAIN is hardcoded in several places. See T2696.
153 * Zero except in {{transclusion}} tags.
155 public $mDefaultNamespace = NS_MAIN
;
157 /** @var int The page length, 0 for special pages */
158 protected $mLength = -1;
160 /** @var null Is the article at this title a redirect? */
161 public $mRedirect = null;
163 /** @var array Associative array of user ID -> timestamp/false */
164 private $mNotificationTimestamp = [];
166 /** @var bool Whether a page has any subpages */
167 private $mHasSubpages;
169 /** @var bool The (string) language code of the page's language and content code. */
170 private $mPageLanguage = false;
172 /** @var string|bool|null The page language code from the database, null if not saved in
173 * the database or false if not loaded, yet. */
174 private $mDbPageLanguage = false;
176 /** @var TitleValue A corresponding TitleValue object */
177 private $mTitleValue = null;
179 /** @var bool Would deleting this page be a big deletion? */
180 private $mIsBigDeletion = null;
184 * B/C kludge: provide a TitleParser for use by Title.
185 * Ideally, Title would have no methods that need this.
186 * Avoid usage of this singleton by using TitleValue
187 * and the associated services when possible.
189 * @return TitleFormatter
191 private static function getTitleFormatter() {
192 return MediaWikiServices
::getInstance()->getTitleFormatter();
196 * B/C kludge: provide an InterwikiLookup for use by Title.
197 * Ideally, Title would have no methods that need this.
198 * Avoid usage of this singleton by using TitleValue
199 * and the associated services when possible.
201 * @return InterwikiLookup
203 private static function getInterwikiLookup() {
204 return MediaWikiServices
::getInstance()->getInterwikiLookup();
210 function __construct() {
214 * Create a new Title from a prefixed DB key
216 * @param string $key The database key, which has underscores
217 * instead of spaces, possibly including namespace and
219 * @return Title|null Title, or null on an error
221 public static function newFromDBkey( $key ) {
223 $t->mDbkeyform
= $key;
226 $t->secureAndSplit();
228 } catch ( MalformedTitleException
$ex ) {
234 * Create a new Title from a TitleValue
236 * @param TitleValue $titleValue Assumed to be safe.
240 public static function newFromTitleValue( TitleValue
$titleValue ) {
241 return self
::newFromLinkTarget( $titleValue );
245 * Create a new Title from a LinkTarget
247 * @param LinkTarget $linkTarget Assumed to be safe.
251 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
252 if ( $linkTarget instanceof Title
) {
253 // Special case if it's already a Title object
256 return self
::makeTitle(
257 $linkTarget->getNamespace(),
258 $linkTarget->getText(),
259 $linkTarget->getFragment(),
260 $linkTarget->getInterwiki()
265 * Create a new Title from text, such as what one would find in a link. De-
266 * codes any HTML entities in the text.
268 * Title objects returned by this method are guaranteed to be valid, and
269 * thus return true from the isValid() method.
271 * @param string|int|null $text The link text; spaces, prefixes, and an
272 * initial ':' indicating the main namespace are accepted.
273 * @param int $defaultNamespace The namespace to use if none is specified
274 * by a prefix. If you want to force a specific namespace even if
275 * $text might begin with a namespace prefix, use makeTitle() or
277 * @throws InvalidArgumentException
278 * @return Title|null Title or null on an error.
280 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
281 // DWIM: Integers can be passed in here when page titles are used as array keys.
282 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
283 throw new InvalidArgumentException( '$text must be a string.' );
285 if ( $text === null ) {
290 return self
::newFromTextThrow( strval( $text ), $defaultNamespace );
291 } catch ( MalformedTitleException
$ex ) {
297 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
298 * rather than returning null.
300 * The exception subclasses encode detailed information about why the title is invalid.
302 * Title objects returned by this method are guaranteed to be valid, and
303 * thus return true from the isValid() method.
305 * @see Title::newFromText
308 * @param string $text Title text to check
309 * @param int $defaultNamespace
310 * @throws MalformedTitleException If the title is invalid
313 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
314 if ( is_object( $text ) ) {
315 throw new MWException( '$text must be a string, given an object' );
316 } elseif ( $text === null ) {
317 // Legacy code relies on MalformedTitleException being thrown in this case
318 // (happens when URL with no title in it is parsed). TODO fix
319 throw new MalformedTitleException( 'title-invalid-empty' );
322 $titleCache = self
::getTitleCache();
324 // Wiki pages often contain multiple links to the same page.
325 // Title normalization and parsing can become expensive on pages with many
326 // links, so we can save a little time by caching them.
327 // In theory these are value objects and won't get changed...
328 if ( $defaultNamespace == NS_MAIN
) {
329 $t = $titleCache->get( $text );
335 // Convert things like é ā or 〗 into normalized (T16952) text
336 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
339 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
340 $t->mDefaultNamespace
= intval( $defaultNamespace );
342 $t->secureAndSplit();
343 if ( $defaultNamespace == NS_MAIN
) {
344 $titleCache->set( $text, $t );
350 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
352 * Example of wrong and broken code:
353 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
355 * Example of right code:
356 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
358 * Create a new Title from URL-encoded text. Ensures that
359 * the given title's length does not exceed the maximum.
361 * @param string $url The title, as might be taken from a URL
362 * @return Title|null The new object, or null on an error
364 public static function newFromURL( $url ) {
367 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
368 # but some URLs used it as a space replacement and they still come
369 # from some external search tools.
370 if ( strpos( self
::legalChars(), '+' ) === false ) {
371 $url = strtr( $url, '+', ' ' );
374 $t->mDbkeyform
= strtr( $url, ' ', '_' );
377 $t->secureAndSplit();
379 } catch ( MalformedTitleException
$ex ) {
385 * @return MapCacheLRU
387 private static function getTitleCache() {
388 if ( self
::$titleCache == null ) {
389 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
391 return self
::$titleCache;
395 * Returns a list of fields that are to be selected for initializing Title
396 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
397 * whether to include page_content_model.
401 protected static function getSelectFields() {
402 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
405 'page_namespace', 'page_title', 'page_id',
406 'page_len', 'page_is_redirect', 'page_latest',
409 if ( $wgContentHandlerUseDB ) {
410 $fields[] = 'page_content_model';
413 if ( $wgPageLanguageUseDB ) {
414 $fields[] = 'page_lang';
421 * Create a new Title from an article ID
423 * @param int $id The page_id corresponding to the Title to create
424 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
425 * @return Title|null The new object, or null on an error
427 public static function newFromID( $id, $flags = 0 ) {
428 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
429 $row = $db->selectRow(
431 self
::getSelectFields(),
432 [ 'page_id' => $id ],
435 if ( $row !== false ) {
436 $title = self
::newFromRow( $row );
444 * Make an array of titles from an array of IDs
446 * @param int[] $ids Array of IDs
447 * @return Title[] Array of Titles
449 public static function newFromIDs( $ids ) {
450 if ( !count( $ids ) ) {
453 $dbr = wfGetDB( DB_REPLICA
);
457 self
::getSelectFields(),
458 [ 'page_id' => $ids ],
463 foreach ( $res as $row ) {
464 $titles[] = self
::newFromRow( $row );
470 * Make a Title object from a DB row
472 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
473 * @return Title Corresponding Title
475 public static function newFromRow( $row ) {
476 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
477 $t->loadFromRow( $row );
482 * Load Title object fields from a DB row.
483 * If false is given, the title will be treated as non-existing.
485 * @param stdClass|bool $row Database row
487 public function loadFromRow( $row ) {
488 if ( $row ) { // page found
489 if ( isset( $row->page_id
) ) {
490 $this->mArticleID
= (int)$row->page_id
;
492 if ( isset( $row->page_len
) ) {
493 $this->mLength
= (int)$row->page_len
;
495 if ( isset( $row->page_is_redirect
) ) {
496 $this->mRedirect
= (bool)$row->page_is_redirect
;
498 if ( isset( $row->page_latest
) ) {
499 $this->mLatestID
= (int)$row->page_latest
;
501 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
502 $this->mContentModel
= strval( $row->page_content_model
);
503 } elseif ( !$this->mForcedContentModel
) {
504 $this->mContentModel
= false; # initialized lazily in getContentModel()
506 if ( isset( $row->page_lang
) ) {
507 $this->mDbPageLanguage
= (string)$row->page_lang
;
509 if ( isset( $row->page_restrictions
) ) {
510 $this->mOldRestrictions
= $row->page_restrictions
;
512 } else { // page not found
513 $this->mArticleID
= 0;
515 $this->mRedirect
= false;
516 $this->mLatestID
= 0;
517 if ( !$this->mForcedContentModel
) {
518 $this->mContentModel
= false; # initialized lazily in getContentModel()
524 * Create a new Title from a namespace index and a DB key.
526 * It's assumed that $ns and $title are safe, for instance when
527 * they came directly from the database or a special page name,
528 * not from user input.
530 * No validation is applied. For convenience, spaces are normalized
531 * to underscores, so that e.g. user_text fields can be used directly.
533 * @note This method may return Title objects that are "invalid"
534 * according to the isValid() method. This is usually caused by
535 * configuration changes: e.g. a namespace that was once defined is
536 * no longer configured, or a character that was once allowed in
537 * titles is now forbidden.
539 * @param int $ns The namespace of the article
540 * @param string $title The unprefixed database key form
541 * @param string $fragment The link fragment (after the "#")
542 * @param string $interwiki The interwiki prefix
543 * @return Title The new object
545 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
547 $t->mInterwiki
= $interwiki;
548 $t->mFragment
= $fragment;
549 $t->mNamespace
= $ns = intval( $ns );
550 $t->mDbkeyform
= strtr( $title, ' ', '_' );
551 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
552 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
553 $t->mTextform
= strtr( $title, '_', ' ' );
554 $t->mContentModel
= false; # initialized lazily in getContentModel()
559 * Create a new Title from a namespace index and a DB key.
560 * The parameters will be checked for validity, which is a bit slower
561 * than makeTitle() but safer for user-provided data.
563 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
564 * that is, they return true from the isValid() method. If no valid Title
565 * can be constructed from the input, this method returns null.
567 * @param int $ns The namespace of the article
568 * @param string $title Database key form
569 * @param string $fragment The link fragment (after the "#")
570 * @param string $interwiki Interwiki prefix
571 * @return Title|null The new object, or null on an error
573 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
574 // NOTE: ideally, this would just call makeTitle() and then isValid(),
575 // but presently, that means more overhead on a potential performance hotspot.
577 if ( !MWNamespace
::exists( $ns ) ) {
582 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
585 $t->secureAndSplit();
587 } catch ( MalformedTitleException
$ex ) {
593 * Create a new Title for the Main Page
595 * @return Title The new object
597 public static function newMainPage() {
598 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
599 // Don't give fatal errors if the message is broken
601 $title = self
::newFromText( 'Main Page' );
607 * Get the prefixed DB key associated with an ID
609 * @param int $id The page_id of the article
610 * @return Title|null An object representing the article, or null if no such article was found
612 public static function nameOf( $id ) {
613 $dbr = wfGetDB( DB_REPLICA
);
615 $s = $dbr->selectRow(
617 [ 'page_namespace', 'page_title' ],
618 [ 'page_id' => $id ],
621 if ( $s === false ) {
625 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
630 * Get a regex character class describing the legal characters in a link
632 * @return string The list of characters, not delimited
634 public static function legalChars() {
635 global $wgLegalTitleChars;
636 return $wgLegalTitleChars;
640 * Utility method for converting a character sequence from bytes to Unicode.
642 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
643 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
645 * @param string $byteClass
648 public static function convertByteClassToUnicodeClass( $byteClass ) {
649 $length = strlen( $byteClass );
651 $x0 = $x1 = $x2 = '';
653 $d0 = $d1 = $d2 = '';
654 // Decoded integer codepoints
655 $ord0 = $ord1 = $ord2 = 0;
657 $r0 = $r1 = $r2 = '';
661 $allowUnicode = false;
662 for ( $pos = 0; $pos < $length; $pos++
) {
663 // Shift the queues down
672 // Load the current input token and decoded values
673 $inChar = $byteClass[$pos];
674 if ( $inChar == '\\' ) {
675 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
676 $x0 = $inChar . $m[0];
677 $d0 = chr( hexdec( $m[1] ) );
678 $pos +
= strlen( $m[0] );
679 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
680 $x0 = $inChar . $m[0];
681 $d0 = chr( octdec( $m[0] ) );
682 $pos +
= strlen( $m[0] );
683 } elseif ( $pos +
1 >= $length ) {
686 $d0 = $byteClass[$pos +
1];
694 // Load the current re-encoded value
695 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
696 $r0 = sprintf( '\x%02x', $ord0 );
697 } elseif ( $ord0 >= 0x80 ) {
698 // Allow unicode if a single high-bit character appears
699 $r0 = sprintf( '\x%02x', $ord0 );
700 $allowUnicode = true;
701 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
707 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
709 if ( $ord2 > $ord0 ) {
711 } elseif ( $ord0 >= 0x80 ) {
713 $allowUnicode = true;
714 if ( $ord2 < 0x80 ) {
715 // Keep the non-unicode section of the range
722 // Reset state to the initial value
723 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
724 } elseif ( $ord2 < 0x80 ) {
729 if ( $ord1 < 0x80 ) {
732 if ( $ord0 < 0x80 ) {
735 if ( $allowUnicode ) {
736 $out .= '\u0080-\uFFFF';
742 * Make a prefixed DB key from a DB key and a namespace index
744 * @param int $ns Numerical representation of the namespace
745 * @param string $title The DB key form the title
746 * @param string $fragment The link fragment (after the "#")
747 * @param string $interwiki The interwiki prefix
748 * @param bool $canonicalNamespace If true, use the canonical name for
749 * $ns instead of the localized version.
750 * @return string The prefixed form of the title
752 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
753 $canonicalNamespace = false
755 if ( $canonicalNamespace ) {
756 $namespace = MWNamespace
::getCanonicalName( $ns );
758 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
760 $name = $namespace == '' ?
$title : "$namespace:$title";
761 if ( strval( $interwiki ) != '' ) {
762 $name = "$interwiki:$name";
764 if ( strval( $fragment ) != '' ) {
765 $name .= '#' . $fragment;
771 * Callback for usort() to do title sorts by (namespace, title)
773 * @param LinkTarget $a
774 * @param LinkTarget $b
776 * @return int Result of string comparison, or namespace comparison
778 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
779 return $a->getNamespace() <=> $b->getNamespace()
780 ?
: strcmp( $a->getText(), $b->getText() );
784 * Returns true if the title is valid, false if it is invalid.
786 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
787 * Invalid titles may get returned from makeTitle(), and it may be useful to
788 * allow them to exist, e.g. in order to process log entries about pages in
789 * namespaces that belong to extensions that are no longer installed.
791 * @note This method is relatively expensive. When constructing Title
792 * objects that need to be valid, use an instantiator method that is guaranteed
793 * to return valid titles, such as makeTitleSafe() or newFromText().
797 public function isValid() {
798 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
803 $parser = MediaWikiServices
::getInstance()->getTitleParser();
804 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
806 } catch ( MalformedTitleException
$ex ) {
812 * Determine whether the object refers to a page within
813 * this project (either this wiki or a wiki with a local
814 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
816 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
818 public function isLocal() {
819 if ( $this->isExternal() ) {
820 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
822 return $iw->isLocal();
829 * Is this Title interwiki?
833 public function isExternal() {
834 return $this->mInterwiki
!== '';
838 * Get the interwiki prefix
840 * Use Title::isExternal to check if a interwiki is set
842 * @return string Interwiki prefix
844 public function getInterwiki() {
845 return $this->mInterwiki
;
849 * Was this a local interwiki link?
853 public function wasLocalInterwiki() {
854 return $this->mLocalInterwiki
;
858 * Determine whether the object refers to a page within
859 * this project and is transcludable.
861 * @return bool True if this is transcludable
863 public function isTrans() {
864 if ( !$this->isExternal() ) {
868 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
872 * Returns the DB name of the distant wiki which owns the object.
874 * @return string|false The DB name
876 public function getTransWikiID() {
877 if ( !$this->isExternal() ) {
881 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
885 * Get a TitleValue object representing this Title.
887 * @note Not all valid Titles have a corresponding valid TitleValue
888 * (e.g. TitleValues cannot represent page-local links that have a
889 * fragment but no title text).
891 * @return TitleValue|null
893 public function getTitleValue() {
894 if ( $this->mTitleValue
=== null ) {
896 $this->mTitleValue
= new TitleValue(
902 } catch ( InvalidArgumentException
$ex ) {
903 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
904 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
908 return $this->mTitleValue
;
912 * Get the text form (spaces not underscores) of the main part
914 * @return string Main part of the title
916 public function getText() {
917 return $this->mTextform
;
921 * Get the URL-encoded form of the main part
923 * @return string Main part of the title, URL-encoded
925 public function getPartialURL() {
926 return $this->mUrlform
;
930 * Get the main part with underscores
932 * @return string Main part of the title, with underscores
934 public function getDBkey() {
935 return $this->mDbkeyform
;
939 * Get the DB key with the initial letter case as specified by the user
940 * @deprecated since 1.33; please use Title::getDBKey() instead
942 * @return string DB key
944 function getUserCaseDBKey() {
945 if ( !is_null( $this->mUserCaseDBKey
) ) {
946 return $this->mUserCaseDBKey
;
948 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
949 return $this->mDbkeyform
;
954 * Get the namespace index, i.e. one of the NS_xxxx constants.
956 * @return int Namespace index
958 public function getNamespace() {
959 return $this->mNamespace
;
963 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
965 * @todo Deprecate this in favor of SlotRecord::getModel()
967 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
968 * @return string Content model id
970 public function getContentModel( $flags = 0 ) {
971 if ( !$this->mForcedContentModel
972 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
973 && $this->getArticleID( $flags )
975 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
976 $linkCache->addLinkObj( $this ); # in case we already had an article ID
977 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
980 if ( !$this->mContentModel
) {
981 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
984 return $this->mContentModel
;
988 * Convenience method for checking a title's content model name
990 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
991 * @return bool True if $this->getContentModel() == $id
993 public function hasContentModel( $id ) {
994 return $this->getContentModel() == $id;
998 * Set a proposed content model for the page for permissions
999 * checking. This does not actually change the content model
1002 * Additionally, you should make sure you've checked
1003 * ContentHandler::canBeUsedOn() first.
1006 * @param string $model CONTENT_MODEL_XXX constant
1008 public function setContentModel( $model ) {
1009 $this->mContentModel
= $model;
1010 $this->mForcedContentModel
= true;
1014 * Get the namespace text
1016 * @return string|false Namespace text
1018 public function getNsText() {
1019 if ( $this->isExternal() ) {
1020 // This probably shouldn't even happen, except for interwiki transclusion.
1021 // If possible, use the canonical name for the foreign namespace.
1022 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1023 if ( $nsText !== false ) {
1029 $formatter = self
::getTitleFormatter();
1030 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1031 } catch ( InvalidArgumentException
$ex ) {
1032 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1038 * Get the namespace text of the subject (rather than talk) page
1040 * @return string Namespace text
1042 public function getSubjectNsText() {
1043 return MediaWikiServices
::getInstance()->getContentLanguage()->
1044 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1048 * Get the namespace text of the talk page
1050 * @return string Namespace text
1052 public function getTalkNsText() {
1053 return MediaWikiServices
::getInstance()->getContentLanguage()->
1054 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1058 * Can this title have a corresponding talk page?
1060 * @deprecated since 1.30, use canHaveTalkPage() instead.
1062 * @return bool True if this title either is a talk page or can have a talk page associated.
1064 public function canTalk() {
1065 return $this->canHaveTalkPage();
1069 * Can this title have a corresponding talk page?
1071 * @see MWNamespace::hasTalkNamespace
1074 * @return bool True if this title either is a talk page or can have a talk page associated.
1076 public function canHaveTalkPage() {
1077 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1081 * Is this in a namespace that allows actual pages?
1085 public function canExist() {
1086 return $this->mNamespace
>= NS_MAIN
;
1090 * Can this title be added to a user's watchlist?
1094 public function isWatchable() {
1095 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1099 * Returns true if this is a special page.
1103 public function isSpecialPage() {
1104 return $this->mNamespace
== NS_SPECIAL
;
1108 * Returns true if this title resolves to the named special page
1110 * @param string $name The special page name
1113 public function isSpecial( $name ) {
1114 if ( $this->isSpecialPage() ) {
1115 list( $thisName, /* $subpage */ ) =
1116 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1117 resolveAlias( $this->mDbkeyform
);
1118 if ( $name == $thisName ) {
1126 * If the Title refers to a special page alias which is not the local default, resolve
1127 * the alias, and localise the name as necessary. Otherwise, return $this
1131 public function fixSpecialName() {
1132 if ( $this->isSpecialPage() ) {
1133 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1134 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1135 if ( $canonicalName ) {
1136 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1137 if ( $localName != $this->mDbkeyform
) {
1138 return self
::makeTitle( NS_SPECIAL
, $localName );
1146 * Returns true if the title is inside the specified namespace.
1148 * Please make use of this instead of comparing to getNamespace()
1149 * This function is much more resistant to changes we may make
1150 * to namespaces than code that makes direct comparisons.
1151 * @param int $ns The namespace
1155 public function inNamespace( $ns ) {
1156 return MWNamespace
::equals( $this->mNamespace
, $ns );
1160 * Returns true if the title is inside one of the specified namespaces.
1162 * @param int|int[] $namespaces,... The namespaces to check for
1166 public function inNamespaces( /* ... */ ) {
1167 $namespaces = func_get_args();
1168 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1169 $namespaces = $namespaces[0];
1172 foreach ( $namespaces as $ns ) {
1173 if ( $this->inNamespace( $ns ) ) {
1182 * Returns true if the title has the same subject namespace as the
1183 * namespace specified.
1184 * For example this method will take NS_USER and return true if namespace
1185 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1186 * as their subject namespace.
1188 * This is MUCH simpler than individually testing for equivalence
1189 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1194 public function hasSubjectNamespace( $ns ) {
1195 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1199 * Is this Title in a namespace which contains content?
1200 * In other words, is this a content page, for the purposes of calculating
1205 public function isContentPage() {
1206 return MWNamespace
::isContent( $this->mNamespace
);
1210 * Would anybody with sufficient privileges be able to move this page?
1211 * Some pages just aren't movable.
1215 public function isMovable() {
1216 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1217 // Interwiki title or immovable namespace. Hooks don't get to override here
1222 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1227 * Is this the mainpage?
1228 * @note Title::newFromText seems to be sufficiently optimized by the title
1229 * cache that we don't need to over-optimize by doing direct comparisons and
1230 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1231 * ends up reporting something differently than $title->isMainPage();
1236 public function isMainPage() {
1237 return $this->equals( self
::newMainPage() );
1241 * Is this a subpage?
1245 public function isSubpage() {
1246 return MWNamespace
::hasSubpages( $this->mNamespace
)
1247 ?
strpos( $this->getText(), '/' ) !== false
1252 * Is this a conversion table for the LanguageConverter?
1256 public function isConversionTable() {
1257 // @todo ConversionTable should become a separate content model.
1259 return $this->mNamespace
== NS_MEDIAWIKI
&&
1260 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1264 * Does that page contain wikitext, or it is JS, CSS or whatever?
1268 public function isWikitextPage() {
1269 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1273 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1274 * global UI. This is generally true for pages in the MediaWiki namespace having
1275 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1277 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1280 * Note that this method should not return true for pages that contain and show
1281 * "inactive" CSS, JSON, or JS.
1286 public function isSiteConfigPage() {
1288 $this->isSiteCssConfigPage()
1289 ||
$this->isSiteJsonConfigPage()
1290 ||
$this->isSiteJsConfigPage()
1296 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1298 public function isCssOrJsPage() {
1299 wfDeprecated( __METHOD__
, '1.31' );
1300 return ( NS_MEDIAWIKI
== $this->mNamespace
1301 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1302 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1306 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1311 public function isUserConfigPage() {
1313 $this->isUserCssConfigPage()
1314 ||
$this->isUserJsonConfigPage()
1315 ||
$this->isUserJsConfigPage()
1321 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1323 public function isCssJsSubpage() {
1324 wfDeprecated( __METHOD__
, '1.31' );
1325 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1326 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1327 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1331 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1333 * @return string Containing skin name from .css, .json, or .js subpage title
1336 public function getSkinFromConfigSubpage() {
1337 $subpage = explode( '/', $this->mTextform
);
1338 $subpage = $subpage[count( $subpage ) - 1];
1339 $lastdot = strrpos( $subpage, '.' );
1340 if ( $lastdot === false ) {
1341 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1343 return substr( $subpage, 0, $lastdot );
1347 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1348 * @return string Containing skin name from .css, .json, or .js subpage title
1350 public function getSkinFromCssJsSubpage() {
1351 wfDeprecated( __METHOD__
, '1.31' );
1352 return $this->getSkinFromConfigSubpage();
1356 * Is this a CSS "config" sub-page of a user page?
1361 public function isUserCssConfigPage() {
1363 NS_USER
== $this->mNamespace
1364 && $this->isSubpage()
1365 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1370 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1373 public function isCssSubpage() {
1374 wfDeprecated( __METHOD__
, '1.31' );
1375 return $this->isUserCssConfigPage();
1379 * Is this a JSON "config" sub-page of a user page?
1384 public function isUserJsonConfigPage() {
1386 NS_USER
== $this->mNamespace
1387 && $this->isSubpage()
1388 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1393 * Is this a JS "config" sub-page of a user page?
1398 public function isUserJsConfigPage() {
1400 NS_USER
== $this->mNamespace
1401 && $this->isSubpage()
1402 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1407 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1410 public function isJsSubpage() {
1411 wfDeprecated( __METHOD__
, '1.31' );
1412 return $this->isUserJsConfigPage();
1416 * Is this a sitewide CSS "config" page?
1421 public function isSiteCssConfigPage() {
1423 NS_MEDIAWIKI
== $this->mNamespace
1425 $this->hasContentModel( CONTENT_MODEL_CSS
)
1426 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1427 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1428 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1434 * Is this a sitewide JSON "config" page?
1439 public function isSiteJsonConfigPage() {
1441 NS_MEDIAWIKI
== $this->mNamespace
1443 $this->hasContentModel( CONTENT_MODEL_JSON
)
1444 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1445 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1446 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1452 * Is this a sitewide JS "config" page?
1457 public function isSiteJsConfigPage() {
1459 NS_MEDIAWIKI
== $this->mNamespace
1461 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1462 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1463 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1464 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1470 * Is this a message which can contain raw HTML?
1475 public function isRawHtmlMessage() {
1476 global $wgRawHtmlMessages;
1478 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1481 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1482 return in_array( $message, $wgRawHtmlMessages, true );
1486 * Is this a talk page of some sort?
1490 public function isTalkPage() {
1491 return MWNamespace
::isTalk( $this->mNamespace
);
1495 * Get a Title object associated with the talk page of this article
1497 * @return Title The object for the talk page
1499 public function getTalkPage() {
1500 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1504 * Get a Title object associated with the talk page of this article,
1505 * if such a talk page can exist.
1509 * @return Title|null The object for the talk page,
1510 * or null if no associated talk page can exist, according to canHaveTalkPage().
1512 public function getTalkPageIfDefined() {
1513 if ( !$this->canHaveTalkPage() ) {
1517 return $this->getTalkPage();
1521 * Get a title object associated with the subject page of this
1524 * @return Title The object for the subject page
1526 public function getSubjectPage() {
1527 // Is this the same title?
1528 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1529 if ( $this->mNamespace
== $subjectNS ) {
1532 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1536 * Get the other title for this page, if this is a subject page
1537 * get the talk page, if it is a subject page get the talk page
1540 * @throws MWException If the page doesn't have an other page
1543 public function getOtherPage() {
1544 if ( $this->isSpecialPage() ) {
1545 throw new MWException( 'Special pages cannot have other pages' );
1547 if ( $this->isTalkPage() ) {
1548 return $this->getSubjectPage();
1550 if ( !$this->canHaveTalkPage() ) {
1551 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1553 return $this->getTalkPage();
1558 * Get the default namespace index, for when there is no namespace
1560 * @return int Default namespace index
1562 public function getDefaultNamespace() {
1563 return $this->mDefaultNamespace
;
1567 * Get the Title fragment (i.e.\ the bit after the #) in text form
1569 * Use Title::hasFragment to check for a fragment
1571 * @return string Title fragment
1573 public function getFragment() {
1574 return $this->mFragment
;
1578 * Check if a Title fragment is set
1583 public function hasFragment() {
1584 return $this->mFragment
!== '';
1588 * Get the fragment in URL form, including the "#" character if there is one
1590 * @return string Fragment in URL form
1592 public function getFragmentForURL() {
1593 if ( !$this->hasFragment() ) {
1595 } elseif ( $this->isExternal() ) {
1596 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1597 // so we treat it like a local interwiki.
1598 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1599 if ( $interwiki && !$interwiki->isLocal() ) {
1600 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1604 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1608 * Set the fragment for this title. Removes the first character from the
1609 * specified fragment before setting, so it assumes you're passing it with
1612 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1613 * or Title::createFragmentTarget().
1614 * Still in active use privately.
1617 * @param string $fragment Text
1619 public function setFragment( $fragment ) {
1620 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1624 * Creates a new Title for a different fragment of the same page.
1627 * @param string $fragment
1630 public function createFragmentTarget( $fragment ) {
1631 return self
::makeTitle(
1640 * Prefix some arbitrary text with the namespace or interwiki prefix
1643 * @param string $name The text
1644 * @return string The prefixed text
1646 private function prefix( $name ) {
1648 if ( $this->isExternal() ) {
1649 $p = $this->mInterwiki
. ':';
1652 if ( $this->mNamespace
!= 0 ) {
1653 $nsText = $this->getNsText();
1655 if ( $nsText === false ) {
1656 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1657 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1658 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1661 $p .= $nsText . ':';
1667 * Get the prefixed database key form
1669 * @return string The prefixed title, with underscores and
1670 * any interwiki and namespace prefixes
1672 public function getPrefixedDBkey() {
1673 $s = $this->prefix( $this->mDbkeyform
);
1674 $s = strtr( $s, ' ', '_' );
1679 * Get the prefixed title with spaces.
1680 * This is the form usually used for display
1682 * @return string The prefixed title, with spaces
1684 public function getPrefixedText() {
1685 if ( $this->prefixedText
=== null ) {
1686 $s = $this->prefix( $this->mTextform
);
1687 $s = strtr( $s, '_', ' ' );
1688 $this->prefixedText
= $s;
1690 return $this->prefixedText
;
1694 * Return a string representation of this title
1696 * @return string Representation of this title
1698 public function __toString() {
1699 return $this->getPrefixedText();
1703 * Get the prefixed title with spaces, plus any fragment
1704 * (part beginning with '#')
1706 * @return string The prefixed title, with spaces and the fragment, including '#'
1708 public function getFullText() {
1709 $text = $this->getPrefixedText();
1710 if ( $this->hasFragment() ) {
1711 $text .= '#' . $this->mFragment
;
1717 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1721 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1725 * @return string Root name
1728 public function getRootText() {
1729 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1730 return $this->getText();
1733 return strtok( $this->getText(), '/' );
1737 * Get the root page name title, i.e. the leftmost part before any slashes
1741 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1742 * # returns: Title{User:Foo}
1745 * @return Title Root title
1748 public function getRootTitle() {
1749 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1753 * Get the base page name without a namespace, i.e. the part before the subpage name
1757 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1758 * # returns: 'Foo/Bar'
1761 * @return string Base name
1763 public function getBaseText() {
1764 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1765 return $this->getText();
1768 $parts = explode( '/', $this->getText() );
1769 # Don't discard the real title if there's no subpage involved
1770 if ( count( $parts ) > 1 ) {
1771 unset( $parts[count( $parts ) - 1] );
1773 return implode( '/', $parts );
1777 * Get the base page name title, i.e. the part before the subpage name
1781 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1782 * # returns: Title{User:Foo/Bar}
1785 * @return Title Base title
1788 public function getBaseTitle() {
1789 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1793 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1797 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1801 * @return string Subpage name
1803 public function getSubpageText() {
1804 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1805 return $this->mTextform
;
1807 $parts = explode( '/', $this->mTextform
);
1808 return $parts[count( $parts ) - 1];
1812 * Get the title for a subpage of the current page
1816 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1817 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1820 * @param string $text The subpage name to add to the title
1821 * @return Title|null Subpage title, or null on an error
1824 public function getSubpage( $text ) {
1825 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1829 * Get a URL-encoded form of the subpage text
1831 * @return string URL-encoded subpage name
1833 public function getSubpageUrlForm() {
1834 $text = $this->getSubpageText();
1835 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1840 * Get a URL-encoded title (not an actual URL) including interwiki
1842 * @return string The URL-encoded form
1844 public function getPrefixedURL() {
1845 $s = $this->prefix( $this->mDbkeyform
);
1846 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1851 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1852 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1853 * second argument named variant. This was deprecated in favor
1854 * of passing an array of option with a "variant" key
1855 * Once $query2 is removed for good, this helper can be dropped
1856 * and the wfArrayToCgi moved to getLocalURL();
1858 * @since 1.19 (r105919)
1859 * @param array|string $query
1860 * @param string|string[]|bool $query2
1863 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1864 if ( $query2 !== false ) {
1865 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1866 "method called with a second parameter is deprecated. Add your " .
1867 "parameter to an array passed as the first parameter.", "1.19" );
1869 if ( is_array( $query ) ) {
1870 $query = wfArrayToCgi( $query );
1873 if ( is_string( $query2 ) ) {
1874 // $query2 is a string, we will consider this to be
1875 // a deprecated $variant argument and add it to the query
1876 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1878 $query2 = wfArrayToCgi( $query2 );
1880 // If we have $query content add a & to it first
1884 // Now append the queries together
1891 * Get a real URL referring to this title, with interwiki link and
1894 * @see self::getLocalURL for the arguments.
1896 * @param string|string[] $query
1897 * @param string|string[]|bool $query2
1898 * @param string|int|null $proto Protocol type to use in URL
1899 * @return string The URL
1901 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1902 $query = self
::fixUrlQueryArgs( $query, $query2 );
1904 # Hand off all the decisions on urls to getLocalURL
1905 $url = $this->getLocalURL( $query );
1907 # Expand the url to make it a full url. Note that getLocalURL has the
1908 # potential to output full urls for a variety of reasons, so we use
1909 # wfExpandUrl instead of simply prepending $wgServer
1910 $url = wfExpandUrl( $url, $proto );
1912 # Finally, add the fragment.
1913 $url .= $this->getFragmentForURL();
1914 // Avoid PHP 7.1 warning from passing $this by reference
1916 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1921 * Get a url appropriate for making redirects based on an untrusted url arg
1923 * This is basically the same as getFullUrl(), but in the case of external
1924 * interwikis, we send the user to a landing page, to prevent possible
1925 * phishing attacks and the like.
1927 * @note Uses current protocol by default, since technically relative urls
1928 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1929 * places where the url gets cached, as might pollute between
1930 * https and non-https users.
1931 * @see self::getLocalURL for the arguments.
1932 * @param array|string $query
1933 * @param string $proto Protocol type to use in URL
1934 * @return string A url suitable to use in an HTTP location header.
1936 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1938 if ( $this->isExternal() ) {
1939 $target = SpecialPage
::getTitleFor(
1941 $this->getPrefixedDBkey()
1944 return $target->getFullURL( $query, false, $proto );
1948 * Get a URL with no fragment or server name (relative URL) from a Title object.
1949 * If this page is generated with action=render, however,
1950 * $wgServer is prepended to make an absolute URL.
1952 * @see self::getFullURL to always get an absolute URL.
1953 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1954 * valid to link, locally, to the current Title.
1955 * @see self::newFromText to produce a Title object.
1957 * @param string|string[] $query An optional query string,
1958 * not used for interwiki links. Can be specified as an associative array as well,
1959 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1960 * Some query patterns will trigger various shorturl path replacements.
1961 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1962 * be an array. If a string is passed it will be interpreted as a deprecated
1963 * variant argument and urlencoded into a variant= argument.
1964 * This second query argument will be added to the $query
1965 * The second parameter is deprecated since 1.19. Pass it as a key,value
1966 * pair in the first parameter array instead.
1968 * @return string String of the URL.
1970 public function getLocalURL( $query = '', $query2 = false ) {
1971 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1973 $query = self
::fixUrlQueryArgs( $query, $query2 );
1975 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1977 $namespace = $this->getNsText();
1978 if ( $namespace != '' ) {
1979 # Can this actually happen? Interwikis shouldn't be parsed.
1980 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1983 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1984 $url = wfAppendQuery( $url, $query );
1986 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1987 if ( $query == '' ) {
1988 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1989 // Avoid PHP 7.1 warning from passing $this by reference
1991 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1993 global $wgVariantArticlePath, $wgActionPaths;
1997 if ( !empty( $wgActionPaths )
1998 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2000 $action = urldecode( $matches[2] );
2001 if ( isset( $wgActionPaths[$action] ) ) {
2002 $query = $matches[1];
2003 if ( isset( $matches[4] ) ) {
2004 $query .= $matches[4];
2006 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2007 if ( $query != '' ) {
2008 $url = wfAppendQuery( $url, $query );
2014 && $wgVariantArticlePath
2015 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2016 && $this->getPageLanguage()->equals(
2017 MediaWikiServices
::getInstance()->getContentLanguage() )
2018 && $this->getPageLanguage()->hasVariants()
2020 $variant = urldecode( $matches[1] );
2021 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2022 // Only do the variant replacement if the given variant is a valid
2023 // variant for the page's language.
2024 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2025 $url = str_replace( '$1', $dbkey, $url );
2029 if ( $url === false ) {
2030 if ( $query == '-' ) {
2033 $url = "{$wgScript}?title={$dbkey}&{$query}";
2036 // Avoid PHP 7.1 warning from passing $this by reference
2038 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2040 // @todo FIXME: This causes breakage in various places when we
2041 // actually expected a local URL and end up with dupe prefixes.
2042 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2043 $url = $wgServer . $url;
2046 // Avoid PHP 7.1 warning from passing $this by reference
2048 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2053 * Get a URL that's the simplest URL that will be valid to link, locally,
2054 * to the current Title. It includes the fragment, but does not include
2055 * the server unless action=render is used (or the link is external). If
2056 * there's a fragment but the prefixed text is empty, we just return a link
2059 * The result obviously should not be URL-escaped, but does need to be
2060 * HTML-escaped if it's being output in HTML.
2062 * @param string|string[] $query
2063 * @param bool $query2
2064 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2065 * or false (default) for no expansion
2066 * @see self::getLocalURL for the arguments.
2067 * @return string The URL
2069 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2070 if ( $this->isExternal() ||
$proto !== false ) {
2071 $ret = $this->getFullURL( $query, $query2, $proto );
2072 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2073 $ret = $this->getFragmentForURL();
2075 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2081 * Get the URL form for an internal link.
2082 * - Used in various CDN-related code, in case we have a different
2083 * internal hostname for the server from the exposed one.
2085 * This uses $wgInternalServer to qualify the path, or $wgServer
2086 * if $wgInternalServer is not set. If the server variable used is
2087 * protocol-relative, the URL will be expanded to http://
2089 * @see self::getLocalURL for the arguments.
2090 * @param string $query
2091 * @param string|bool $query2
2092 * @return string The URL
2094 public function getInternalURL( $query = '', $query2 = false ) {
2095 global $wgInternalServer, $wgServer;
2096 $query = self
::fixUrlQueryArgs( $query, $query2 );
2097 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2098 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2099 // Avoid PHP 7.1 warning from passing $this by reference
2101 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2106 * Get the URL for a canonical link, for use in things like IRC and
2107 * e-mail notifications. Uses $wgCanonicalServer and the
2108 * GetCanonicalURL hook.
2110 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2112 * @see self::getLocalURL for the arguments.
2113 * @param string $query
2114 * @param string|bool $query2
2115 * @return string The URL
2118 public function getCanonicalURL( $query = '', $query2 = false ) {
2119 $query = self
::fixUrlQueryArgs( $query, $query2 );
2120 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2121 // Avoid PHP 7.1 warning from passing $this by reference
2123 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2128 * Get the edit URL for this Title
2130 * @return string The URL, or a null string if this is an interwiki link
2132 public function getEditURL() {
2133 if ( $this->isExternal() ) {
2136 $s = $this->getLocalURL( 'action=edit' );
2142 * Can $user perform $action on this page?
2143 * This skips potentially expensive cascading permission checks
2144 * as well as avoids expensive error formatting
2146 * Suitable for use for nonessential UI controls in common cases, but
2147 * _not_ for functional access control.
2149 * May provide false positives, but should never provide a false negative.
2151 * @param string $action Action that permission needs to be checked for
2152 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2155 public function quickUserCan( $action, $user = null ) {
2156 return $this->userCan( $action, $user, false );
2160 * Can $user perform $action on this page?
2162 * @param string $action Action that permission needs to be checked for
2163 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2165 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2168 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2169 if ( !$user instanceof User
) {
2174 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2178 * Can $user perform $action on this page?
2180 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2182 * @param string $action Action that permission needs to be checked for
2183 * @param User $user User to check
2184 * @param string $rigor One of (quick,full,secure)
2185 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2186 * - full : does cheap and expensive checks possibly from a replica DB
2187 * - secure : does cheap and expensive checks, using the master as needed
2188 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2189 * whose corresponding errors may be ignored.
2190 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2192 public function getUserPermissionsErrors(
2193 $action, $user, $rigor = 'secure', $ignoreErrors = []
2195 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2197 // Remove the errors being ignored.
2198 foreach ( $errors as $index => $error ) {
2199 $errKey = is_array( $error ) ?
$error[0] : $error;
2201 if ( in_array( $errKey, $ignoreErrors ) ) {
2202 unset( $errors[$index] );
2204 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2205 unset( $errors[$index] );
2213 * Permissions checks that fail most often, and which are easiest to test.
2215 * @param string $action The action to check
2216 * @param User $user User to check
2217 * @param array $errors List of current errors
2218 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2219 * @param bool $short Short circuit on first error
2221 * @return array List of errors
2223 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2224 if ( !Hooks
::run( 'TitleQuickPermissions',
2225 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2230 if ( $action == 'create' ) {
2232 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2233 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2235 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2237 } elseif ( $action == 'move' ) {
2238 if ( !$user->isAllowed( 'move-rootuserpages' )
2239 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2240 // Show user page-specific message only if the user can move other pages
2241 $errors[] = [ 'cant-move-user-page' ];
2244 // Check if user is allowed to move files if it's a file
2245 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2246 $errors[] = [ 'movenotallowedfile' ];
2249 // Check if user is allowed to move category pages if it's a category page
2250 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2251 $errors[] = [ 'cant-move-category-page' ];
2254 if ( !$user->isAllowed( 'move' ) ) {
2255 // User can't move anything
2256 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2257 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2258 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2259 // custom message if logged-in users without any special rights can move
2260 $errors[] = [ 'movenologintext' ];
2262 $errors[] = [ 'movenotallowed' ];
2265 } elseif ( $action == 'move-target' ) {
2266 if ( !$user->isAllowed( 'move' ) ) {
2267 // User can't move anything
2268 $errors[] = [ 'movenotallowed' ];
2269 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2270 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2271 // Show user page-specific message only if the user can move other pages
2272 $errors[] = [ 'cant-move-to-user-page' ];
2273 } elseif ( !$user->isAllowed( 'move-categorypages' )
2274 && $this->mNamespace
== NS_CATEGORY
) {
2275 // Show category page-specific message only if the user can move other pages
2276 $errors[] = [ 'cant-move-to-category-page' ];
2278 } elseif ( !$user->isAllowed( $action ) ) {
2279 $errors[] = $this->missingPermissionError( $action, $short );
2286 * Add the resulting error code to the errors array
2288 * @param array $errors List of current errors
2289 * @param array $result Result of errors
2291 * @return array List of errors
2293 private function resultToError( $errors, $result ) {
2294 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2295 // A single array representing an error
2296 $errors[] = $result;
2297 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2298 // A nested array representing multiple errors
2299 $errors = array_merge( $errors, $result );
2300 } elseif ( $result !== '' && is_string( $result ) ) {
2301 // A string representing a message-id
2302 $errors[] = [ $result ];
2303 } elseif ( $result instanceof MessageSpecifier
) {
2304 // A message specifier representing an error
2305 $errors[] = [ $result ];
2306 } elseif ( $result === false ) {
2307 // a generic "We don't want them to do that"
2308 $errors[] = [ 'badaccess-group0' ];
2314 * Check various permission hooks
2316 * @param string $action The action to check
2317 * @param User $user User to check
2318 * @param array $errors List of current errors
2319 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2320 * @param bool $short Short circuit on first error
2322 * @return array List of errors
2324 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2325 // Use getUserPermissionsErrors instead
2327 // Avoid PHP 7.1 warning from passing $this by reference
2329 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2330 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2332 // Check getUserPermissionsErrors hook
2333 // Avoid PHP 7.1 warning from passing $this by reference
2335 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2336 $errors = $this->resultToError( $errors, $result );
2338 // Check getUserPermissionsErrorsExpensive hook
2341 && !( $short && count( $errors ) > 0 )
2342 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2344 $errors = $this->resultToError( $errors, $result );
2351 * Check permissions on special pages & namespaces
2353 * @param string $action The action to check
2354 * @param User $user User to check
2355 * @param array $errors List of current errors
2356 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2357 * @param bool $short Short circuit on first error
2359 * @return array List of errors
2361 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2362 # Only 'createaccount' can be performed on special pages,
2363 # which don't actually exist in the DB.
2364 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2365 $errors[] = [ 'ns-specialprotected' ];
2368 # Check $wgNamespaceProtection for restricted namespaces
2369 if ( $this->isNamespaceProtected( $user ) ) {
2370 $ns = $this->mNamespace
== NS_MAIN ?
2371 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2372 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2373 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2380 * Check sitewide CSS/JSON/JS permissions
2382 * @param string $action The action to check
2383 * @param User $user User to check
2384 * @param array $errors List of current errors
2385 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2386 * @param bool $short Short circuit on first error
2388 * @return array List of errors
2390 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2391 if ( $action != 'patrol' ) {
2393 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2394 // editinterface right. That's implemented as a restriction so no check needed here.
2395 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2396 $error = [ 'sitecssprotected', $action ];
2397 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2398 $error = [ 'sitejsonprotected', $action ];
2399 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2400 $error = [ 'sitejsprotected', $action ];
2401 } elseif ( $this->isRawHtmlMessage() ) {
2402 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2403 if ( !$user->isAllowed( 'editsitejs' ) ) {
2404 $error = [ 'sitejsprotected', $action ];
2405 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2406 $error = [ 'sitecssprotected', $action ];
2411 if ( $user->isAllowed( 'editinterface' ) ) {
2412 // Most users / site admins will probably find out about the new, more restrictive
2413 // permissions by failing to edit something. Give them more info.
2414 // TODO remove this a few release cycles after 1.32
2415 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2425 * Check CSS/JSON/JS sub-page permissions
2427 * @param string $action The action to check
2428 * @param User $user User to check
2429 * @param array $errors List of current errors
2430 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2431 * @param bool $short Short circuit on first error
2433 * @return array List of errors
2435 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2436 # Protect css/json/js subpages of user pages
2437 # XXX: this might be better using restrictions
2439 if ( $action === 'patrol' ) {
2443 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2444 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2446 $this->isUserCssConfigPage()
2447 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2449 $errors[] = [ 'mycustomcssprotected', $action ];
2451 $this->isUserJsonConfigPage()
2452 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2454 $errors[] = [ 'mycustomjsonprotected', $action ];
2456 $this->isUserJsConfigPage()
2457 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2459 $errors[] = [ 'mycustomjsprotected', $action ];
2462 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2463 // deletion/suppression which cannot be used for attacks and we want to avoid the
2464 // situation where an unprivileged user can post abusive content on their subpages
2465 // and only very highly privileged users could remove it.
2466 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2468 $this->isUserCssConfigPage()
2469 && !$user->isAllowed( 'editusercss' )
2471 $errors[] = [ 'customcssprotected', $action ];
2473 $this->isUserJsonConfigPage()
2474 && !$user->isAllowed( 'edituserjson' )
2476 $errors[] = [ 'customjsonprotected', $action ];
2478 $this->isUserJsConfigPage()
2479 && !$user->isAllowed( 'edituserjs' )
2481 $errors[] = [ 'customjsprotected', $action ];
2490 * Check against page_restrictions table requirements on this
2491 * page. The user must possess all required rights for this
2494 * @param string $action The action to check
2495 * @param User $user User to check
2496 * @param array $errors List of current errors
2497 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2498 * @param bool $short Short circuit on first error
2500 * @return array List of errors
2502 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2503 foreach ( $this->getRestrictions( $action ) as $right ) {
2504 // Backwards compatibility, rewrite sysop -> editprotected
2505 if ( $right == 'sysop' ) {
2506 $right = 'editprotected';
2508 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2509 if ( $right == 'autoconfirmed' ) {
2510 $right = 'editsemiprotected';
2512 if ( $right == '' ) {
2515 if ( !$user->isAllowed( $right ) ) {
2516 $errors[] = [ 'protectedpagetext', $right, $action ];
2517 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2518 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2526 * Check restrictions on cascading pages.
2528 * @param string $action The action to check
2529 * @param User $user User to check
2530 * @param array $errors List of current errors
2531 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2532 * @param bool $short Short circuit on first error
2534 * @return array List of errors
2536 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2537 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2538 # We /could/ use the protection level on the source page, but it's
2539 # fairly ugly as we have to establish a precedence hierarchy for pages
2540 # included by multiple cascade-protected pages. So just restrict
2541 # it to people with 'protect' permission, as they could remove the
2542 # protection anyway.
2543 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2544 # Cascading protection depends on more than this page...
2545 # Several cascading protected pages may include this page...
2546 # Check each cascading level
2547 # This is only for protection restrictions, not for all actions
2548 if ( isset( $restrictions[$action] ) ) {
2549 foreach ( $restrictions[$action] as $right ) {
2550 // Backwards compatibility, rewrite sysop -> editprotected
2551 if ( $right == 'sysop' ) {
2552 $right = 'editprotected';
2554 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2555 if ( $right == 'autoconfirmed' ) {
2556 $right = 'editsemiprotected';
2558 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2560 foreach ( $cascadingSources as $page ) {
2561 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2563 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2573 * Check action permissions not already checked in checkQuickPermissions
2575 * @param string $action The action to check
2576 * @param User $user User to check
2577 * @param array $errors List of current errors
2578 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2579 * @param bool $short Short circuit on first error
2581 * @return array List of errors
2583 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2584 global $wgDeleteRevisionsLimit, $wgLang;
2586 if ( $action == 'protect' ) {
2587 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2588 // If they can't edit, they shouldn't protect.
2589 $errors[] = [ 'protect-cantedit' ];
2591 } elseif ( $action == 'create' ) {
2592 $title_protection = $this->getTitleProtection();
2593 if ( $title_protection ) {
2594 if ( $title_protection['permission'] == ''
2595 ||
!$user->isAllowed( $title_protection['permission'] )
2599 User
::whoIs( $title_protection['user'] ),
2600 $title_protection['reason']
2604 } elseif ( $action == 'move' ) {
2605 // Check for immobile pages
2606 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2607 // Specific message for this case
2608 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2609 } elseif ( !$this->isMovable() ) {
2610 // Less specific message for rarer cases
2611 $errors[] = [ 'immobile-source-page' ];
2613 } elseif ( $action == 'move-target' ) {
2614 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2615 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2616 } elseif ( !$this->isMovable() ) {
2617 $errors[] = [ 'immobile-target-page' ];
2619 } elseif ( $action == 'delete' ) {
2620 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2621 if ( !$tempErrors ) {
2622 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2623 $user, $tempErrors, $rigor, true );
2625 if ( $tempErrors ) {
2626 // If protection keeps them from editing, they shouldn't be able to delete.
2627 $errors[] = [ 'deleteprotected' ];
2629 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2630 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2632 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2634 } elseif ( $action === 'undelete' ) {
2635 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2636 // Undeleting implies editing
2637 $errors[] = [ 'undelete-cantedit' ];
2639 if ( !$this->exists()
2640 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2642 // Undeleting where nothing currently exists implies creating
2643 $errors[] = [ 'undelete-cantcreate' ];
2650 * Check that the user isn't blocked from editing.
2652 * @param string $action The action to check
2653 * @param User $user User to check
2654 * @param array $errors List of current errors
2655 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2656 * @param bool $short Short circuit on first error
2658 * @return array List of errors
2660 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2661 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2662 // Account creation blocks handled at userlogin.
2663 // Unblocking handled in SpecialUnblock
2664 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2668 // Optimize for a very common case
2669 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2673 if ( $wgEmailConfirmToEdit
2674 && !$user->isEmailConfirmed()
2675 && $action === 'edit'
2677 $errors[] = [ 'confirmedittext' ];
2680 $useReplica = ( $rigor !== 'secure' );
2681 $block = $user->getBlock( $useReplica );
2683 // The block may explicitly allow an action (like "read" or "upload").
2684 if ( $block && $block->prevents( $action ) === false ) {
2688 // Determine if the user is blocked from this action on this page.
2689 // What gets passed into this method is a user right, not an action name.
2690 // There is no way to instantiate an action by restriction. However, this
2691 // will get the action where the restriction is the same. This may result
2692 // in actions being blocked that shouldn't be.
2694 if ( Action
::exists( $action ) ) {
2695 // Clone the title to prevent mutations to this object which is done
2696 // by Title::loadFromRow() in WikiPage::loadFromRow().
2697 $page = WikiPage
::factory( clone $this );
2698 // Creating an action will perform several database queries to ensure that
2699 // the action has not been overridden by the content type.
2700 // @todo FIXME: Pass the relevant context into this function.
2701 $actionObj = Action
::factory( $action, $page, RequestContext
::getMain() );
2702 // Ensure that the retrieved action matches the restriction.
2703 if ( $actionObj && $actionObj->getRestriction() !== $action ) {
2708 // If no action object is returned, assume that the action requires unblock
2709 // which is the default.
2710 if ( !$actionObj ||
$actionObj->requiresUnblock() ) {
2711 if ( $user->isBlockedFrom( $this, $useReplica ) ) {
2712 // @todo FIXME: Pass the relevant context into this function.
2714 ?
$block->getPermissionsError( RequestContext
::getMain() )
2715 : [ 'actionblockedtext' ];
2723 * Check that the user is allowed to read this page.
2725 * @param string $action The action to check
2726 * @param User $user User to check
2727 * @param array $errors List of current errors
2728 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2729 * @param bool $short Short circuit on first error
2731 * @return array List of errors
2733 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2734 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2736 $whitelisted = false;
2737 if ( User
::isEveryoneAllowed( 'read' ) ) {
2738 # Shortcut for public wikis, allows skipping quite a bit of code
2739 $whitelisted = true;
2740 } elseif ( $user->isAllowed( 'read' ) ) {
2741 # If the user is allowed to read pages, he is allowed to read all pages
2742 $whitelisted = true;
2743 } elseif ( $this->isSpecial( 'Userlogin' )
2744 ||
$this->isSpecial( 'PasswordReset' )
2745 ||
$this->isSpecial( 'Userlogout' )
2747 # Always grant access to the login page.
2748 # Even anons need to be able to log in.
2749 $whitelisted = true;
2750 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2751 # Time to check the whitelist
2752 # Only do these checks is there's something to check against
2753 $name = $this->getPrefixedText();
2754 $dbName = $this->getPrefixedDBkey();
2756 // Check for explicit whitelisting with and without underscores
2757 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2758 $whitelisted = true;
2759 } elseif ( $this->mNamespace
== NS_MAIN
) {
2760 # Old settings might have the title prefixed with
2761 # a colon for main-namespace pages
2762 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2763 $whitelisted = true;
2765 } elseif ( $this->isSpecialPage() ) {
2766 # If it's a special page, ditch the subpage bit and check again
2767 $name = $this->mDbkeyform
;
2768 list( $name, /* $subpage */ ) =
2769 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
2770 resolveAlias( $name );
2772 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2773 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2774 $whitelisted = true;
2780 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2781 $name = $this->getPrefixedText();
2782 // Check for regex whitelisting
2783 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2784 if ( preg_match( $listItem, $name ) ) {
2785 $whitelisted = true;
2791 if ( !$whitelisted ) {
2792 # If the title is not whitelisted, give extensions a chance to do so...
2793 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2794 if ( !$whitelisted ) {
2795 $errors[] = $this->missingPermissionError( $action, $short );
2803 * Get a description array when the user doesn't have the right to perform
2804 * $action (i.e. when User::isAllowed() returns false)
2806 * @param string $action The action to check
2807 * @param bool $short Short circuit on first error
2808 * @return array Array containing an error message key and any parameters
2810 private function missingPermissionError( $action, $short ) {
2811 // We avoid expensive display logic for quickUserCan's and such
2813 return [ 'badaccess-group0' ];
2816 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2820 * Can $user perform $action on this page? This is an internal function,
2821 * with multiple levels of checks depending on performance needs; see $rigor below.
2822 * It does not check wfReadOnly().
2824 * @param string $action Action that permission needs to be checked for
2825 * @param User $user User to check
2826 * @param string $rigor One of (quick,full,secure)
2827 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2828 * - full : does cheap and expensive checks possibly from a replica DB
2829 * - secure : does cheap and expensive checks, using the master as needed
2830 * @param bool $short Set this to true to stop after the first permission error.
2831 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2833 protected function getUserPermissionsErrorsInternal(
2834 $action, $user, $rigor = 'secure', $short = false
2836 if ( $rigor === true ) {
2837 $rigor = 'secure'; // b/c
2838 } elseif ( $rigor === false ) {
2839 $rigor = 'quick'; // b/c
2840 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2841 throw new Exception( "Invalid rigor parameter '$rigor'." );
2844 # Read has special handling
2845 if ( $action == 'read' ) {
2847 'checkPermissionHooks',
2848 'checkReadPermissions',
2849 'checkUserBlock', // for wgBlockDisablesLogin
2851 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2852 # or checkUserConfigPermissions here as it will lead to duplicate
2853 # error messages. This is okay to do since anywhere that checks for
2854 # create will also check for edit, and those checks are called for edit.
2855 } elseif ( $action == 'create' ) {
2857 'checkQuickPermissions',
2858 'checkPermissionHooks',
2859 'checkPageRestrictions',
2860 'checkCascadingSourcesRestrictions',
2861 'checkActionPermissions',
2866 'checkQuickPermissions',
2867 'checkPermissionHooks',
2868 'checkSpecialsAndNSPermissions',
2869 'checkSiteConfigPermissions',
2870 'checkUserConfigPermissions',
2871 'checkPageRestrictions',
2872 'checkCascadingSourcesRestrictions',
2873 'checkActionPermissions',
2879 foreach ( $checks as $method ) {
2880 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2882 if ( $short && $errors !== [] ) {
2891 * Get a filtered list of all restriction types supported by this wiki.
2892 * @param bool $exists True to get all restriction types that apply to
2893 * titles that do exist, False for all restriction types that apply to
2894 * titles that do not exist
2897 public static function getFilteredRestrictionTypes( $exists = true ) {
2898 global $wgRestrictionTypes;
2899 $types = $wgRestrictionTypes;
2901 # Remove the create restriction for existing titles
2902 $types = array_diff( $types, [ 'create' ] );
2904 # Only the create and upload restrictions apply to non-existing titles
2905 $types = array_intersect( $types, [ 'create', 'upload' ] );
2911 * Returns restriction types for the current Title
2913 * @return array Applicable restriction types
2915 public function getRestrictionTypes() {
2916 if ( $this->isSpecialPage() ) {
2920 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2922 if ( $this->mNamespace
!= NS_FILE
) {
2923 # Remove the upload restriction for non-file titles
2924 $types = array_diff( $types, [ 'upload' ] );
2927 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2929 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2930 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2936 * Is this title subject to title protection?
2937 * Title protection is the one applied against creation of such title.
2939 * @return array|bool An associative array representing any existent title
2940 * protection, or false if there's none.
2942 public function getTitleProtection() {
2943 $protection = $this->getTitleProtectionInternal();
2944 if ( $protection ) {
2945 if ( $protection['permission'] == 'sysop' ) {
2946 $protection['permission'] = 'editprotected'; // B/C
2948 if ( $protection['permission'] == 'autoconfirmed' ) {
2949 $protection['permission'] = 'editsemiprotected'; // B/C
2956 * Fetch title protection settings
2958 * To work correctly, $this->loadRestrictions() needs to have access to the
2959 * actual protections in the database without munging 'sysop' =>
2960 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2961 * callers probably want $this->getTitleProtection() instead.
2963 * @return array|bool
2965 protected function getTitleProtectionInternal() {
2966 // Can't protect pages in special namespaces
2967 if ( $this->mNamespace
< 0 ) {
2971 // Can't protect pages that exist.
2972 if ( $this->exists() ) {
2976 if ( $this->mTitleProtection
=== null ) {
2977 $dbr = wfGetDB( DB_REPLICA
);
2978 $commentStore = CommentStore
::getStore();
2979 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2980 $res = $dbr->select(
2981 [ 'protected_titles' ] +
$commentQuery['tables'],
2983 'user' => 'pt_user',
2984 'expiry' => 'pt_expiry',
2985 'permission' => 'pt_create_perm'
2986 ] +
$commentQuery['fields'],
2987 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2990 $commentQuery['joins']
2993 // fetchRow returns false if there are no rows.
2994 $row = $dbr->fetchRow( $res );
2996 $this->mTitleProtection
= [
2997 'user' => $row['user'],
2998 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2999 'permission' => $row['permission'],
3000 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
3003 $this->mTitleProtection
= false;
3006 return $this->mTitleProtection
;
3010 * Remove any title protection due to page existing
3012 public function deleteTitleProtection() {
3013 $dbw = wfGetDB( DB_MASTER
);
3017 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
3020 $this->mTitleProtection
= false;
3024 * Is this page "semi-protected" - the *only* protection levels are listed
3025 * in $wgSemiprotectedRestrictionLevels?
3027 * @param string $action Action to check (default: edit)
3030 public function isSemiProtected( $action = 'edit' ) {
3031 global $wgSemiprotectedRestrictionLevels;
3033 $restrictions = $this->getRestrictions( $action );
3034 $semi = $wgSemiprotectedRestrictionLevels;
3035 if ( !$restrictions ||
!$semi ) {
3036 // Not protected, or all protection is full protection
3040 // Remap autoconfirmed to editsemiprotected for BC
3041 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3042 $semi[$key] = 'editsemiprotected';
3044 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3045 $restrictions[$key] = 'editsemiprotected';
3048 return !array_diff( $restrictions, $semi );
3052 * Does the title correspond to a protected article?
3054 * @param string $action The action the page is protected from,
3055 * by default checks all actions.
3058 public function isProtected( $action = '' ) {
3059 global $wgRestrictionLevels;
3061 $restrictionTypes = $this->getRestrictionTypes();
3063 # Special pages have inherent protection
3064 if ( $this->isSpecialPage() ) {
3068 # Check regular protection levels
3069 foreach ( $restrictionTypes as $type ) {
3070 if ( $action == $type ||
$action == '' ) {
3071 $r = $this->getRestrictions( $type );
3072 foreach ( $wgRestrictionLevels as $level ) {
3073 if ( in_array( $level, $r ) && $level != '' ) {
3084 * Determines if $user is unable to edit this page because it has been protected
3085 * by $wgNamespaceProtection.
3087 * @param User $user User object to check permissions
3090 public function isNamespaceProtected( User
$user ) {
3091 global $wgNamespaceProtection;
3093 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3094 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3095 if ( $right != '' && !$user->isAllowed( $right ) ) {
3104 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3106 * @return bool If the page is subject to cascading restrictions.
3108 public function isCascadeProtected() {
3109 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3110 return ( $sources > 0 );
3114 * Determines whether cascading protection sources have already been loaded from
3117 * @param bool $getPages True to check if the pages are loaded, or false to check
3118 * if the status is loaded.
3119 * @return bool Whether or not the specified information has been loaded
3122 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3123 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3127 * Cascading protection: Get the source of any cascading restrictions on this page.
3129 * @param bool $getPages Whether or not to retrieve the actual pages
3130 * that the restrictions have come from and the actual restrictions
3132 * @return array Two elements: First is an array of Title objects of the
3133 * pages from which cascading restrictions have come, false for
3134 * none, or true if such restrictions exist but $getPages was not
3135 * set. Second is an array like that returned by
3136 * Title::getAllRestrictions(), or an empty array if $getPages is
3139 public function getCascadeProtectionSources( $getPages = true ) {
3140 $pagerestrictions = [];
3142 if ( $this->mCascadeSources
!== null && $getPages ) {
3143 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3144 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3145 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3148 $dbr = wfGetDB( DB_REPLICA
);
3150 if ( $this->mNamespace
== NS_FILE
) {
3151 $tables = [ 'imagelinks', 'page_restrictions' ];
3153 'il_to' => $this->mDbkeyform
,
3158 $tables = [ 'templatelinks', 'page_restrictions' ];
3160 'tl_namespace' => $this->mNamespace
,
3161 'tl_title' => $this->mDbkeyform
,
3168 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3169 'pr_expiry', 'pr_type', 'pr_level' ];
3170 $where_clauses[] = 'page_id=pr_page';
3173 $cols = [ 'pr_expiry' ];
3176 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3178 $sources = $getPages ?
[] : false;
3179 $now = wfTimestampNow();
3181 foreach ( $res as $row ) {
3182 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3183 if ( $expiry > $now ) {
3185 $page_id = $row->pr_page
;
3186 $page_ns = $row->page_namespace
;
3187 $page_title = $row->page_title
;
3188 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3189 # Add groups needed for each restriction type if its not already there
3190 # Make sure this restriction type still exists
3192 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3193 $pagerestrictions[$row->pr_type
] = [];
3197 isset( $pagerestrictions[$row->pr_type
] )
3198 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3200 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3209 $this->mCascadeSources
= $sources;
3210 $this->mCascadingRestrictions
= $pagerestrictions;
3212 $this->mHasCascadingRestrictions
= $sources;
3215 return [ $sources, $pagerestrictions ];
3219 * Accessor for mRestrictionsLoaded
3221 * @return bool Whether or not the page's restrictions have already been
3222 * loaded from the database
3225 public function areRestrictionsLoaded() {
3226 return $this->mRestrictionsLoaded
;
3230 * Accessor/initialisation for mRestrictions
3232 * @param string $action Action that permission needs to be checked for
3233 * @return array Restriction levels needed to take the action. All levels are
3234 * required. Note that restriction levels are normally user rights, but 'sysop'
3235 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3236 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3238 public function getRestrictions( $action ) {
3239 if ( !$this->mRestrictionsLoaded
) {
3240 $this->loadRestrictions();
3242 return $this->mRestrictions
[$action] ??
[];
3246 * Accessor/initialisation for mRestrictions
3248 * @return array Keys are actions, values are arrays as returned by
3249 * Title::getRestrictions()
3252 public function getAllRestrictions() {
3253 if ( !$this->mRestrictionsLoaded
) {
3254 $this->loadRestrictions();
3256 return $this->mRestrictions
;
3260 * Get the expiry time for the restriction against a given action
3262 * @param string $action
3263 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3264 * or not protected at all, or false if the action is not recognised.
3266 public function getRestrictionExpiry( $action ) {
3267 if ( !$this->mRestrictionsLoaded
) {
3268 $this->loadRestrictions();
3270 return $this->mRestrictionsExpiry
[$action] ??
false;
3274 * Returns cascading restrictions for the current article
3278 function areRestrictionsCascading() {
3279 if ( !$this->mRestrictionsLoaded
) {
3280 $this->loadRestrictions();
3283 return $this->mCascadeRestriction
;
3287 * Compiles list of active page restrictions from both page table (pre 1.10)
3288 * and page_restrictions table for this existing page.
3289 * Public for usage by LiquidThreads.
3291 * @param array $rows Array of db result objects
3292 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3293 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3294 * Edit and move sections are separated by a colon
3295 * Example: "edit=autoconfirmed,sysop:move=sysop"
3297 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3298 // This function will only read rows from a table that we migrated away
3299 // from before adding READ_LATEST support to loadRestrictions, so we
3300 // don't need to support reading from DB_MASTER here.
3301 $dbr = wfGetDB( DB_REPLICA
);
3303 $restrictionTypes = $this->getRestrictionTypes();
3305 foreach ( $restrictionTypes as $type ) {
3306 $this->mRestrictions
[$type] = [];
3307 $this->mRestrictionsExpiry
[$type] = 'infinity';
3310 $this->mCascadeRestriction
= false;
3312 # Backwards-compatibility: also load the restrictions from the page record (old format).
3313 if ( $oldFashionedRestrictions !== null ) {
3314 $this->mOldRestrictions
= $oldFashionedRestrictions;
3317 if ( $this->mOldRestrictions
=== false ) {
3318 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3319 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3322 if ( $this->mOldRestrictions
!= '' ) {
3323 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3324 $temp = explode( '=', trim( $restrict ) );
3325 if ( count( $temp ) == 1 ) {
3326 // old old format should be treated as edit/move restriction
3327 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3328 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3330 $restriction = trim( $temp[1] );
3331 if ( $restriction != '' ) { // some old entries are empty
3332 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3338 if ( count( $rows ) ) {
3339 # Current system - load second to make them override.
3340 $now = wfTimestampNow();
3342 # Cycle through all the restrictions.
3343 foreach ( $rows as $row ) {
3344 // Don't take care of restrictions types that aren't allowed
3345 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3349 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3351 // Only apply the restrictions if they haven't expired!
3352 if ( !$expiry ||
$expiry > $now ) {
3353 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3354 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3356 $this->mCascadeRestriction |
= $row->pr_cascade
;
3361 $this->mRestrictionsLoaded
= true;
3365 * Load restrictions from the page_restrictions table
3367 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3368 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3369 * Edit and move sections are separated by a colon
3370 * Example: "edit=autoconfirmed,sysop:move=sysop"
3371 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3372 * from the master DB.
3374 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3375 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
3376 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
3380 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3381 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3382 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3383 $id = $this->getArticleID();
3385 $fname = __METHOD__
;
3386 $loadRestrictionsFromDb = function ( Database
$dbr ) use ( $fname, $id ) {
3387 return iterator_to_array(
3389 'page_restrictions',
3390 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3391 [ 'pr_page' => $id ],
3397 if ( $readLatest ) {
3398 $dbr = wfGetDB( DB_MASTER
);
3399 $rows = $loadRestrictionsFromDb( $dbr );
3401 $cache = ObjectCache
::getMainWANInstance();
3402 $rows = $cache->getWithSetCallback(
3403 // Page protections always leave a new null revision
3404 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3406 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3407 $dbr = wfGetDB( DB_REPLICA
);
3409 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3411 return $loadRestrictionsFromDb( $dbr );
3416 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3418 $title_protection = $this->getTitleProtectionInternal();
3420 if ( $title_protection ) {
3421 $now = wfTimestampNow();
3422 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3424 if ( !$expiry ||
$expiry > $now ) {
3425 // Apply the restrictions
3426 $this->mRestrictionsExpiry
['create'] = $expiry;
3427 $this->mRestrictions
['create'] =
3428 explode( ',', trim( $title_protection['permission'] ) );
3429 } else { // Get rid of the old restrictions
3430 $this->mTitleProtection
= false;
3433 $this->mRestrictionsExpiry
['create'] = 'infinity';
3435 $this->mRestrictionsLoaded
= true;
3440 * Flush the protection cache in this object and force reload from the database.
3441 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3443 public function flushRestrictions() {
3444 $this->mRestrictionsLoaded
= false;
3445 $this->mTitleProtection
= null;
3449 * Purge expired restrictions from the page_restrictions table
3451 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3453 static function purgeExpiredRestrictions() {
3454 if ( wfReadOnly() ) {
3458 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3459 wfGetDB( DB_MASTER
),
3461 function ( IDatabase
$dbw, $fname ) {
3462 $config = MediaWikiServices
::getInstance()->getMainConfig();
3463 $ids = $dbw->selectFieldValues(
3464 'page_restrictions',
3466 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3468 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3471 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3476 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3477 wfGetDB( DB_MASTER
),
3479 function ( IDatabase
$dbw, $fname ) {
3482 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3490 * Does this have subpages? (Warning, usually requires an extra DB query.)
3494 public function hasSubpages() {
3495 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3500 # We dynamically add a member variable for the purpose of this method
3501 # alone to cache the result. There's no point in having it hanging
3502 # around uninitialized in every Title object; therefore we only add it
3503 # if needed and don't declare it statically.
3504 if ( $this->mHasSubpages
=== null ) {
3505 $this->mHasSubpages
= false;
3506 $subpages = $this->getSubpages( 1 );
3507 if ( $subpages instanceof TitleArray
) {
3508 $this->mHasSubpages
= (bool)$subpages->count();
3512 return $this->mHasSubpages
;
3516 * Get all subpages of this page.
3518 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3519 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3520 * doesn't allow subpages
3522 public function getSubpages( $limit = -1 ) {
3523 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3527 $dbr = wfGetDB( DB_REPLICA
);
3528 $conds['page_namespace'] = $this->mNamespace
;
3529 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3531 if ( $limit > -1 ) {
3532 $options['LIMIT'] = $limit;
3534 return TitleArray
::newFromResult(
3535 $dbr->select( 'page',
3536 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3545 * Is there a version of this page in the deletion archive?
3547 * @return int The number of archived revisions
3549 public function isDeleted() {
3550 if ( $this->mNamespace
< 0 ) {
3553 $dbr = wfGetDB( DB_REPLICA
);
3555 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3556 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3559 if ( $this->mNamespace
== NS_FILE
) {
3560 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3561 [ 'fa_name' => $this->mDbkeyform
],
3570 * Is there a version of this page in the deletion archive?
3574 public function isDeletedQuick() {
3575 if ( $this->mNamespace
< 0 ) {
3578 $dbr = wfGetDB( DB_REPLICA
);
3579 $deleted = (bool)$dbr->selectField( 'archive', '1',
3580 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3583 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3584 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3585 [ 'fa_name' => $this->mDbkeyform
],
3593 * Get the article ID for this Title from the link cache,
3594 * adding it if necessary
3596 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3598 * @return int The ID
3600 public function getArticleID( $flags = 0 ) {
3601 if ( $this->mNamespace
< 0 ) {
3602 $this->mArticleID
= 0;
3603 return $this->mArticleID
;
3605 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3606 if ( $flags & self
::GAID_FOR_UPDATE
) {
3607 $oldUpdate = $linkCache->forUpdate( true );
3608 $linkCache->clearLink( $this );
3609 $this->mArticleID
= $linkCache->addLinkObj( $this );
3610 $linkCache->forUpdate( $oldUpdate );
3612 if ( $this->mArticleID
== -1 ) {
3613 $this->mArticleID
= $linkCache->addLinkObj( $this );
3616 return $this->mArticleID
;
3620 * Is this an article that is a redirect page?
3621 * Uses link cache, adding it if necessary
3623 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3626 public function isRedirect( $flags = 0 ) {
3627 if ( !is_null( $this->mRedirect
) ) {
3628 return $this->mRedirect
;
3630 if ( !$this->getArticleID( $flags ) ) {
3631 $this->mRedirect
= false;
3632 return $this->mRedirect
;
3635 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3636 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3637 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3638 if ( $cached === null ) {
3639 # Trust LinkCache's state over our own
3640 # LinkCache is telling us that the page doesn't exist, despite there being cached
3641 # data relating to an existing page in $this->mArticleID. Updaters should clear
3642 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3643 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3644 # LinkCache to refresh its data from the master.
3645 $this->mRedirect
= false;
3646 return $this->mRedirect
;
3649 $this->mRedirect
= (bool)$cached;
3651 return $this->mRedirect
;
3655 * What is the length of this page?
3656 * Uses link cache, adding it if necessary
3658 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3661 public function getLength( $flags = 0 ) {
3662 if ( $this->mLength
!= -1 ) {
3663 return $this->mLength
;
3665 if ( !$this->getArticleID( $flags ) ) {
3667 return $this->mLength
;
3669 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3670 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3671 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3672 if ( $cached === null ) {
3673 # Trust LinkCache's state over our own, as for isRedirect()
3675 return $this->mLength
;
3678 $this->mLength
= intval( $cached );
3680 return $this->mLength
;
3684 * What is the page_latest field for this page?
3686 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3687 * @return int Int or 0 if the page doesn't exist
3689 public function getLatestRevID( $flags = 0 ) {
3690 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3691 return intval( $this->mLatestID
);
3693 if ( !$this->getArticleID( $flags ) ) {
3694 $this->mLatestID
= 0;
3695 return $this->mLatestID
;
3697 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3698 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3699 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3700 if ( $cached === null ) {
3701 # Trust LinkCache's state over our own, as for isRedirect()
3702 $this->mLatestID
= 0;
3703 return $this->mLatestID
;
3706 $this->mLatestID
= intval( $cached );
3708 return $this->mLatestID
;
3712 * This clears some fields in this object, and clears any associated
3713 * keys in the "bad links" section of the link cache.
3715 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3716 * loading of the new page_id. It's also called from
3717 * WikiPage::doDeleteArticleReal()
3719 * @param int $newid The new Article ID
3721 public function resetArticleID( $newid ) {
3722 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3723 $linkCache->clearLink( $this );
3725 if ( $newid === false ) {
3726 $this->mArticleID
= -1;
3728 $this->mArticleID
= intval( $newid );
3730 $this->mRestrictionsLoaded
= false;
3731 $this->mRestrictions
= [];
3732 $this->mOldRestrictions
= false;
3733 $this->mRedirect
= null;
3734 $this->mLength
= -1;
3735 $this->mLatestID
= false;
3736 $this->mContentModel
= false;
3737 $this->mEstimateRevisions
= null;
3738 $this->mPageLanguage
= false;
3739 $this->mDbPageLanguage
= false;
3740 $this->mIsBigDeletion
= null;
3743 public static function clearCaches() {
3744 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3745 $linkCache->clear();
3747 $titleCache = self
::getTitleCache();
3748 $titleCache->clear();
3752 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3754 * @param string $text Containing title to capitalize
3755 * @param int $ns Namespace index, defaults to NS_MAIN
3756 * @return string Containing capitalized title
3758 public static function capitalize( $text, $ns = NS_MAIN
) {
3759 if ( MWNamespace
::isCapitalized( $ns ) ) {
3760 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3767 * Secure and split - main initialisation function for this object
3769 * Assumes that mDbkeyform has been set, and is urldecoded
3770 * and uses underscores, but not otherwise munged. This function
3771 * removes illegal characters, splits off the interwiki and
3772 * namespace prefixes, sets the other forms, and canonicalizes
3775 * @throws MalformedTitleException On invalid titles
3776 * @return bool True on success
3778 private function secureAndSplit() {
3779 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3780 // the parsing code with Title, while avoiding massive refactoring.
3781 // @todo: get rid of secureAndSplit, refactor parsing code.
3782 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3783 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3784 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3785 // MalformedTitleException can be thrown here
3786 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3789 $this->setFragment( '#' . $parts['fragment'] );
3790 $this->mInterwiki
= $parts['interwiki'];
3791 $this->mLocalInterwiki
= $parts['local_interwiki'];
3792 $this->mNamespace
= $parts['namespace'];
3793 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3795 $this->mDbkeyform
= $parts['dbkey'];
3796 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3797 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3799 # We already know that some pages won't be in the database!
3800 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3801 $this->mArticleID
= 0;
3808 * Get an array of Title objects linking to this Title
3809 * Also stores the IDs in the link cache.
3811 * WARNING: do not use this function on arbitrary user-supplied titles!
3812 * On heavily-used templates it will max out the memory.
3814 * @param array $options May be FOR UPDATE
3815 * @param string $table Table name
3816 * @param string $prefix Fields prefix
3817 * @return Title[] Array of Title objects linking here
3819 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3820 if ( count( $options ) > 0 ) {
3821 $db = wfGetDB( DB_MASTER
);
3823 $db = wfGetDB( DB_REPLICA
);
3828 self
::getSelectFields(),
3830 "{$prefix}_from=page_id",
3831 "{$prefix}_namespace" => $this->mNamespace
,
3832 "{$prefix}_title" => $this->mDbkeyform
],
3838 if ( $res->numRows() ) {
3839 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3840 foreach ( $res as $row ) {
3841 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3843 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3844 $retVal[] = $titleObj;
3852 * Get an array of Title objects using this Title as a template
3853 * Also stores the IDs in the link cache.
3855 * WARNING: do not use this function on arbitrary user-supplied titles!
3856 * On heavily-used templates it will max out the memory.
3858 * @param array $options Query option to Database::select()
3859 * @return Title[] Array of Title the Title objects linking here
3861 public function getTemplateLinksTo( $options = [] ) {
3862 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3866 * Get an array of Title objects linked from this Title
3867 * Also stores the IDs in the link cache.
3869 * WARNING: do not use this function on arbitrary user-supplied titles!
3870 * On heavily-used templates it will max out the memory.
3872 * @param array $options Query option to Database::select()
3873 * @param string $table Table name
3874 * @param string $prefix Fields prefix
3875 * @return array Array of Title objects linking here
3877 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3878 $id = $this->getArticleID();
3880 # If the page doesn't exist; there can't be any link from this page
3885 $db = wfGetDB( DB_REPLICA
);
3887 $blNamespace = "{$prefix}_namespace";
3888 $blTitle = "{$prefix}_title";
3890 $pageQuery = WikiPage
::getQueryInfo();
3892 [ $table, 'nestpage' => $pageQuery['tables'] ],
3894 [ $blNamespace, $blTitle ],
3895 $pageQuery['fields']
3897 [ "{$prefix}_from" => $id ],
3902 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3903 ] ] +
$pageQuery['joins']
3907 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3908 foreach ( $res as $row ) {
3909 if ( $row->page_id
) {
3910 $titleObj = self
::newFromRow( $row );
3912 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3913 $linkCache->addBadLinkObj( $titleObj );
3915 $retVal[] = $titleObj;
3922 * Get an array of Title objects used on this Title as a template
3923 * Also stores the IDs in the link cache.
3925 * WARNING: do not use this function on arbitrary user-supplied titles!
3926 * On heavily-used templates it will max out the memory.
3928 * @param array $options May be FOR UPDATE
3929 * @return Title[] Array of Title the Title objects used here
3931 public function getTemplateLinksFrom( $options = [] ) {
3932 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3936 * Get an array of Title objects referring to non-existent articles linked
3939 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3940 * should use redirect table in this case).
3941 * @return Title[] Array of Title the Title objects
3943 public function getBrokenLinksFrom() {
3944 if ( $this->getArticleID() == 0 ) {
3945 # All links from article ID 0 are false positives
3949 $dbr = wfGetDB( DB_REPLICA
);
3950 $res = $dbr->select(
3951 [ 'page', 'pagelinks' ],
3952 [ 'pl_namespace', 'pl_title' ],
3954 'pl_from' => $this->getArticleID(),
3955 'page_namespace IS NULL'
3961 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3967 foreach ( $res as $row ) {
3968 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3974 * Get a list of URLs to purge from the CDN cache when this
3977 * @return string[] Array of String the URLs
3979 public function getCdnUrls() {
3981 $this->getInternalURL(),
3982 $this->getInternalURL( 'action=history' )
3985 $pageLang = $this->getPageLanguage();
3986 if ( $pageLang->hasVariants() ) {
3987 $variants = $pageLang->getVariants();
3988 foreach ( $variants as $vCode ) {
3989 $urls[] = $this->getInternalURL( $vCode );
3993 // If we are looking at a css/js user subpage, purge the action=raw.
3994 if ( $this->isUserJsConfigPage() ) {
3995 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3996 } elseif ( $this->isUserJsonConfigPage() ) {
3997 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3998 } elseif ( $this->isUserCssConfigPage() ) {
3999 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
4002 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
4007 * Purge all applicable CDN URLs
4009 public function purgeSquid() {
4010 DeferredUpdates
::addUpdate(
4011 new CdnCacheUpdate( $this->getCdnUrls() ),
4012 DeferredUpdates
::PRESEND
4017 * Check whether a given move operation would be valid.
4018 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
4020 * @deprecated since 1.25, use MovePage's methods instead
4021 * @param Title &$nt The new title
4022 * @param bool $auth Whether to check user permissions (uses $wgUser)
4023 * @param string $reason Is the log summary of the move, used for spam checking
4024 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4026 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4029 if ( !( $nt instanceof Title
) ) {
4030 // Normally we'd add this to $errors, but we'll get
4031 // lots of syntax errors if $nt is not an object
4032 return [ [ 'badtitletext' ] ];
4035 $mp = new MovePage( $this, $nt );
4036 $errors = $mp->isValidMove()->getErrorsArray();
4038 $errors = wfMergeErrorArrays(
4040 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4044 return $errors ?
: true;
4048 * Check if the requested move target is a valid file move target
4049 * @todo move this to MovePage
4050 * @param Title $nt Target title
4051 * @return array List of errors
4053 protected function validateFileMoveOperation( $nt ) {
4058 $destFile = wfLocalFile( $nt );
4059 $destFile->load( File
::READ_LATEST
);
4060 if ( !$wgUser->isAllowed( 'reupload-shared' )
4061 && !$destFile->exists() && wfFindFile( $nt )
4063 $errors[] = [ 'file-exists-sharedrepo' ];
4070 * Move a title to a new location
4072 * @deprecated since 1.25, use the MovePage class instead
4073 * @param Title &$nt The new title
4074 * @param bool $auth Indicates whether $wgUser's permissions
4076 * @param string $reason The reason for the move
4077 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4078 * Ignored if the user doesn't have the suppressredirect right.
4079 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4080 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4082 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4083 array $changeTags = []
4086 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4087 if ( is_array( $err ) ) {
4088 // Auto-block user's IP if the account was "hard" blocked
4089 $wgUser->spreadAnyEditBlock();
4092 // Check suppressredirect permission
4093 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4094 $createRedirect = true;
4097 $mp = new MovePage( $this, $nt );
4098 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4099 if ( $status->isOK() ) {
4102 return $status->getErrorsArray();
4107 * Move this page's subpages to be subpages of $nt
4109 * @param Title $nt Move target
4110 * @param bool $auth Whether $wgUser's permissions should be checked
4111 * @param string $reason The reason for the move
4112 * @param bool $createRedirect Whether to create redirects from the old subpages to
4113 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4114 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4115 * @return array Array with old page titles as keys, and strings (new page titles) or
4116 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4117 * getUserPermissionsErrors()-like error array with numeric indices if
4118 * no pages were moved
4120 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4121 array $changeTags = []
4123 global $wgMaximumMovedPages;
4124 // Check permissions
4125 if ( !$this->userCan( 'move-subpages' ) ) {
4127 [ 'cant-move-subpages' ],
4130 // Do the source and target namespaces support subpages?
4131 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4133 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4136 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4138 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4142 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4145 foreach ( $subpages as $oldSubpage ) {
4147 if ( $count > $wgMaximumMovedPages ) {
4148 $retval[$oldSubpage->getPrefixedText()] = [
4149 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4154 // We don't know whether this function was called before
4155 // or after moving the root page, so check both
4157 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4158 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4160 // When moving a page to a subpage of itself,
4161 // don't move it twice
4164 $newPageName = preg_replace(
4165 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4166 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4167 $oldSubpage->getDBkey() );
4168 if ( $oldSubpage->isTalkPage() ) {
4169 $newNs = $nt->getTalkPage()->getNamespace();
4171 $newNs = $nt->getSubjectPage()->getNamespace();
4173 # T16385: we need makeTitleSafe because the new page names may
4174 # be longer than 255 characters.
4175 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4177 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4178 if ( $success === true ) {
4179 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4181 $retval[$oldSubpage->getPrefixedText()] = $success;
4188 * Checks if this page is just a one-rev redirect.
4189 * Adds lock, so don't use just for light purposes.
4193 public function isSingleRevRedirect() {
4194 global $wgContentHandlerUseDB;
4196 $dbw = wfGetDB( DB_MASTER
);
4199 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4200 if ( $wgContentHandlerUseDB ) {
4201 $fields[] = 'page_content_model';
4204 $row = $dbw->selectRow( 'page',
4210 # Cache some fields we may want
4211 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4212 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4213 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4214 $this->mContentModel
= $row && isset( $row->page_content_model
)
4215 ?
strval( $row->page_content_model
)
4218 if ( !$this->mRedirect
) {
4221 # Does the article have a history?
4222 $row = $dbw->selectField( [ 'page', 'revision' ],
4224 [ 'page_namespace' => $this->mNamespace
,
4225 'page_title' => $this->mDbkeyform
,
4227 'page_latest != rev_id'
4232 # Return true if there was no history
4233 return ( $row === false );
4237 * Checks if $this can be moved to a given Title
4238 * - Selects for update, so don't call it unless you mean business
4240 * @deprecated since 1.25, use MovePage's methods instead
4241 * @param Title $nt The new title to check
4244 public function isValidMoveTarget( $nt ) {
4245 # Is it an existing file?
4246 if ( $nt->getNamespace() == NS_FILE
) {
4247 $file = wfLocalFile( $nt );
4248 $file->load( File
::READ_LATEST
);
4249 if ( $file->exists() ) {
4250 wfDebug( __METHOD__
. ": file exists\n" );
4254 # Is it a redirect with no history?
4255 if ( !$nt->isSingleRevRedirect() ) {
4256 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4259 # Get the article text
4260 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4261 if ( !is_object( $rev ) ) {
4264 $content = $rev->getContent();
4265 # Does the redirect point to the source?
4266 # Or is it a broken self-redirect, usually caused by namespace collisions?
4267 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4269 if ( $redirTitle ) {
4270 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4271 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4272 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4278 # Fail safe (not a redirect after all. strange.)
4279 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4280 " is a redirect, but it doesn't contain a valid redirect.\n" );
4286 * Get categories to which this Title belongs and return an array of
4287 * categories' names.
4289 * @return array Array of parents in the form:
4290 * $parent => $currentarticle
4292 public function getParentCategories() {
4295 $titleKey = $this->getArticleID();
4297 if ( $titleKey === 0 ) {
4301 $dbr = wfGetDB( DB_REPLICA
);
4303 $res = $dbr->select(
4306 [ 'cl_from' => $titleKey ],
4310 if ( $res->numRows() > 0 ) {
4311 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4312 foreach ( $res as $row ) {
4313 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4314 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4315 $this->getFullText();
4322 * Get a tree of parent categories
4324 * @param array $children Array with the children in the keys, to check for circular refs
4325 * @return array Tree of parent categories
4327 public function getParentCategoryTree( $children = [] ) {
4329 $parents = $this->getParentCategories();
4332 foreach ( $parents as $parent => $current ) {
4333 if ( array_key_exists( $parent, $children ) ) {
4334 # Circular reference
4335 $stack[$parent] = [];
4337 $nt = self
::newFromText( $parent );
4339 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4349 * Get an associative array for selecting this title from
4352 * @return array Array suitable for the $where parameter of DB::select()
4354 public function pageCond() {
4355 if ( $this->mArticleID
> 0 ) {
4356 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4357 return [ 'page_id' => $this->mArticleID
];
4359 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4364 * Get next/previous revision ID relative to another revision ID
4365 * @param int $revId Revision ID. Get the revision that was before this one.
4366 * @param int $flags Title::GAID_FOR_UPDATE
4367 * @param string $dir 'next' or 'prev'
4368 * @return int|bool New revision ID, or false if none exists
4370 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4371 $revId = (int)$revId;
4372 if ( $dir === 'next' ) {
4375 } elseif ( $dir === 'prev' ) {
4379 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4382 if ( $flags & self
::GAID_FOR_UPDATE
) {
4383 $db = wfGetDB( DB_MASTER
);
4385 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4388 // Intentionally not caring if the specified revision belongs to this
4389 // page. We only care about the timestamp.
4390 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4391 if ( $ts === false ) {
4392 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4393 if ( $ts === false ) {
4394 // Or should this throw an InvalidArgumentException or something?
4398 $ts = $db->addQuotes( $ts );
4400 $revId = $db->selectField( 'revision', 'rev_id',
4402 'rev_page' => $this->getArticleID( $flags ),
4403 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4407 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4408 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4412 if ( $revId === false ) {
4415 return intval( $revId );
4420 * Get the revision ID of the previous revision
4422 * @param int $revId Revision ID. Get the revision that was before this one.
4423 * @param int $flags Title::GAID_FOR_UPDATE
4424 * @return int|bool Old revision ID, or false if none exists
4426 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4427 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4431 * Get the revision ID of the next revision
4433 * @param int $revId Revision ID. Get the revision that was after this one.
4434 * @param int $flags Title::GAID_FOR_UPDATE
4435 * @return int|bool Next revision ID, or false if none exists
4437 public function getNextRevisionID( $revId, $flags = 0 ) {
4438 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4442 * Get the first revision of the page
4444 * @param int $flags Title::GAID_FOR_UPDATE
4445 * @return Revision|null If page doesn't exist
4447 public function getFirstRevision( $flags = 0 ) {
4448 $pageId = $this->getArticleID( $flags );
4450 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4451 $revQuery = Revision
::getQueryInfo();
4452 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4453 [ 'rev_page' => $pageId ],
4456 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4457 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4462 return new Revision( $row, 0, $this );
4469 * Get the oldest revision timestamp of this page
4471 * @param int $flags Title::GAID_FOR_UPDATE
4472 * @return string|null MW timestamp
4474 public function getEarliestRevTime( $flags = 0 ) {
4475 $rev = $this->getFirstRevision( $flags );
4476 return $rev ?
$rev->getTimestamp() : null;
4480 * Check if this is a new page
4484 public function isNewPage() {
4485 $dbr = wfGetDB( DB_REPLICA
);
4486 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4490 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4494 public function isBigDeletion() {
4495 global $wgDeleteRevisionsLimit;
4497 if ( !$wgDeleteRevisionsLimit ) {
4501 if ( $this->mIsBigDeletion
=== null ) {
4502 $dbr = wfGetDB( DB_REPLICA
);
4504 $revCount = $dbr->selectRowCount(
4507 [ 'rev_page' => $this->getArticleID() ],
4509 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4512 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4515 return $this->mIsBigDeletion
;
4519 * Get the approximate revision count of this page.
4523 public function estimateRevisionCount() {
4524 if ( !$this->exists() ) {
4528 if ( $this->mEstimateRevisions
=== null ) {
4529 $dbr = wfGetDB( DB_REPLICA
);
4530 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4531 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4534 return $this->mEstimateRevisions
;
4538 * Get the number of revisions between the given revision.
4539 * Used for diffs and other things that really need it.
4541 * @param int|Revision $old Old revision or rev ID (first before range)
4542 * @param int|Revision $new New revision or rev ID (first after range)
4543 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4544 * @return int Number of revisions between these revisions.
4546 public function countRevisionsBetween( $old, $new, $max = null ) {
4547 if ( !( $old instanceof Revision
) ) {
4548 $old = Revision
::newFromTitle( $this, (int)$old );
4550 if ( !( $new instanceof Revision
) ) {
4551 $new = Revision
::newFromTitle( $this, (int)$new );
4553 if ( !$old ||
!$new ) {
4554 return 0; // nothing to compare
4556 $dbr = wfGetDB( DB_REPLICA
);
4558 'rev_page' => $this->getArticleID(),
4559 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4560 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4562 if ( $max !== null ) {
4563 return $dbr->selectRowCount( 'revision', '1',
4566 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4569 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4574 * Get the authors between the given revisions or revision IDs.
4575 * Used for diffs and other things that really need it.
4579 * @param int|Revision $old Old revision or rev ID (first before range by default)
4580 * @param int|Revision $new New revision or rev ID (first after range by default)
4581 * @param int $limit Maximum number of authors
4582 * @param string|array $options (Optional): Single option, or an array of options:
4583 * 'include_old' Include $old in the range; $new is excluded.
4584 * 'include_new' Include $new in the range; $old is excluded.
4585 * 'include_both' Include both $old and $new in the range.
4586 * Unknown option values are ignored.
4587 * @return array|null Names of revision authors in the range; null if not both revisions exist
4589 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4590 if ( !( $old instanceof Revision
) ) {
4591 $old = Revision
::newFromTitle( $this, (int)$old );
4593 if ( !( $new instanceof Revision
) ) {
4594 $new = Revision
::newFromTitle( $this, (int)$new );
4596 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4597 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4598 // in the sanity check below?
4599 if ( !$old ||
!$new ) {
4600 return null; // nothing to compare
4605 $options = (array)$options;
4606 if ( in_array( 'include_old', $options ) ) {
4609 if ( in_array( 'include_new', $options ) ) {
4612 if ( in_array( 'include_both', $options ) ) {
4616 // No DB query needed if $old and $new are the same or successive revisions:
4617 if ( $old->getId() === $new->getId() ) {
4618 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4620 [ $old->getUserText( Revision
::RAW
) ];
4621 } elseif ( $old->getId() === $new->getParentId() ) {
4622 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4623 $authors[] = $old->getUserText( Revision
::RAW
);
4624 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4625 $authors[] = $new->getUserText( Revision
::RAW
);
4627 } elseif ( $old_cmp === '>=' ) {
4628 $authors[] = $old->getUserText( Revision
::RAW
);
4629 } elseif ( $new_cmp === '<=' ) {
4630 $authors[] = $new->getUserText( Revision
::RAW
);
4634 $dbr = wfGetDB( DB_REPLICA
);
4635 $revQuery = Revision
::getQueryInfo();
4636 $authors = $dbr->selectFieldValues(
4637 $revQuery['tables'],
4638 $revQuery['fields']['rev_user_text'],
4640 'rev_page' => $this->getArticleID(),
4641 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4642 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4644 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4651 * Get the number of authors between the given revisions or revision IDs.
4652 * Used for diffs and other things that really need it.
4654 * @param int|Revision $old Old revision or rev ID (first before range by default)
4655 * @param int|Revision $new New revision or rev ID (first after range by default)
4656 * @param int $limit Maximum number of authors
4657 * @param string|array $options (Optional): Single option, or an array of options:
4658 * 'include_old' Include $old in the range; $new is excluded.
4659 * 'include_new' Include $new in the range; $old is excluded.
4660 * 'include_both' Include both $old and $new in the range.
4661 * Unknown option values are ignored.
4662 * @return int Number of revision authors in the range; zero if not both revisions exist
4664 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4665 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4666 return $authors ?
count( $authors ) : 0;
4670 * Compare with another title.
4672 * @param Title $title
4675 public function equals( Title
$title ) {
4676 // Note: === is necessary for proper matching of number-like titles.
4677 return $this->mInterwiki
=== $title->mInterwiki
4678 && $this->mNamespace
== $title->mNamespace
4679 && $this->mDbkeyform
=== $title->mDbkeyform
;
4683 * Check if this title is a subpage of another title
4685 * @param Title $title
4688 public function isSubpageOf( Title
$title ) {
4689 return $this->mInterwiki
=== $title->mInterwiki
4690 && $this->mNamespace
== $title->mNamespace
4691 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4695 * Check if page exists. For historical reasons, this function simply
4696 * checks for the existence of the title in the page table, and will
4697 * thus return false for interwiki links, special pages and the like.
4698 * If you want to know if a title can be meaningfully viewed, you should
4699 * probably call the isKnown() method instead.
4701 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4702 * from master/for update
4705 public function exists( $flags = 0 ) {
4706 $exists = $this->getArticleID( $flags ) != 0;
4707 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4712 * Should links to this title be shown as potentially viewable (i.e. as
4713 * "bluelinks"), even if there's no record by this title in the page
4716 * This function is semi-deprecated for public use, as well as somewhat
4717 * misleadingly named. You probably just want to call isKnown(), which
4718 * calls this function internally.
4720 * (ISSUE: Most of these checks are cheap, but the file existence check
4721 * can potentially be quite expensive. Including it here fixes a lot of
4722 * existing code, but we might want to add an optional parameter to skip
4723 * it and any other expensive checks.)
4727 public function isAlwaysKnown() {
4731 * Allows overriding default behavior for determining if a page exists.
4732 * If $isKnown is kept as null, regular checks happen. If it's
4733 * a boolean, this value is returned by the isKnown method.
4737 * @param Title $title
4738 * @param bool|null $isKnown
4740 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4742 if ( !is_null( $isKnown ) ) {
4746 if ( $this->isExternal() ) {
4747 return true; // any interwiki link might be viewable, for all we know
4750 switch ( $this->mNamespace
) {
4753 // file exists, possibly in a foreign repo
4754 return (bool)wfFindFile( $this );
4756 // valid special page
4757 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4758 exists( $this->mDbkeyform
);
4760 // selflink, possibly with fragment
4761 return $this->mDbkeyform
== '';
4763 // known system message
4764 return $this->hasSourceText() !== false;
4771 * Does this title refer to a page that can (or might) be meaningfully
4772 * viewed? In particular, this function may be used to determine if
4773 * links to the title should be rendered as "bluelinks" (as opposed to
4774 * "redlinks" to non-existent pages).
4775 * Adding something else to this function will cause inconsistency
4776 * since LinkHolderArray calls isAlwaysKnown() and does its own
4777 * page existence check.
4781 public function isKnown() {
4782 return $this->isAlwaysKnown() ||
$this->exists();
4786 * Does this page have source text?
4790 public function hasSourceText() {
4791 if ( $this->exists() ) {
4795 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4796 // If the page doesn't exist but is a known system message, default
4797 // message content will be displayed, same for language subpages-
4798 // Use always content language to avoid loading hundreds of languages
4799 // to get the link color.
4800 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4801 list( $name, ) = MessageCache
::singleton()->figureMessage(
4802 $contLang->lcfirst( $this->getText() )
4804 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4805 return $message->exists();
4812 * Get the default (plain) message contents for an page that overrides an
4813 * interface message key.
4815 * Primary use cases:
4818 * - Show default when viewing the page. The Article::getSubstituteContent
4819 * method displays the default message content, instead of the
4820 * 'noarticletext' placeholder message normally used.
4823 * - Title of edit page. When creating an interface message override,
4824 * the editor is told they are "Editing the page", instead of
4825 * "Creating the page". (EditPage::setHeaders)
4826 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4827 * or editing a an interface message override. (EditPage::showIntro)
4828 * - Opening the editor. The contents of the localisation message are used
4829 * as contents of the editor when creating a new page in the MediaWiki
4830 * namespace. This simplifies the process for editors when "changing"
4831 * an interface message by creating an override. (EditPage::getContentObject)
4832 * - Showing a diff. The left-hand side of a diff when an editor is
4833 * previewing their changes before saving the creation of a page in the
4834 * MediaWiki namespace. (EditPage::showDiff)
4835 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4836 * page with the proposed content matching the interface message default,
4837 * the save is rejected, the same way we disallow blank pages from being
4838 * created. (EditPage::internalAttemptSave)
4841 * - Default content, when using the 'prepend' or 'append' feature.
4844 * - Label the create action as "Edit", if the page can be an override.
4846 * @return string|bool
4848 public function getDefaultMessageText() {
4849 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4853 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4854 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4856 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4858 if ( $message->exists() ) {
4859 return $message->plain();
4866 * Updates page_touched for this page; called from LinksUpdate.php
4868 * @param string|null $purgeTime [optional] TS_MW timestamp
4869 * @return bool True if the update succeeded
4871 public function invalidateCache( $purgeTime = null ) {
4872 if ( wfReadOnly() ) {
4874 } elseif ( $this->mArticleID
=== 0 ) {
4875 return true; // avoid gap locking if we know it's not there
4878 $dbw = wfGetDB( DB_MASTER
);
4879 $dbw->onTransactionPreCommitOrIdle(
4880 function () use ( $dbw ) {
4881 ResourceLoaderWikiModule
::invalidateModuleCache(
4882 $this, null, null, $dbw->getDomainId() );
4887 $conds = $this->pageCond();
4888 DeferredUpdates
::addUpdate(
4889 new AutoCommitUpdate(
4892 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4893 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4896 [ 'page_touched' => $dbTimestamp ],
4897 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4900 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4903 DeferredUpdates
::PRESEND
4910 * Update page_touched timestamps and send CDN purge messages for
4911 * pages linking to this title. May be sent to the job queue depending
4912 * on the number of links. Typically called on create and delete.
4914 public function touchLinks() {
4915 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4916 if ( $this->mNamespace
== NS_CATEGORY
) {
4917 DeferredUpdates
::addUpdate(
4918 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4924 * Get the last touched timestamp
4926 * @param IDatabase|null $db
4927 * @return string|false Last-touched timestamp
4929 public function getTouched( $db = null ) {
4930 if ( $db === null ) {
4931 $db = wfGetDB( DB_REPLICA
);
4933 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4938 * Get the timestamp when this page was updated since the user last saw it.
4940 * @param User|null $user
4941 * @return string|null
4943 public function getNotificationTimestamp( $user = null ) {
4946 // Assume current user if none given
4950 // Check cache first
4951 $uid = $user->getId();
4955 // avoid isset here, as it'll return false for null entries
4956 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4957 return $this->mNotificationTimestamp
[$uid];
4959 // Don't cache too much!
4960 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4961 $this->mNotificationTimestamp
= [];
4964 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4965 $watchedItem = $store->getWatchedItem( $user, $this );
4966 if ( $watchedItem ) {
4967 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4969 $this->mNotificationTimestamp
[$uid] = false;
4972 return $this->mNotificationTimestamp
[$uid];
4976 * Generate strings used for xml 'id' names in monobook tabs
4978 * @param string $prepend Defaults to 'nstab-'
4979 * @return string XML 'id' name
4981 public function getNamespaceKey( $prepend = 'nstab-' ) {
4982 // Gets the subject namespace of this title
4983 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4984 // Prefer canonical namespace name for HTML IDs
4985 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4986 if ( $namespaceKey === false ) {
4987 // Fallback to localised text
4988 $namespaceKey = $this->getSubjectNsText();
4990 // Makes namespace key lowercase
4991 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4993 if ( $namespaceKey == '' ) {
4994 $namespaceKey = 'main';
4996 // Changes file to image for backwards compatibility
4997 if ( $namespaceKey == 'file' ) {
4998 $namespaceKey = 'image';
5000 return $prepend . $namespaceKey;
5004 * Get all extant redirects to this Title
5006 * @param int|null $ns Single namespace to consider; null to consider all namespaces
5007 * @return Title[] Array of Title redirects to this title
5009 public function getRedirectsHere( $ns = null ) {
5012 $dbr = wfGetDB( DB_REPLICA
);
5014 'rd_namespace' => $this->mNamespace
,
5015 'rd_title' => $this->mDbkeyform
,
5018 if ( $this->isExternal() ) {
5019 $where['rd_interwiki'] = $this->mInterwiki
;
5021 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
5023 if ( !is_null( $ns ) ) {
5024 $where['page_namespace'] = $ns;
5027 $res = $dbr->select(
5028 [ 'redirect', 'page' ],
5029 [ 'page_namespace', 'page_title' ],
5034 foreach ( $res as $row ) {
5035 $redirs[] = self
::newFromRow( $row );
5041 * Check if this Title is a valid redirect target
5045 public function isValidRedirectTarget() {
5046 global $wgInvalidRedirectTargets;
5048 if ( $this->isSpecialPage() ) {
5049 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5050 if ( $this->isSpecial( 'Userlogout' ) ) {
5054 foreach ( $wgInvalidRedirectTargets as $target ) {
5055 if ( $this->isSpecial( $target ) ) {
5065 * Get a backlink cache object
5067 * @return BacklinkCache
5069 public function getBacklinkCache() {
5070 return BacklinkCache
::get( $this );
5074 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5078 public function canUseNoindex() {
5079 global $wgExemptFromUserRobotsControl;
5081 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
5082 ? MWNamespace
::getContentNamespaces()
5083 : $wgExemptFromUserRobotsControl;
5085 return !in_array( $this->mNamespace
, $bannedNamespaces );
5089 * Returns the raw sort key to be used for categories, with the specified
5090 * prefix. This will be fed to Collation::getSortKey() to get a
5091 * binary sortkey that can be used for actual sorting.
5093 * @param string $prefix The prefix to be used, specified using
5094 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5098 public function getCategorySortkey( $prefix = '' ) {
5099 $unprefixed = $this->getText();
5101 // Anything that uses this hook should only depend
5102 // on the Title object passed in, and should probably
5103 // tell the users to run updateCollations.php --force
5104 // in order to re-sort existing category relations.
5105 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5106 if ( $prefix !== '' ) {
5107 # Separate with a line feed, so the unprefixed part is only used as
5108 # a tiebreaker when two pages have the exact same prefix.
5109 # In UCA, tab is the only character that can sort above LF
5110 # so we strip both of them from the original prefix.
5111 $prefix = strtr( $prefix, "\n\t", ' ' );
5112 return "$prefix\n$unprefixed";
5118 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5119 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5120 * the db, it will return NULL.
5122 * @return string|null|bool
5124 private function getDbPageLanguageCode() {
5125 global $wgPageLanguageUseDB;
5127 // check, if the page language could be saved in the database, and if so and
5128 // the value is not requested already, lookup the page language using LinkCache
5129 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5130 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5131 $linkCache->addLinkObj( $this );
5132 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5135 return $this->mDbPageLanguage
;
5139 * Get the language in which the content of this page is written in
5140 * wikitext. Defaults to content language, but in certain cases it can be
5141 * e.g. $wgLang (such as special pages, which are in the user language).
5146 public function getPageLanguage() {
5147 global $wgLang, $wgLanguageCode;
5148 if ( $this->isSpecialPage() ) {
5149 // special pages are in the user language
5153 // Checking if DB language is set
5154 $dbPageLanguage = $this->getDbPageLanguageCode();
5155 if ( $dbPageLanguage ) {
5156 return wfGetLangObj( $dbPageLanguage );
5159 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5160 // Note that this may depend on user settings, so the cache should
5161 // be only per-request.
5162 // NOTE: ContentHandler::getPageLanguage() may need to load the
5163 // content to determine the page language!
5164 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5166 $contentHandler = ContentHandler
::getForTitle( $this );
5167 $langObj = $contentHandler->getPageLanguage( $this );
5168 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5170 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5177 * Get the language in which the content of this page is written when
5178 * viewed by user. Defaults to content language, but in certain cases it can be
5179 * e.g. $wgLang (such as special pages, which are in the user language).
5184 public function getPageViewLanguage() {
5187 if ( $this->isSpecialPage() ) {
5188 // If the user chooses a variant, the content is actually
5189 // in a language whose code is the variant code.
5190 $variant = $wgLang->getPreferredVariant();
5191 if ( $wgLang->getCode() !== $variant ) {
5192 return Language
::factory( $variant );
5198 // Checking if DB language is set
5199 $dbPageLanguage = $this->getDbPageLanguageCode();
5200 if ( $dbPageLanguage ) {
5201 $pageLang = wfGetLangObj( $dbPageLanguage );
5202 $variant = $pageLang->getPreferredVariant();
5203 if ( $pageLang->getCode() !== $variant ) {
5204 $pageLang = Language
::factory( $variant );
5210 // @note Can't be cached persistently, depends on user settings.
5211 // @note ContentHandler::getPageViewLanguage() may need to load the
5212 // content to determine the page language!
5213 $contentHandler = ContentHandler
::getForTitle( $this );
5214 $pageLang = $contentHandler->getPageViewLanguage( $this );
5219 * Get a list of rendered edit notices for this page.
5221 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5222 * they will already be wrapped in paragraphs.
5225 * @param int $oldid Revision ID that's being edited
5228 public function getEditNotices( $oldid = 0 ) {
5231 // Optional notice for the entire namespace
5232 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5233 $msg = wfMessage( $editnotice_ns );
5234 if ( $msg->exists() ) {
5235 $html = $msg->parseAsBlock();
5236 // Edit notices may have complex logic, but output nothing (T91715)
5237 if ( trim( $html ) !== '' ) {
5238 $notices[$editnotice_ns] = Html
::rawElement(
5242 'mw-editnotice-namespace',
5243 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5250 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5251 // Optional notice for page itself and any parent page
5252 $editnotice_base = $editnotice_ns;
5253 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
5254 $editnotice_base .= '-' . $part;
5255 $msg = wfMessage( $editnotice_base );
5256 if ( $msg->exists() ) {
5257 $html = $msg->parseAsBlock();
5258 if ( trim( $html ) !== '' ) {
5259 $notices[$editnotice_base] = Html
::rawElement(
5263 'mw-editnotice-base',
5264 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5272 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5273 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5274 $msg = wfMessage( $editnoticeText );
5275 if ( $msg->exists() ) {
5276 $html = $msg->parseAsBlock();
5277 if ( trim( $html ) !== '' ) {
5278 $notices[$editnoticeText] = Html
::rawElement(
5282 'mw-editnotice-page',
5283 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5291 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5298 public function __sleep() {
5306 'mDefaultNamespace',
5310 public function __wakeup() {
5311 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5312 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5313 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );