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 static private $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
117 protected $mOldRestrictions = false;
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
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 * Escape a text fragment, say from a link, for a URL
773 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
775 * @param string $fragment Containing a URL or link fragment (after the "#")
776 * @return string Escaped string
778 static function escapeFragmentForURL( $fragment ) {
779 wfDeprecated( __METHOD__
, '1.30' );
780 # Note that we don't urlencode the fragment. urlencoded Unicode
781 # fragments appear not to work in IE (at least up to 7) or in at least
782 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
783 # to care if they aren't encoded.
784 return Sanitizer
::escapeId( $fragment, 'noninitial' );
788 * Callback for usort() to do title sorts by (namespace, title)
790 * @param LinkTarget $a
791 * @param LinkTarget $b
793 * @return int Result of string comparison, or namespace comparison
795 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
796 return $a->getNamespace() <=> $b->getNamespace()
797 ?
: strcmp( $a->getText(), $b->getText() );
801 * Returns true if the title is valid, false if it is invalid.
803 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
804 * Invalid titles may get returned from makeTitle(), and it may be useful to
805 * allow them to exist, e.g. in order to process log entries about pages in
806 * namespaces that belong to extensions that are no longer installed.
808 * @note This method is relatively expensive. When constructing Title
809 * objects that need to be valid, use an instantiator method that is guaranteed
810 * to return valid titles, such as makeTitleSafe() or newFromText().
814 public function isValid() {
815 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
820 $parser = MediaWikiServices
::getInstance()->getTitleParser();
821 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
823 } catch ( MalformedTitleException
$ex ) {
829 * Determine whether the object refers to a page within
830 * this project (either this wiki or a wiki with a local
831 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
833 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
835 public function isLocal() {
836 if ( $this->isExternal() ) {
837 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
839 return $iw->isLocal();
846 * Is this Title interwiki?
850 public function isExternal() {
851 return $this->mInterwiki
!== '';
855 * Get the interwiki prefix
857 * Use Title::isExternal to check if a interwiki is set
859 * @return string Interwiki prefix
861 public function getInterwiki() {
862 return $this->mInterwiki
;
866 * Was this a local interwiki link?
870 public function wasLocalInterwiki() {
871 return $this->mLocalInterwiki
;
875 * Determine whether the object refers to a page within
876 * this project and is transcludable.
878 * @return bool True if this is transcludable
880 public function isTrans() {
881 if ( !$this->isExternal() ) {
885 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
889 * Returns the DB name of the distant wiki which owns the object.
891 * @return string|false The DB name
893 public function getTransWikiID() {
894 if ( !$this->isExternal() ) {
898 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
902 * Get a TitleValue object representing this Title.
904 * @note Not all valid Titles have a corresponding valid TitleValue
905 * (e.g. TitleValues cannot represent page-local links that have a
906 * fragment but no title text).
908 * @return TitleValue|null
910 public function getTitleValue() {
911 if ( $this->mTitleValue
=== null ) {
913 $this->mTitleValue
= new TitleValue(
919 } catch ( InvalidArgumentException
$ex ) {
920 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
921 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
925 return $this->mTitleValue
;
929 * Get the text form (spaces not underscores) of the main part
931 * @return string Main part of the title
933 public function getText() {
934 return $this->mTextform
;
938 * Get the URL-encoded form of the main part
940 * @return string Main part of the title, URL-encoded
942 public function getPartialURL() {
943 return $this->mUrlform
;
947 * Get the main part with underscores
949 * @return string Main part of the title, with underscores
951 public function getDBkey() {
952 return $this->mDbkeyform
;
956 * Get the DB key with the initial letter case as specified by the user
957 * @deprecated since 1.33; please use Title::getDBKey() instead
959 * @return string DB key
961 function getUserCaseDBKey() {
962 if ( !is_null( $this->mUserCaseDBKey
) ) {
963 return $this->mUserCaseDBKey
;
965 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
966 return $this->mDbkeyform
;
971 * Get the namespace index, i.e. one of the NS_xxxx constants.
973 * @return int Namespace index
975 public function getNamespace() {
976 return $this->mNamespace
;
980 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
982 * @todo Deprecate this in favor of SlotRecord::getModel()
984 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
985 * @return string Content model id
987 public function getContentModel( $flags = 0 ) {
988 if ( !$this->mForcedContentModel
989 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
990 && $this->getArticleID( $flags )
992 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
993 $linkCache->addLinkObj( $this ); # in case we already had an article ID
994 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
997 if ( !$this->mContentModel
) {
998 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1001 return $this->mContentModel
;
1005 * Convenience method for checking a title's content model name
1007 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1008 * @return bool True if $this->getContentModel() == $id
1010 public function hasContentModel( $id ) {
1011 return $this->getContentModel() == $id;
1015 * Set a proposed content model for the page for permissions
1016 * checking. This does not actually change the content model
1019 * Additionally, you should make sure you've checked
1020 * ContentHandler::canBeUsedOn() first.
1023 * @param string $model CONTENT_MODEL_XXX constant
1025 public function setContentModel( $model ) {
1026 $this->mContentModel
= $model;
1027 $this->mForcedContentModel
= true;
1031 * Get the namespace text
1033 * @return string|false Namespace text
1035 public function getNsText() {
1036 if ( $this->isExternal() ) {
1037 // This probably shouldn't even happen, except for interwiki transclusion.
1038 // If possible, use the canonical name for the foreign namespace.
1039 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1040 if ( $nsText !== false ) {
1046 $formatter = self
::getTitleFormatter();
1047 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1048 } catch ( InvalidArgumentException
$ex ) {
1049 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1055 * Get the namespace text of the subject (rather than talk) page
1057 * @return string Namespace text
1059 public function getSubjectNsText() {
1060 return MediaWikiServices
::getInstance()->getContentLanguage()->
1061 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1065 * Get the namespace text of the talk page
1067 * @return string Namespace text
1069 public function getTalkNsText() {
1070 return MediaWikiServices
::getInstance()->getContentLanguage()->
1071 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1075 * Can this title have a corresponding talk page?
1077 * @deprecated since 1.30, use canHaveTalkPage() instead.
1079 * @return bool True if this title either is a talk page or can have a talk page associated.
1081 public function canTalk() {
1082 return $this->canHaveTalkPage();
1086 * Can this title have a corresponding talk page?
1088 * @see MWNamespace::hasTalkNamespace
1091 * @return bool True if this title either is a talk page or can have a talk page associated.
1093 public function canHaveTalkPage() {
1094 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1098 * Is this in a namespace that allows actual pages?
1102 public function canExist() {
1103 return $this->mNamespace
>= NS_MAIN
;
1107 * Can this title be added to a user's watchlist?
1111 public function isWatchable() {
1112 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1116 * Returns true if this is a special page.
1120 public function isSpecialPage() {
1121 return $this->mNamespace
== NS_SPECIAL
;
1125 * Returns true if this title resolves to the named special page
1127 * @param string $name The special page name
1130 public function isSpecial( $name ) {
1131 if ( $this->isSpecialPage() ) {
1132 list( $thisName, /* $subpage */ ) =
1133 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1134 resolveAlias( $this->mDbkeyform
);
1135 if ( $name == $thisName ) {
1143 * If the Title refers to a special page alias which is not the local default, resolve
1144 * the alias, and localise the name as necessary. Otherwise, return $this
1148 public function fixSpecialName() {
1149 if ( $this->isSpecialPage() ) {
1150 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1151 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1152 if ( $canonicalName ) {
1153 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1154 if ( $localName != $this->mDbkeyform
) {
1155 return self
::makeTitle( NS_SPECIAL
, $localName );
1163 * Returns true if the title is inside the specified namespace.
1165 * Please make use of this instead of comparing to getNamespace()
1166 * This function is much more resistant to changes we may make
1167 * to namespaces than code that makes direct comparisons.
1168 * @param int $ns The namespace
1172 public function inNamespace( $ns ) {
1173 return MWNamespace
::equals( $this->mNamespace
, $ns );
1177 * Returns true if the title is inside one of the specified namespaces.
1179 * @param int|int[] $namespaces,... The namespaces to check for
1183 public function inNamespaces( /* ... */ ) {
1184 $namespaces = func_get_args();
1185 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1186 $namespaces = $namespaces[0];
1189 foreach ( $namespaces as $ns ) {
1190 if ( $this->inNamespace( $ns ) ) {
1199 * Returns true if the title has the same subject namespace as the
1200 * namespace specified.
1201 * For example this method will take NS_USER and return true if namespace
1202 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1203 * as their subject namespace.
1205 * This is MUCH simpler than individually testing for equivalence
1206 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1211 public function hasSubjectNamespace( $ns ) {
1212 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1216 * Is this Title in a namespace which contains content?
1217 * In other words, is this a content page, for the purposes of calculating
1222 public function isContentPage() {
1223 return MWNamespace
::isContent( $this->mNamespace
);
1227 * Would anybody with sufficient privileges be able to move this page?
1228 * Some pages just aren't movable.
1232 public function isMovable() {
1233 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1234 // Interwiki title or immovable namespace. Hooks don't get to override here
1239 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1244 * Is this the mainpage?
1245 * @note Title::newFromText seems to be sufficiently optimized by the title
1246 * cache that we don't need to over-optimize by doing direct comparisons and
1247 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1248 * ends up reporting something differently than $title->isMainPage();
1253 public function isMainPage() {
1254 return $this->equals( self
::newMainPage() );
1258 * Is this a subpage?
1262 public function isSubpage() {
1263 return MWNamespace
::hasSubpages( $this->mNamespace
)
1264 ?
strpos( $this->getText(), '/' ) !== false
1269 * Is this a conversion table for the LanguageConverter?
1273 public function isConversionTable() {
1274 // @todo ConversionTable should become a separate content model.
1276 return $this->mNamespace
== NS_MEDIAWIKI
&&
1277 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1281 * Does that page contain wikitext, or it is JS, CSS or whatever?
1285 public function isWikitextPage() {
1286 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1290 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1291 * global UI. This is generally true for pages in the MediaWiki namespace having
1292 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1294 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1297 * Note that this method should not return true for pages that contain and show
1298 * "inactive" CSS, JSON, or JS.
1303 public function isSiteConfigPage() {
1305 $this->isSiteCssConfigPage()
1306 ||
$this->isSiteJsonConfigPage()
1307 ||
$this->isSiteJsConfigPage()
1313 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1315 public function isCssOrJsPage() {
1316 wfDeprecated( __METHOD__
, '1.31' );
1317 return ( NS_MEDIAWIKI
== $this->mNamespace
1318 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1319 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1323 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1328 public function isUserConfigPage() {
1330 $this->isUserCssConfigPage()
1331 ||
$this->isUserJsonConfigPage()
1332 ||
$this->isUserJsConfigPage()
1338 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1340 public function isCssJsSubpage() {
1341 wfDeprecated( __METHOD__
, '1.31' );
1342 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1343 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1344 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1348 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1350 * @return string Containing skin name from .css, .json, or .js subpage title
1353 public function getSkinFromConfigSubpage() {
1354 $subpage = explode( '/', $this->mTextform
);
1355 $subpage = $subpage[count( $subpage ) - 1];
1356 $lastdot = strrpos( $subpage, '.' );
1357 if ( $lastdot === false ) {
1358 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1360 return substr( $subpage, 0, $lastdot );
1364 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1365 * @return string Containing skin name from .css, .json, or .js subpage title
1367 public function getSkinFromCssJsSubpage() {
1368 wfDeprecated( __METHOD__
, '1.31' );
1369 return $this->getSkinFromConfigSubpage();
1373 * Is this a CSS "config" sub-page of a user page?
1378 public function isUserCssConfigPage() {
1380 NS_USER
== $this->mNamespace
1381 && $this->isSubpage()
1382 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1387 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1390 public function isCssSubpage() {
1391 wfDeprecated( __METHOD__
, '1.31' );
1392 return $this->isUserCssConfigPage();
1396 * Is this a JSON "config" sub-page of a user page?
1401 public function isUserJsonConfigPage() {
1403 NS_USER
== $this->mNamespace
1404 && $this->isSubpage()
1405 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1410 * Is this a JS "config" sub-page of a user page?
1415 public function isUserJsConfigPage() {
1417 NS_USER
== $this->mNamespace
1418 && $this->isSubpage()
1419 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1424 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1427 public function isJsSubpage() {
1428 wfDeprecated( __METHOD__
, '1.31' );
1429 return $this->isUserJsConfigPage();
1433 * Is this a sitewide CSS "config" page?
1438 public function isSiteCssConfigPage() {
1440 NS_MEDIAWIKI
== $this->mNamespace
1442 $this->hasContentModel( CONTENT_MODEL_CSS
)
1443 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1444 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1445 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1451 * Is this a sitewide JSON "config" page?
1456 public function isSiteJsonConfigPage() {
1458 NS_MEDIAWIKI
== $this->mNamespace
1460 $this->hasContentModel( CONTENT_MODEL_JSON
)
1461 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1462 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1463 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1469 * Is this a sitewide JS "config" page?
1474 public function isSiteJsConfigPage() {
1476 NS_MEDIAWIKI
== $this->mNamespace
1478 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1479 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1480 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1481 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1487 * Is this a message which can contain raw HTML?
1492 public function isRawHtmlMessage() {
1493 global $wgRawHtmlMessages;
1495 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1498 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1499 return in_array( $message, $wgRawHtmlMessages, true );
1503 * Is this a talk page of some sort?
1507 public function isTalkPage() {
1508 return MWNamespace
::isTalk( $this->mNamespace
);
1512 * Get a Title object associated with the talk page of this article
1514 * @return Title The object for the talk page
1516 public function getTalkPage() {
1517 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1521 * Get a Title object associated with the talk page of this article,
1522 * if such a talk page can exist.
1526 * @return Title|null The object for the talk page,
1527 * or null if no associated talk page can exist, according to canHaveTalkPage().
1529 public function getTalkPageIfDefined() {
1530 if ( !$this->canHaveTalkPage() ) {
1534 return $this->getTalkPage();
1538 * Get a title object associated with the subject page of this
1541 * @return Title The object for the subject page
1543 public function getSubjectPage() {
1544 // Is this the same title?
1545 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1546 if ( $this->mNamespace
== $subjectNS ) {
1549 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1553 * Get the other title for this page, if this is a subject page
1554 * get the talk page, if it is a subject page get the talk page
1557 * @throws MWException If the page doesn't have an other page
1560 public function getOtherPage() {
1561 if ( $this->isSpecialPage() ) {
1562 throw new MWException( 'Special pages cannot have other pages' );
1564 if ( $this->isTalkPage() ) {
1565 return $this->getSubjectPage();
1567 if ( !$this->canHaveTalkPage() ) {
1568 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1570 return $this->getTalkPage();
1575 * Get the default namespace index, for when there is no namespace
1577 * @return int Default namespace index
1579 public function getDefaultNamespace() {
1580 return $this->mDefaultNamespace
;
1584 * Get the Title fragment (i.e.\ the bit after the #) in text form
1586 * Use Title::hasFragment to check for a fragment
1588 * @return string Title fragment
1590 public function getFragment() {
1591 return $this->mFragment
;
1595 * Check if a Title fragment is set
1600 public function hasFragment() {
1601 return $this->mFragment
!== '';
1605 * Get the fragment in URL form, including the "#" character if there is one
1607 * @return string Fragment in URL form
1609 public function getFragmentForURL() {
1610 if ( !$this->hasFragment() ) {
1612 } elseif ( $this->isExternal()
1613 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1615 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1617 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1621 * Set the fragment for this title. Removes the first character from the
1622 * specified fragment before setting, so it assumes you're passing it with
1625 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1626 * or Title::createFragmentTarget().
1627 * Still in active use privately.
1630 * @param string $fragment Text
1632 public function setFragment( $fragment ) {
1633 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1637 * Creates a new Title for a different fragment of the same page.
1640 * @param string $fragment
1643 public function createFragmentTarget( $fragment ) {
1644 return self
::makeTitle(
1653 * Prefix some arbitrary text with the namespace or interwiki prefix
1656 * @param string $name The text
1657 * @return string The prefixed text
1659 private function prefix( $name ) {
1661 if ( $this->isExternal() ) {
1662 $p = $this->mInterwiki
. ':';
1665 if ( $this->mNamespace
!= 0 ) {
1666 $nsText = $this->getNsText();
1668 if ( $nsText === false ) {
1669 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1670 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1671 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1674 $p .= $nsText . ':';
1680 * Get the prefixed database key form
1682 * @return string The prefixed title, with underscores and
1683 * any interwiki and namespace prefixes
1685 public function getPrefixedDBkey() {
1686 $s = $this->prefix( $this->mDbkeyform
);
1687 $s = strtr( $s, ' ', '_' );
1692 * Get the prefixed title with spaces.
1693 * This is the form usually used for display
1695 * @return string The prefixed title, with spaces
1697 public function getPrefixedText() {
1698 if ( $this->prefixedText
=== null ) {
1699 $s = $this->prefix( $this->mTextform
);
1700 $s = strtr( $s, '_', ' ' );
1701 $this->prefixedText
= $s;
1703 return $this->prefixedText
;
1707 * Return a string representation of this title
1709 * @return string Representation of this title
1711 public function __toString() {
1712 return $this->getPrefixedText();
1716 * Get the prefixed title with spaces, plus any fragment
1717 * (part beginning with '#')
1719 * @return string The prefixed title, with spaces and the fragment, including '#'
1721 public function getFullText() {
1722 $text = $this->getPrefixedText();
1723 if ( $this->hasFragment() ) {
1724 $text .= '#' . $this->mFragment
;
1730 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1734 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1738 * @return string Root name
1741 public function getRootText() {
1742 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1743 return $this->getText();
1746 return strtok( $this->getText(), '/' );
1750 * Get the root page name title, i.e. the leftmost part before any slashes
1754 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1755 * # returns: Title{User:Foo}
1758 * @return Title Root title
1761 public function getRootTitle() {
1762 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1766 * Get the base page name without a namespace, i.e. the part before the subpage name
1770 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1771 * # returns: 'Foo/Bar'
1774 * @return string Base name
1776 public function getBaseText() {
1777 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1778 return $this->getText();
1781 $parts = explode( '/', $this->getText() );
1782 # Don't discard the real title if there's no subpage involved
1783 if ( count( $parts ) > 1 ) {
1784 unset( $parts[count( $parts ) - 1] );
1786 return implode( '/', $parts );
1790 * Get the base page name title, i.e. the part before the subpage name
1794 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1795 * # returns: Title{User:Foo/Bar}
1798 * @return Title Base title
1801 public function getBaseTitle() {
1802 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1806 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1810 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1814 * @return string Subpage name
1816 public function getSubpageText() {
1817 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1818 return $this->mTextform
;
1820 $parts = explode( '/', $this->mTextform
);
1821 return $parts[count( $parts ) - 1];
1825 * Get the title for a subpage of the current page
1829 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1830 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1833 * @param string $text The subpage name to add to the title
1834 * @return Title Subpage title
1837 public function getSubpage( $text ) {
1838 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1842 * Get a URL-encoded form of the subpage text
1844 * @return string URL-encoded subpage name
1846 public function getSubpageUrlForm() {
1847 $text = $this->getSubpageText();
1848 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1853 * Get a URL-encoded title (not an actual URL) including interwiki
1855 * @return string The URL-encoded form
1857 public function getPrefixedURL() {
1858 $s = $this->prefix( $this->mDbkeyform
);
1859 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1864 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1865 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1866 * second argument named variant. This was deprecated in favor
1867 * of passing an array of option with a "variant" key
1868 * Once $query2 is removed for good, this helper can be dropped
1869 * and the wfArrayToCgi moved to getLocalURL();
1871 * @since 1.19 (r105919)
1872 * @param array|string $query
1873 * @param string|string[]|bool $query2
1876 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1877 if ( $query2 !== false ) {
1878 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1879 "method called with a second parameter is deprecated. Add your " .
1880 "parameter to an array passed as the first parameter.", "1.19" );
1882 if ( is_array( $query ) ) {
1883 $query = wfArrayToCgi( $query );
1886 if ( is_string( $query2 ) ) {
1887 // $query2 is a string, we will consider this to be
1888 // a deprecated $variant argument and add it to the query
1889 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1891 $query2 = wfArrayToCgi( $query2 );
1893 // If we have $query content add a & to it first
1897 // Now append the queries together
1904 * Get a real URL referring to this title, with interwiki link and
1907 * @see self::getLocalURL for the arguments.
1909 * @param string|string[] $query
1910 * @param string|string[]|bool $query2
1911 * @param string|int|null $proto Protocol type to use in URL
1912 * @return string The URL
1914 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1915 $query = self
::fixUrlQueryArgs( $query, $query2 );
1917 # Hand off all the decisions on urls to getLocalURL
1918 $url = $this->getLocalURL( $query );
1920 # Expand the url to make it a full url. Note that getLocalURL has the
1921 # potential to output full urls for a variety of reasons, so we use
1922 # wfExpandUrl instead of simply prepending $wgServer
1923 $url = wfExpandUrl( $url, $proto );
1925 # Finally, add the fragment.
1926 $url .= $this->getFragmentForURL();
1927 // Avoid PHP 7.1 warning from passing $this by reference
1929 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1934 * Get a url appropriate for making redirects based on an untrusted url arg
1936 * This is basically the same as getFullUrl(), but in the case of external
1937 * interwikis, we send the user to a landing page, to prevent possible
1938 * phishing attacks and the like.
1940 * @note Uses current protocol by default, since technically relative urls
1941 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1942 * places where the url gets cached, as might pollute between
1943 * https and non-https users.
1944 * @see self::getLocalURL for the arguments.
1945 * @param array|string $query
1946 * @param string $proto Protocol type to use in URL
1947 * @return string A url suitable to use in an HTTP location header.
1949 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1951 if ( $this->isExternal() ) {
1952 $target = SpecialPage
::getTitleFor(
1954 $this->getPrefixedDBkey()
1957 return $target->getFullURL( $query, false, $proto );
1961 * Get a URL with no fragment or server name (relative URL) from a Title object.
1962 * If this page is generated with action=render, however,
1963 * $wgServer is prepended to make an absolute URL.
1965 * @see self::getFullURL to always get an absolute URL.
1966 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1967 * valid to link, locally, to the current Title.
1968 * @see self::newFromText to produce a Title object.
1970 * @param string|string[] $query An optional query string,
1971 * not used for interwiki links. Can be specified as an associative array as well,
1972 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1973 * Some query patterns will trigger various shorturl path replacements.
1974 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1975 * be an array. If a string is passed it will be interpreted as a deprecated
1976 * variant argument and urlencoded into a variant= argument.
1977 * This second query argument will be added to the $query
1978 * The second parameter is deprecated since 1.19. Pass it as a key,value
1979 * pair in the first parameter array instead.
1981 * @return string String of the URL.
1983 public function getLocalURL( $query = '', $query2 = false ) {
1984 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1986 $query = self
::fixUrlQueryArgs( $query, $query2 );
1988 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1990 $namespace = $this->getNsText();
1991 if ( $namespace != '' ) {
1992 # Can this actually happen? Interwikis shouldn't be parsed.
1993 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1996 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1997 $url = wfAppendQuery( $url, $query );
1999 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2000 if ( $query == '' ) {
2001 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2002 // Avoid PHP 7.1 warning from passing $this by reference
2004 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2006 global $wgVariantArticlePath, $wgActionPaths;
2010 if ( !empty( $wgActionPaths )
2011 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2013 $action = urldecode( $matches[2] );
2014 if ( isset( $wgActionPaths[$action] ) ) {
2015 $query = $matches[1];
2016 if ( isset( $matches[4] ) ) {
2017 $query .= $matches[4];
2019 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2020 if ( $query != '' ) {
2021 $url = wfAppendQuery( $url, $query );
2027 && $wgVariantArticlePath
2028 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2029 && $this->getPageLanguage()->equals(
2030 MediaWikiServices
::getInstance()->getContentLanguage() )
2031 && $this->getPageLanguage()->hasVariants()
2033 $variant = urldecode( $matches[1] );
2034 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2035 // Only do the variant replacement if the given variant is a valid
2036 // variant for the page's language.
2037 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2038 $url = str_replace( '$1', $dbkey, $url );
2042 if ( $url === false ) {
2043 if ( $query == '-' ) {
2046 $url = "{$wgScript}?title={$dbkey}&{$query}";
2049 // Avoid PHP 7.1 warning from passing $this by reference
2051 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2053 // @todo FIXME: This causes breakage in various places when we
2054 // actually expected a local URL and end up with dupe prefixes.
2055 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2056 $url = $wgServer . $url;
2059 // Avoid PHP 7.1 warning from passing $this by reference
2061 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2066 * Get a URL that's the simplest URL that will be valid to link, locally,
2067 * to the current Title. It includes the fragment, but does not include
2068 * the server unless action=render is used (or the link is external). If
2069 * there's a fragment but the prefixed text is empty, we just return a link
2072 * The result obviously should not be URL-escaped, but does need to be
2073 * HTML-escaped if it's being output in HTML.
2075 * @param string|string[] $query
2076 * @param bool $query2
2077 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2078 * or false (default) for no expansion
2079 * @see self::getLocalURL for the arguments.
2080 * @return string The URL
2082 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2083 if ( $this->isExternal() ||
$proto !== false ) {
2084 $ret = $this->getFullURL( $query, $query2, $proto );
2085 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2086 $ret = $this->getFragmentForURL();
2088 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2094 * Get the URL form for an internal link.
2095 * - Used in various CDN-related code, in case we have a different
2096 * internal hostname for the server from the exposed one.
2098 * This uses $wgInternalServer to qualify the path, or $wgServer
2099 * if $wgInternalServer is not set. If the server variable used is
2100 * protocol-relative, the URL will be expanded to http://
2102 * @see self::getLocalURL for the arguments.
2103 * @param string $query
2104 * @param string|bool $query2
2105 * @return string The URL
2107 public function getInternalURL( $query = '', $query2 = false ) {
2108 global $wgInternalServer, $wgServer;
2109 $query = self
::fixUrlQueryArgs( $query, $query2 );
2110 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2111 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2112 // Avoid PHP 7.1 warning from passing $this by reference
2114 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2119 * Get the URL for a canonical link, for use in things like IRC and
2120 * e-mail notifications. Uses $wgCanonicalServer and the
2121 * GetCanonicalURL hook.
2123 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2125 * @see self::getLocalURL for the arguments.
2126 * @param string $query
2127 * @param string|bool $query2
2128 * @return string The URL
2131 public function getCanonicalURL( $query = '', $query2 = false ) {
2132 $query = self
::fixUrlQueryArgs( $query, $query2 );
2133 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2134 // Avoid PHP 7.1 warning from passing $this by reference
2136 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2141 * Get the edit URL for this Title
2143 * @return string The URL, or a null string if this is an interwiki link
2145 public function getEditURL() {
2146 if ( $this->isExternal() ) {
2149 $s = $this->getLocalURL( 'action=edit' );
2155 * Can $user perform $action on this page?
2156 * This skips potentially expensive cascading permission checks
2157 * as well as avoids expensive error formatting
2159 * Suitable for use for nonessential UI controls in common cases, but
2160 * _not_ for functional access control.
2162 * May provide false positives, but should never provide a false negative.
2164 * @param string $action Action that permission needs to be checked for
2165 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2168 public function quickUserCan( $action, $user = null ) {
2169 return $this->userCan( $action, $user, false );
2173 * Can $user perform $action on this page?
2175 * @param string $action Action that permission needs to be checked for
2176 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2178 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2181 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2182 if ( !$user instanceof User
) {
2187 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2191 * Can $user perform $action on this page?
2193 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2195 * @param string $action Action that permission needs to be checked for
2196 * @param User $user User to check
2197 * @param string $rigor One of (quick,full,secure)
2198 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2199 * - full : does cheap and expensive checks possibly from a replica DB
2200 * - secure : does cheap and expensive checks, using the master as needed
2201 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2202 * whose corresponding errors may be ignored.
2203 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2205 public function getUserPermissionsErrors(
2206 $action, $user, $rigor = 'secure', $ignoreErrors = []
2208 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2210 // Remove the errors being ignored.
2211 foreach ( $errors as $index => $error ) {
2212 $errKey = is_array( $error ) ?
$error[0] : $error;
2214 if ( in_array( $errKey, $ignoreErrors ) ) {
2215 unset( $errors[$index] );
2217 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2218 unset( $errors[$index] );
2226 * Permissions checks that fail most often, and which are easiest to test.
2228 * @param string $action The action to check
2229 * @param User $user User to check
2230 * @param array $errors List of current errors
2231 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2232 * @param bool $short Short circuit on first error
2234 * @return array List of errors
2236 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2237 if ( !Hooks
::run( 'TitleQuickPermissions',
2238 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2243 if ( $action == 'create' ) {
2245 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2246 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2248 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2250 } elseif ( $action == 'move' ) {
2251 if ( !$user->isAllowed( 'move-rootuserpages' )
2252 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2253 // Show user page-specific message only if the user can move other pages
2254 $errors[] = [ 'cant-move-user-page' ];
2257 // Check if user is allowed to move files if it's a file
2258 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2259 $errors[] = [ 'movenotallowedfile' ];
2262 // Check if user is allowed to move category pages if it's a category page
2263 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2264 $errors[] = [ 'cant-move-category-page' ];
2267 if ( !$user->isAllowed( 'move' ) ) {
2268 // User can't move anything
2269 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2270 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2271 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2272 // custom message if logged-in users without any special rights can move
2273 $errors[] = [ 'movenologintext' ];
2275 $errors[] = [ 'movenotallowed' ];
2278 } elseif ( $action == 'move-target' ) {
2279 if ( !$user->isAllowed( 'move' ) ) {
2280 // User can't move anything
2281 $errors[] = [ 'movenotallowed' ];
2282 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2283 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2284 // Show user page-specific message only if the user can move other pages
2285 $errors[] = [ 'cant-move-to-user-page' ];
2286 } elseif ( !$user->isAllowed( 'move-categorypages' )
2287 && $this->mNamespace
== NS_CATEGORY
) {
2288 // Show category page-specific message only if the user can move other pages
2289 $errors[] = [ 'cant-move-to-category-page' ];
2291 } elseif ( !$user->isAllowed( $action ) ) {
2292 $errors[] = $this->missingPermissionError( $action, $short );
2299 * Add the resulting error code to the errors array
2301 * @param array $errors List of current errors
2302 * @param array $result Result of errors
2304 * @return array List of errors
2306 private function resultToError( $errors, $result ) {
2307 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2308 // A single array representing an error
2309 $errors[] = $result;
2310 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2311 // A nested array representing multiple errors
2312 $errors = array_merge( $errors, $result );
2313 } elseif ( $result !== '' && is_string( $result ) ) {
2314 // A string representing a message-id
2315 $errors[] = [ $result ];
2316 } elseif ( $result instanceof MessageSpecifier
) {
2317 // A message specifier representing an error
2318 $errors[] = [ $result ];
2319 } elseif ( $result === false ) {
2320 // a generic "We don't want them to do that"
2321 $errors[] = [ 'badaccess-group0' ];
2327 * Check various permission hooks
2329 * @param string $action The action to check
2330 * @param User $user User to check
2331 * @param array $errors List of current errors
2332 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2333 * @param bool $short Short circuit on first error
2335 * @return array List of errors
2337 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2338 // Use getUserPermissionsErrors instead
2340 // Avoid PHP 7.1 warning from passing $this by reference
2342 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2343 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2345 // Check getUserPermissionsErrors hook
2346 // Avoid PHP 7.1 warning from passing $this by reference
2348 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2349 $errors = $this->resultToError( $errors, $result );
2351 // Check getUserPermissionsErrorsExpensive hook
2354 && !( $short && count( $errors ) > 0 )
2355 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2357 $errors = $this->resultToError( $errors, $result );
2364 * Check permissions on special pages & namespaces
2366 * @param string $action The action to check
2367 * @param User $user User to check
2368 * @param array $errors List of current errors
2369 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2370 * @param bool $short Short circuit on first error
2372 * @return array List of errors
2374 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2375 # Only 'createaccount' can be performed on special pages,
2376 # which don't actually exist in the DB.
2377 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2378 $errors[] = [ 'ns-specialprotected' ];
2381 # Check $wgNamespaceProtection for restricted namespaces
2382 if ( $this->isNamespaceProtected( $user ) ) {
2383 $ns = $this->mNamespace
== NS_MAIN ?
2384 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2385 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2386 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2393 * Check sitewide CSS/JSON/JS permissions
2395 * @param string $action The action to check
2396 * @param User $user User to check
2397 * @param array $errors List of current errors
2398 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2399 * @param bool $short Short circuit on first error
2401 * @return array List of errors
2403 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2404 if ( $action != 'patrol' ) {
2406 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2407 // editinterface right. That's implemented as a restriction so no check needed here.
2408 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2409 $error = [ 'sitecssprotected', $action ];
2410 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2411 $error = [ 'sitejsonprotected', $action ];
2412 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2413 $error = [ 'sitejsprotected', $action ];
2414 } elseif ( $this->isRawHtmlMessage() ) {
2415 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2416 if ( !$user->isAllowed( 'editsitejs' ) ) {
2417 $error = [ 'sitejsprotected', $action ];
2418 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2419 $error = [ 'sitecssprotected', $action ];
2424 if ( $user->isAllowed( 'editinterface' ) ) {
2425 // Most users / site admins will probably find out about the new, more restrictive
2426 // permissions by failing to edit something. Give them more info.
2427 // TODO remove this a few release cycles after 1.32
2428 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2438 * Check CSS/JSON/JS sub-page permissions
2440 * @param string $action The action to check
2441 * @param User $user User to check
2442 * @param array $errors List of current errors
2443 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2444 * @param bool $short Short circuit on first error
2446 * @return array List of errors
2448 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2449 # Protect css/json/js subpages of user pages
2450 # XXX: this might be better using restrictions
2452 if ( $action === 'patrol' ) {
2456 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2457 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2459 $this->isUserCssConfigPage()
2460 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2462 $errors[] = [ 'mycustomcssprotected', $action ];
2464 $this->isUserJsonConfigPage()
2465 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2467 $errors[] = [ 'mycustomjsonprotected', $action ];
2469 $this->isUserJsConfigPage()
2470 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2472 $errors[] = [ 'mycustomjsprotected', $action ];
2475 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2476 // deletion/suppression which cannot be used for attacks and we want to avoid the
2477 // situation where an unprivileged user can post abusive content on their subpages
2478 // and only very highly privileged users could remove it.
2479 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2481 $this->isUserCssConfigPage()
2482 && !$user->isAllowed( 'editusercss' )
2484 $errors[] = [ 'customcssprotected', $action ];
2486 $this->isUserJsonConfigPage()
2487 && !$user->isAllowed( 'edituserjson' )
2489 $errors[] = [ 'customjsonprotected', $action ];
2491 $this->isUserJsConfigPage()
2492 && !$user->isAllowed( 'edituserjs' )
2494 $errors[] = [ 'customjsprotected', $action ];
2503 * Check against page_restrictions table requirements on this
2504 * page. The user must possess all required rights for this
2507 * @param string $action The action to check
2508 * @param User $user User to check
2509 * @param array $errors List of current errors
2510 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2511 * @param bool $short Short circuit on first error
2513 * @return array List of errors
2515 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2516 foreach ( $this->getRestrictions( $action ) as $right ) {
2517 // Backwards compatibility, rewrite sysop -> editprotected
2518 if ( $right == 'sysop' ) {
2519 $right = 'editprotected';
2521 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2522 if ( $right == 'autoconfirmed' ) {
2523 $right = 'editsemiprotected';
2525 if ( $right == '' ) {
2528 if ( !$user->isAllowed( $right ) ) {
2529 $errors[] = [ 'protectedpagetext', $right, $action ];
2530 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2531 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2539 * Check restrictions on cascading pages.
2541 * @param string $action The action to check
2542 * @param User $user User to check
2543 * @param array $errors List of current errors
2544 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2545 * @param bool $short Short circuit on first error
2547 * @return array List of errors
2549 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2550 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2551 # We /could/ use the protection level on the source page, but it's
2552 # fairly ugly as we have to establish a precedence hierarchy for pages
2553 # included by multiple cascade-protected pages. So just restrict
2554 # it to people with 'protect' permission, as they could remove the
2555 # protection anyway.
2556 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2557 # Cascading protection depends on more than this page...
2558 # Several cascading protected pages may include this page...
2559 # Check each cascading level
2560 # This is only for protection restrictions, not for all actions
2561 if ( isset( $restrictions[$action] ) ) {
2562 foreach ( $restrictions[$action] as $right ) {
2563 // Backwards compatibility, rewrite sysop -> editprotected
2564 if ( $right == 'sysop' ) {
2565 $right = 'editprotected';
2567 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2568 if ( $right == 'autoconfirmed' ) {
2569 $right = 'editsemiprotected';
2571 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2573 foreach ( $cascadingSources as $page ) {
2574 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2576 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2586 * Check action permissions not already checked in checkQuickPermissions
2588 * @param string $action The action to check
2589 * @param User $user User to check
2590 * @param array $errors List of current errors
2591 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2592 * @param bool $short Short circuit on first error
2594 * @return array List of errors
2596 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2597 global $wgDeleteRevisionsLimit, $wgLang;
2599 if ( $action == 'protect' ) {
2600 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2601 // If they can't edit, they shouldn't protect.
2602 $errors[] = [ 'protect-cantedit' ];
2604 } elseif ( $action == 'create' ) {
2605 $title_protection = $this->getTitleProtection();
2606 if ( $title_protection ) {
2607 if ( $title_protection['permission'] == ''
2608 ||
!$user->isAllowed( $title_protection['permission'] )
2612 User
::whoIs( $title_protection['user'] ),
2613 $title_protection['reason']
2617 } elseif ( $action == 'move' ) {
2618 // Check for immobile pages
2619 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2620 // Specific message for this case
2621 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2622 } elseif ( !$this->isMovable() ) {
2623 // Less specific message for rarer cases
2624 $errors[] = [ 'immobile-source-page' ];
2626 } elseif ( $action == 'move-target' ) {
2627 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2628 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2629 } elseif ( !$this->isMovable() ) {
2630 $errors[] = [ 'immobile-target-page' ];
2632 } elseif ( $action == 'delete' ) {
2633 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2634 if ( !$tempErrors ) {
2635 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2636 $user, $tempErrors, $rigor, true );
2638 if ( $tempErrors ) {
2639 // If protection keeps them from editing, they shouldn't be able to delete.
2640 $errors[] = [ 'deleteprotected' ];
2642 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2643 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2645 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2647 } elseif ( $action === 'undelete' ) {
2648 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2649 // Undeleting implies editing
2650 $errors[] = [ 'undelete-cantedit' ];
2652 if ( !$this->exists()
2653 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2655 // Undeleting where nothing currently exists implies creating
2656 $errors[] = [ 'undelete-cantcreate' ];
2663 * Check that the user isn't blocked from editing.
2665 * @param string $action The action to check
2666 * @param User $user User to check
2667 * @param array $errors List of current errors
2668 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2669 * @param bool $short Short circuit on first error
2671 * @return array List of errors
2673 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2674 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2675 // Account creation blocks handled at userlogin.
2676 // Unblocking handled in SpecialUnblock
2677 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2681 // Optimize for a very common case
2682 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2686 if ( $wgEmailConfirmToEdit
2687 && !$user->isEmailConfirmed()
2688 && $action === 'edit'
2690 $errors[] = [ 'confirmedittext' ];
2693 $useReplica = ( $rigor !== 'secure' );
2694 if ( ( $action == 'edit' ||
$action == 'create' )
2695 && !$user->isBlockedFrom( $this, $useReplica )
2697 // Don't block the user from editing their own talk page unless they've been
2698 // explicitly blocked from that too.
2699 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2700 // @todo FIXME: Pass the relevant context into this function.
2701 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2708 * Check that the user is allowed to read this page.
2710 * @param string $action The action to check
2711 * @param User $user User to check
2712 * @param array $errors List of current errors
2713 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2714 * @param bool $short Short circuit on first error
2716 * @return array List of errors
2718 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2719 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2721 $whitelisted = false;
2722 if ( User
::isEveryoneAllowed( 'read' ) ) {
2723 # Shortcut for public wikis, allows skipping quite a bit of code
2724 $whitelisted = true;
2725 } elseif ( $user->isAllowed( 'read' ) ) {
2726 # If the user is allowed to read pages, he is allowed to read all pages
2727 $whitelisted = true;
2728 } elseif ( $this->isSpecial( 'Userlogin' )
2729 ||
$this->isSpecial( 'PasswordReset' )
2730 ||
$this->isSpecial( 'Userlogout' )
2732 # Always grant access to the login page.
2733 # Even anons need to be able to log in.
2734 $whitelisted = true;
2735 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2736 # Time to check the whitelist
2737 # Only do these checks is there's something to check against
2738 $name = $this->getPrefixedText();
2739 $dbName = $this->getPrefixedDBkey();
2741 // Check for explicit whitelisting with and without underscores
2742 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2743 $whitelisted = true;
2744 } elseif ( $this->mNamespace
== NS_MAIN
) {
2745 # Old settings might have the title prefixed with
2746 # a colon for main-namespace pages
2747 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2748 $whitelisted = true;
2750 } elseif ( $this->isSpecialPage() ) {
2751 # If it's a special page, ditch the subpage bit and check again
2752 $name = $this->mDbkeyform
;
2753 list( $name, /* $subpage */ ) =
2754 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
2755 resolveAlias( $name );
2757 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2758 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2759 $whitelisted = true;
2765 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2766 $name = $this->getPrefixedText();
2767 // Check for regex whitelisting
2768 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2769 if ( preg_match( $listItem, $name ) ) {
2770 $whitelisted = true;
2776 if ( !$whitelisted ) {
2777 # If the title is not whitelisted, give extensions a chance to do so...
2778 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2779 if ( !$whitelisted ) {
2780 $errors[] = $this->missingPermissionError( $action, $short );
2788 * Get a description array when the user doesn't have the right to perform
2789 * $action (i.e. when User::isAllowed() returns false)
2791 * @param string $action The action to check
2792 * @param bool $short Short circuit on first error
2793 * @return array Array containing an error message key and any parameters
2795 private function missingPermissionError( $action, $short ) {
2796 // We avoid expensive display logic for quickUserCan's and such
2798 return [ 'badaccess-group0' ];
2801 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2805 * Can $user perform $action on this page? This is an internal function,
2806 * with multiple levels of checks depending on performance needs; see $rigor below.
2807 * It does not check wfReadOnly().
2809 * @param string $action Action that permission needs to be checked for
2810 * @param User $user User to check
2811 * @param string $rigor One of (quick,full,secure)
2812 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2813 * - full : does cheap and expensive checks possibly from a replica DB
2814 * - secure : does cheap and expensive checks, using the master as needed
2815 * @param bool $short Set this to true to stop after the first permission error.
2816 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2818 protected function getUserPermissionsErrorsInternal(
2819 $action, $user, $rigor = 'secure', $short = false
2821 if ( $rigor === true ) {
2822 $rigor = 'secure'; // b/c
2823 } elseif ( $rigor === false ) {
2824 $rigor = 'quick'; // b/c
2825 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2826 throw new Exception( "Invalid rigor parameter '$rigor'." );
2829 # Read has special handling
2830 if ( $action == 'read' ) {
2832 'checkPermissionHooks',
2833 'checkReadPermissions',
2834 'checkUserBlock', // for wgBlockDisablesLogin
2836 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2837 # or checkUserConfigPermissions here as it will lead to duplicate
2838 # error messages. This is okay to do since anywhere that checks for
2839 # create will also check for edit, and those checks are called for edit.
2840 } elseif ( $action == 'create' ) {
2842 'checkQuickPermissions',
2843 'checkPermissionHooks',
2844 'checkPageRestrictions',
2845 'checkCascadingSourcesRestrictions',
2846 'checkActionPermissions',
2851 'checkQuickPermissions',
2852 'checkPermissionHooks',
2853 'checkSpecialsAndNSPermissions',
2854 'checkSiteConfigPermissions',
2855 'checkUserConfigPermissions',
2856 'checkPageRestrictions',
2857 'checkCascadingSourcesRestrictions',
2858 'checkActionPermissions',
2864 foreach ( $checks as $method ) {
2865 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2867 if ( $short && $errors !== [] ) {
2876 * Get a filtered list of all restriction types supported by this wiki.
2877 * @param bool $exists True to get all restriction types that apply to
2878 * titles that do exist, False for all restriction types that apply to
2879 * titles that do not exist
2882 public static function getFilteredRestrictionTypes( $exists = true ) {
2883 global $wgRestrictionTypes;
2884 $types = $wgRestrictionTypes;
2886 # Remove the create restriction for existing titles
2887 $types = array_diff( $types, [ 'create' ] );
2889 # Only the create and upload restrictions apply to non-existing titles
2890 $types = array_intersect( $types, [ 'create', 'upload' ] );
2896 * Returns restriction types for the current Title
2898 * @return array Applicable restriction types
2900 public function getRestrictionTypes() {
2901 if ( $this->isSpecialPage() ) {
2905 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2907 if ( $this->mNamespace
!= NS_FILE
) {
2908 # Remove the upload restriction for non-file titles
2909 $types = array_diff( $types, [ 'upload' ] );
2912 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2914 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2915 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2921 * Is this title subject to title protection?
2922 * Title protection is the one applied against creation of such title.
2924 * @return array|bool An associative array representing any existent title
2925 * protection, or false if there's none.
2927 public function getTitleProtection() {
2928 $protection = $this->getTitleProtectionInternal();
2929 if ( $protection ) {
2930 if ( $protection['permission'] == 'sysop' ) {
2931 $protection['permission'] = 'editprotected'; // B/C
2933 if ( $protection['permission'] == 'autoconfirmed' ) {
2934 $protection['permission'] = 'editsemiprotected'; // B/C
2941 * Fetch title protection settings
2943 * To work correctly, $this->loadRestrictions() needs to have access to the
2944 * actual protections in the database without munging 'sysop' =>
2945 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2946 * callers probably want $this->getTitleProtection() instead.
2948 * @return array|bool
2950 protected function getTitleProtectionInternal() {
2951 // Can't protect pages in special namespaces
2952 if ( $this->mNamespace
< 0 ) {
2956 // Can't protect pages that exist.
2957 if ( $this->exists() ) {
2961 if ( $this->mTitleProtection
=== null ) {
2962 $dbr = wfGetDB( DB_REPLICA
);
2963 $commentStore = CommentStore
::getStore();
2964 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2965 $res = $dbr->select(
2966 [ 'protected_titles' ] +
$commentQuery['tables'],
2968 'user' => 'pt_user',
2969 'expiry' => 'pt_expiry',
2970 'permission' => 'pt_create_perm'
2971 ] +
$commentQuery['fields'],
2972 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2975 $commentQuery['joins']
2978 // fetchRow returns false if there are no rows.
2979 $row = $dbr->fetchRow( $res );
2981 $this->mTitleProtection
= [
2982 'user' => $row['user'],
2983 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2984 'permission' => $row['permission'],
2985 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2988 $this->mTitleProtection
= false;
2991 return $this->mTitleProtection
;
2995 * Remove any title protection due to page existing
2997 public function deleteTitleProtection() {
2998 $dbw = wfGetDB( DB_MASTER
);
3002 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
3005 $this->mTitleProtection
= false;
3009 * Is this page "semi-protected" - the *only* protection levels are listed
3010 * in $wgSemiprotectedRestrictionLevels?
3012 * @param string $action Action to check (default: edit)
3015 public function isSemiProtected( $action = 'edit' ) {
3016 global $wgSemiprotectedRestrictionLevels;
3018 $restrictions = $this->getRestrictions( $action );
3019 $semi = $wgSemiprotectedRestrictionLevels;
3020 if ( !$restrictions ||
!$semi ) {
3021 // Not protected, or all protection is full protection
3025 // Remap autoconfirmed to editsemiprotected for BC
3026 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3027 $semi[$key] = 'editsemiprotected';
3029 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3030 $restrictions[$key] = 'editsemiprotected';
3033 return !array_diff( $restrictions, $semi );
3037 * Does the title correspond to a protected article?
3039 * @param string $action The action the page is protected from,
3040 * by default checks all actions.
3043 public function isProtected( $action = '' ) {
3044 global $wgRestrictionLevels;
3046 $restrictionTypes = $this->getRestrictionTypes();
3048 # Special pages have inherent protection
3049 if ( $this->isSpecialPage() ) {
3053 # Check regular protection levels
3054 foreach ( $restrictionTypes as $type ) {
3055 if ( $action == $type ||
$action == '' ) {
3056 $r = $this->getRestrictions( $type );
3057 foreach ( $wgRestrictionLevels as $level ) {
3058 if ( in_array( $level, $r ) && $level != '' ) {
3069 * Determines if $user is unable to edit this page because it has been protected
3070 * by $wgNamespaceProtection.
3072 * @param User $user User object to check permissions
3075 public function isNamespaceProtected( User
$user ) {
3076 global $wgNamespaceProtection;
3078 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3079 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3080 if ( $right != '' && !$user->isAllowed( $right ) ) {
3089 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3091 * @return bool If the page is subject to cascading restrictions.
3093 public function isCascadeProtected() {
3094 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3095 return ( $sources > 0 );
3099 * Determines whether cascading protection sources have already been loaded from
3102 * @param bool $getPages True to check if the pages are loaded, or false to check
3103 * if the status is loaded.
3104 * @return bool Whether or not the specified information has been loaded
3107 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3108 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3112 * Cascading protection: Get the source of any cascading restrictions on this page.
3114 * @param bool $getPages Whether or not to retrieve the actual pages
3115 * that the restrictions have come from and the actual restrictions
3117 * @return array Two elements: First is an array of Title objects of the
3118 * pages from which cascading restrictions have come, false for
3119 * none, or true if such restrictions exist but $getPages was not
3120 * set. Second is an array like that returned by
3121 * Title::getAllRestrictions(), or an empty array if $getPages is
3124 public function getCascadeProtectionSources( $getPages = true ) {
3125 $pagerestrictions = [];
3127 if ( $this->mCascadeSources
!== null && $getPages ) {
3128 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3129 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3130 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3133 $dbr = wfGetDB( DB_REPLICA
);
3135 if ( $this->mNamespace
== NS_FILE
) {
3136 $tables = [ 'imagelinks', 'page_restrictions' ];
3138 'il_to' => $this->mDbkeyform
,
3143 $tables = [ 'templatelinks', 'page_restrictions' ];
3145 'tl_namespace' => $this->mNamespace
,
3146 'tl_title' => $this->mDbkeyform
,
3153 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3154 'pr_expiry', 'pr_type', 'pr_level' ];
3155 $where_clauses[] = 'page_id=pr_page';
3158 $cols = [ 'pr_expiry' ];
3161 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3163 $sources = $getPages ?
[] : false;
3164 $now = wfTimestampNow();
3166 foreach ( $res as $row ) {
3167 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3168 if ( $expiry > $now ) {
3170 $page_id = $row->pr_page
;
3171 $page_ns = $row->page_namespace
;
3172 $page_title = $row->page_title
;
3173 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3174 # Add groups needed for each restriction type if its not already there
3175 # Make sure this restriction type still exists
3177 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3178 $pagerestrictions[$row->pr_type
] = [];
3182 isset( $pagerestrictions[$row->pr_type
] )
3183 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3185 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3194 $this->mCascadeSources
= $sources;
3195 $this->mCascadingRestrictions
= $pagerestrictions;
3197 $this->mHasCascadingRestrictions
= $sources;
3200 return [ $sources, $pagerestrictions ];
3204 * Accessor for mRestrictionsLoaded
3206 * @return bool Whether or not the page's restrictions have already been
3207 * loaded from the database
3210 public function areRestrictionsLoaded() {
3211 return $this->mRestrictionsLoaded
;
3215 * Accessor/initialisation for mRestrictions
3217 * @param string $action Action that permission needs to be checked for
3218 * @return array Restriction levels needed to take the action. All levels are
3219 * required. Note that restriction levels are normally user rights, but 'sysop'
3220 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3221 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3223 public function getRestrictions( $action ) {
3224 if ( !$this->mRestrictionsLoaded
) {
3225 $this->loadRestrictions();
3227 return $this->mRestrictions
[$action] ??
[];
3231 * Accessor/initialisation for mRestrictions
3233 * @return array Keys are actions, values are arrays as returned by
3234 * Title::getRestrictions()
3237 public function getAllRestrictions() {
3238 if ( !$this->mRestrictionsLoaded
) {
3239 $this->loadRestrictions();
3241 return $this->mRestrictions
;
3245 * Get the expiry time for the restriction against a given action
3247 * @param string $action
3248 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3249 * or not protected at all, or false if the action is not recognised.
3251 public function getRestrictionExpiry( $action ) {
3252 if ( !$this->mRestrictionsLoaded
) {
3253 $this->loadRestrictions();
3255 return $this->mRestrictionsExpiry
[$action] ??
false;
3259 * Returns cascading restrictions for the current article
3263 function areRestrictionsCascading() {
3264 if ( !$this->mRestrictionsLoaded
) {
3265 $this->loadRestrictions();
3268 return $this->mCascadeRestriction
;
3272 * Compiles list of active page restrictions from both page table (pre 1.10)
3273 * and page_restrictions table for this existing page.
3274 * Public for usage by LiquidThreads.
3276 * @param array $rows Array of db result objects
3277 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3278 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3279 * Edit and move sections are separated by a colon
3280 * Example: "edit=autoconfirmed,sysop:move=sysop"
3282 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3283 // This function will only read rows from a table that we migrated away
3284 // from before adding READ_LATEST support to loadRestrictions, so we
3285 // don't need to support reading from DB_MASTER here.
3286 $dbr = wfGetDB( DB_REPLICA
);
3288 $restrictionTypes = $this->getRestrictionTypes();
3290 foreach ( $restrictionTypes as $type ) {
3291 $this->mRestrictions
[$type] = [];
3292 $this->mRestrictionsExpiry
[$type] = 'infinity';
3295 $this->mCascadeRestriction
= false;
3297 # Backwards-compatibility: also load the restrictions from the page record (old format).
3298 if ( $oldFashionedRestrictions !== null ) {
3299 $this->mOldRestrictions
= $oldFashionedRestrictions;
3302 if ( $this->mOldRestrictions
=== false ) {
3303 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3304 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3307 if ( $this->mOldRestrictions
!= '' ) {
3308 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3309 $temp = explode( '=', trim( $restrict ) );
3310 if ( count( $temp ) == 1 ) {
3311 // old old format should be treated as edit/move restriction
3312 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3313 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3315 $restriction = trim( $temp[1] );
3316 if ( $restriction != '' ) { // some old entries are empty
3317 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3323 if ( count( $rows ) ) {
3324 # Current system - load second to make them override.
3325 $now = wfTimestampNow();
3327 # Cycle through all the restrictions.
3328 foreach ( $rows as $row ) {
3329 // Don't take care of restrictions types that aren't allowed
3330 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3334 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3336 // Only apply the restrictions if they haven't expired!
3337 if ( !$expiry ||
$expiry > $now ) {
3338 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3339 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3341 $this->mCascadeRestriction |
= $row->pr_cascade
;
3346 $this->mRestrictionsLoaded
= true;
3350 * Load restrictions from the page_restrictions table
3352 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3353 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3354 * Edit and move sections are separated by a colon
3355 * Example: "edit=autoconfirmed,sysop:move=sysop"
3356 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
3357 * from the master DB.
3359 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
3360 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
3361 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
3365 // TODO: should probably pass $flags into getArticleID, but it seems hacky
3366 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
3367 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
3368 $id = $this->getArticleID();
3370 $fname = __METHOD__
;
3371 $loadRestrictionsFromDb = function ( Database
$dbr ) use ( $fname, $id ) {
3372 return iterator_to_array(
3374 'page_restrictions',
3375 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3376 [ 'pr_page' => $id ],
3382 if ( $readLatest ) {
3383 $dbr = wfGetDB( DB_MASTER
);
3384 $rows = $loadRestrictionsFromDb( $dbr );
3386 $cache = ObjectCache
::getMainWANInstance();
3387 $rows = $cache->getWithSetCallback(
3388 // Page protections always leave a new null revision
3389 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3391 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
3392 $dbr = wfGetDB( DB_REPLICA
);
3394 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3396 return $loadRestrictionsFromDb( $dbr );
3401 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3403 $title_protection = $this->getTitleProtectionInternal();
3405 if ( $title_protection ) {
3406 $now = wfTimestampNow();
3407 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3409 if ( !$expiry ||
$expiry > $now ) {
3410 // Apply the restrictions
3411 $this->mRestrictionsExpiry
['create'] = $expiry;
3412 $this->mRestrictions
['create'] =
3413 explode( ',', trim( $title_protection['permission'] ) );
3414 } else { // Get rid of the old restrictions
3415 $this->mTitleProtection
= false;
3418 $this->mRestrictionsExpiry
['create'] = 'infinity';
3420 $this->mRestrictionsLoaded
= true;
3425 * Flush the protection cache in this object and force reload from the database.
3426 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3428 public function flushRestrictions() {
3429 $this->mRestrictionsLoaded
= false;
3430 $this->mTitleProtection
= null;
3434 * Purge expired restrictions from the page_restrictions table
3436 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3438 static function purgeExpiredRestrictions() {
3439 if ( wfReadOnly() ) {
3443 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3444 wfGetDB( DB_MASTER
),
3446 function ( IDatabase
$dbw, $fname ) {
3447 $config = MediaWikiServices
::getInstance()->getMainConfig();
3448 $ids = $dbw->selectFieldValues(
3449 'page_restrictions',
3451 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3453 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3456 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3461 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3462 wfGetDB( DB_MASTER
),
3464 function ( IDatabase
$dbw, $fname ) {
3467 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3475 * Does this have subpages? (Warning, usually requires an extra DB query.)
3479 public function hasSubpages() {
3480 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3485 # We dynamically add a member variable for the purpose of this method
3486 # alone to cache the result. There's no point in having it hanging
3487 # around uninitialized in every Title object; therefore we only add it
3488 # if needed and don't declare it statically.
3489 if ( $this->mHasSubpages
=== null ) {
3490 $this->mHasSubpages
= false;
3491 $subpages = $this->getSubpages( 1 );
3492 if ( $subpages instanceof TitleArray
) {
3493 $this->mHasSubpages
= (bool)$subpages->count();
3497 return $this->mHasSubpages
;
3501 * Get all subpages of this page.
3503 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3504 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3505 * doesn't allow subpages
3507 public function getSubpages( $limit = -1 ) {
3508 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3512 $dbr = wfGetDB( DB_REPLICA
);
3513 $conds['page_namespace'] = $this->mNamespace
;
3514 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3516 if ( $limit > -1 ) {
3517 $options['LIMIT'] = $limit;
3519 return TitleArray
::newFromResult(
3520 $dbr->select( 'page',
3521 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3530 * Is there a version of this page in the deletion archive?
3532 * @return int The number of archived revisions
3534 public function isDeleted() {
3535 if ( $this->mNamespace
< 0 ) {
3538 $dbr = wfGetDB( DB_REPLICA
);
3540 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3541 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3544 if ( $this->mNamespace
== NS_FILE
) {
3545 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3546 [ 'fa_name' => $this->mDbkeyform
],
3555 * Is there a version of this page in the deletion archive?
3559 public function isDeletedQuick() {
3560 if ( $this->mNamespace
< 0 ) {
3563 $dbr = wfGetDB( DB_REPLICA
);
3564 $deleted = (bool)$dbr->selectField( 'archive', '1',
3565 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3568 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3569 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3570 [ 'fa_name' => $this->mDbkeyform
],
3578 * Get the article ID for this Title from the link cache,
3579 * adding it if necessary
3581 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3583 * @return int The ID
3585 public function getArticleID( $flags = 0 ) {
3586 if ( $this->mNamespace
< 0 ) {
3587 $this->mArticleID
= 0;
3588 return $this->mArticleID
;
3590 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3591 if ( $flags & self
::GAID_FOR_UPDATE
) {
3592 $oldUpdate = $linkCache->forUpdate( true );
3593 $linkCache->clearLink( $this );
3594 $this->mArticleID
= $linkCache->addLinkObj( $this );
3595 $linkCache->forUpdate( $oldUpdate );
3597 if ( $this->mArticleID
== -1 ) {
3598 $this->mArticleID
= $linkCache->addLinkObj( $this );
3601 return $this->mArticleID
;
3605 * Is this an article that is a redirect page?
3606 * Uses link cache, adding it if necessary
3608 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3611 public function isRedirect( $flags = 0 ) {
3612 if ( !is_null( $this->mRedirect
) ) {
3613 return $this->mRedirect
;
3615 if ( !$this->getArticleID( $flags ) ) {
3616 $this->mRedirect
= false;
3617 return $this->mRedirect
;
3620 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3621 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3622 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3623 if ( $cached === null ) {
3624 # Trust LinkCache's state over our own
3625 # LinkCache is telling us that the page doesn't exist, despite there being cached
3626 # data relating to an existing page in $this->mArticleID. Updaters should clear
3627 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3628 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3629 # LinkCache to refresh its data from the master.
3630 $this->mRedirect
= false;
3631 return $this->mRedirect
;
3634 $this->mRedirect
= (bool)$cached;
3636 return $this->mRedirect
;
3640 * What is the length of this page?
3641 * Uses link cache, adding it if necessary
3643 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3646 public function getLength( $flags = 0 ) {
3647 if ( $this->mLength
!= -1 ) {
3648 return $this->mLength
;
3650 if ( !$this->getArticleID( $flags ) ) {
3652 return $this->mLength
;
3654 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3655 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3656 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3657 if ( $cached === null ) {
3658 # Trust LinkCache's state over our own, as for isRedirect()
3660 return $this->mLength
;
3663 $this->mLength
= intval( $cached );
3665 return $this->mLength
;
3669 * What is the page_latest field for this page?
3671 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3672 * @return int Int or 0 if the page doesn't exist
3674 public function getLatestRevID( $flags = 0 ) {
3675 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3676 return intval( $this->mLatestID
);
3678 if ( !$this->getArticleID( $flags ) ) {
3679 $this->mLatestID
= 0;
3680 return $this->mLatestID
;
3682 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3683 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3684 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3685 if ( $cached === null ) {
3686 # Trust LinkCache's state over our own, as for isRedirect()
3687 $this->mLatestID
= 0;
3688 return $this->mLatestID
;
3691 $this->mLatestID
= intval( $cached );
3693 return $this->mLatestID
;
3697 * This clears some fields in this object, and clears any associated
3698 * keys in the "bad links" section of the link cache.
3700 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3701 * loading of the new page_id. It's also called from
3702 * WikiPage::doDeleteArticleReal()
3704 * @param int $newid The new Article ID
3706 public function resetArticleID( $newid ) {
3707 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3708 $linkCache->clearLink( $this );
3710 if ( $newid === false ) {
3711 $this->mArticleID
= -1;
3713 $this->mArticleID
= intval( $newid );
3715 $this->mRestrictionsLoaded
= false;
3716 $this->mRestrictions
= [];
3717 $this->mOldRestrictions
= false;
3718 $this->mRedirect
= null;
3719 $this->mLength
= -1;
3720 $this->mLatestID
= false;
3721 $this->mContentModel
= false;
3722 $this->mEstimateRevisions
= null;
3723 $this->mPageLanguage
= false;
3724 $this->mDbPageLanguage
= false;
3725 $this->mIsBigDeletion
= null;
3728 public static function clearCaches() {
3729 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3730 $linkCache->clear();
3732 $titleCache = self
::getTitleCache();
3733 $titleCache->clear();
3737 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3739 * @param string $text Containing title to capitalize
3740 * @param int $ns Namespace index, defaults to NS_MAIN
3741 * @return string Containing capitalized title
3743 public static function capitalize( $text, $ns = NS_MAIN
) {
3744 if ( MWNamespace
::isCapitalized( $ns ) ) {
3745 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3752 * Secure and split - main initialisation function for this object
3754 * Assumes that mDbkeyform has been set, and is urldecoded
3755 * and uses underscores, but not otherwise munged. This function
3756 * removes illegal characters, splits off the interwiki and
3757 * namespace prefixes, sets the other forms, and canonicalizes
3760 * @throws MalformedTitleException On invalid titles
3761 * @return bool True on success
3763 private function secureAndSplit() {
3764 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3765 // the parsing code with Title, while avoiding massive refactoring.
3766 // @todo: get rid of secureAndSplit, refactor parsing code.
3767 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3768 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3769 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3770 // MalformedTitleException can be thrown here
3771 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3774 $this->setFragment( '#' . $parts['fragment'] );
3775 $this->mInterwiki
= $parts['interwiki'];
3776 $this->mLocalInterwiki
= $parts['local_interwiki'];
3777 $this->mNamespace
= $parts['namespace'];
3778 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3780 $this->mDbkeyform
= $parts['dbkey'];
3781 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3782 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3784 # We already know that some pages won't be in the database!
3785 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3786 $this->mArticleID
= 0;
3793 * Get an array of Title objects linking to this Title
3794 * Also stores the IDs in the link cache.
3796 * WARNING: do not use this function on arbitrary user-supplied titles!
3797 * On heavily-used templates it will max out the memory.
3799 * @param array $options May be FOR UPDATE
3800 * @param string $table Table name
3801 * @param string $prefix Fields prefix
3802 * @return Title[] Array of Title objects linking here
3804 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3805 if ( count( $options ) > 0 ) {
3806 $db = wfGetDB( DB_MASTER
);
3808 $db = wfGetDB( DB_REPLICA
);
3813 self
::getSelectFields(),
3815 "{$prefix}_from=page_id",
3816 "{$prefix}_namespace" => $this->mNamespace
,
3817 "{$prefix}_title" => $this->mDbkeyform
],
3823 if ( $res->numRows() ) {
3824 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3825 foreach ( $res as $row ) {
3826 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3828 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3829 $retVal[] = $titleObj;
3837 * Get an array of Title objects using this Title as a template
3838 * Also stores the IDs in the link cache.
3840 * WARNING: do not use this function on arbitrary user-supplied titles!
3841 * On heavily-used templates it will max out the memory.
3843 * @param array $options Query option to Database::select()
3844 * @return Title[] Array of Title the Title objects linking here
3846 public function getTemplateLinksTo( $options = [] ) {
3847 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3851 * Get an array of Title objects linked from this Title
3852 * Also stores the IDs in the link cache.
3854 * WARNING: do not use this function on arbitrary user-supplied titles!
3855 * On heavily-used templates it will max out the memory.
3857 * @param array $options Query option to Database::select()
3858 * @param string $table Table name
3859 * @param string $prefix Fields prefix
3860 * @return array Array of Title objects linking here
3862 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3863 $id = $this->getArticleID();
3865 # If the page doesn't exist; there can't be any link from this page
3870 $db = wfGetDB( DB_REPLICA
);
3872 $blNamespace = "{$prefix}_namespace";
3873 $blTitle = "{$prefix}_title";
3875 $pageQuery = WikiPage
::getQueryInfo();
3877 [ $table, 'nestpage' => $pageQuery['tables'] ],
3879 [ $blNamespace, $blTitle ],
3880 $pageQuery['fields']
3882 [ "{$prefix}_from" => $id ],
3887 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3888 ] ] +
$pageQuery['joins']
3892 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3893 foreach ( $res as $row ) {
3894 if ( $row->page_id
) {
3895 $titleObj = self
::newFromRow( $row );
3897 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3898 $linkCache->addBadLinkObj( $titleObj );
3900 $retVal[] = $titleObj;
3907 * Get an array of Title objects used on this Title as a template
3908 * Also stores the IDs in the link cache.
3910 * WARNING: do not use this function on arbitrary user-supplied titles!
3911 * On heavily-used templates it will max out the memory.
3913 * @param array $options May be FOR UPDATE
3914 * @return Title[] Array of Title the Title objects used here
3916 public function getTemplateLinksFrom( $options = [] ) {
3917 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3921 * Get an array of Title objects referring to non-existent articles linked
3924 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3925 * should use redirect table in this case).
3926 * @return Title[] Array of Title the Title objects
3928 public function getBrokenLinksFrom() {
3929 if ( $this->getArticleID() == 0 ) {
3930 # All links from article ID 0 are false positives
3934 $dbr = wfGetDB( DB_REPLICA
);
3935 $res = $dbr->select(
3936 [ 'page', 'pagelinks' ],
3937 [ 'pl_namespace', 'pl_title' ],
3939 'pl_from' => $this->getArticleID(),
3940 'page_namespace IS NULL'
3946 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3952 foreach ( $res as $row ) {
3953 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3959 * Get a list of URLs to purge from the CDN cache when this
3962 * @return string[] Array of String the URLs
3964 public function getCdnUrls() {
3966 $this->getInternalURL(),
3967 $this->getInternalURL( 'action=history' )
3970 $pageLang = $this->getPageLanguage();
3971 if ( $pageLang->hasVariants() ) {
3972 $variants = $pageLang->getVariants();
3973 foreach ( $variants as $vCode ) {
3974 $urls[] = $this->getInternalURL( $vCode );
3978 // If we are looking at a css/js user subpage, purge the action=raw.
3979 if ( $this->isUserJsConfigPage() ) {
3980 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3981 } elseif ( $this->isUserJsonConfigPage() ) {
3982 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3983 } elseif ( $this->isUserCssConfigPage() ) {
3984 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3987 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3992 * @deprecated since 1.27 use getCdnUrls()
3994 public function getSquidURLs() {
3995 return $this->getCdnUrls();
3999 * Purge all applicable CDN URLs
4001 public function purgeSquid() {
4002 DeferredUpdates
::addUpdate(
4003 new CdnCacheUpdate( $this->getCdnUrls() ),
4004 DeferredUpdates
::PRESEND
4009 * Check whether a given move operation would be valid.
4010 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
4012 * @deprecated since 1.25, use MovePage's methods instead
4013 * @param Title &$nt The new title
4014 * @param bool $auth Whether to check user permissions (uses $wgUser)
4015 * @param string $reason Is the log summary of the move, used for spam checking
4016 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4018 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4021 if ( !( $nt instanceof Title
) ) {
4022 // Normally we'd add this to $errors, but we'll get
4023 // lots of syntax errors if $nt is not an object
4024 return [ [ 'badtitletext' ] ];
4027 $mp = new MovePage( $this, $nt );
4028 $errors = $mp->isValidMove()->getErrorsArray();
4030 $errors = wfMergeErrorArrays(
4032 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4036 return $errors ?
: true;
4040 * Check if the requested move target is a valid file move target
4041 * @todo move this to MovePage
4042 * @param Title $nt Target title
4043 * @return array List of errors
4045 protected function validateFileMoveOperation( $nt ) {
4050 $destFile = wfLocalFile( $nt );
4051 $destFile->load( File
::READ_LATEST
);
4052 if ( !$wgUser->isAllowed( 'reupload-shared' )
4053 && !$destFile->exists() && wfFindFile( $nt )
4055 $errors[] = [ 'file-exists-sharedrepo' ];
4062 * Move a title to a new location
4064 * @deprecated since 1.25, use the MovePage class instead
4065 * @param Title &$nt The new title
4066 * @param bool $auth Indicates whether $wgUser's permissions
4068 * @param string $reason The reason for the move
4069 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4070 * Ignored if the user doesn't have the suppressredirect right.
4071 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4072 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4074 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4075 array $changeTags = []
4078 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4079 if ( is_array( $err ) ) {
4080 // Auto-block user's IP if the account was "hard" blocked
4081 $wgUser->spreadAnyEditBlock();
4084 // Check suppressredirect permission
4085 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4086 $createRedirect = true;
4089 $mp = new MovePage( $this, $nt );
4090 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4091 if ( $status->isOK() ) {
4094 return $status->getErrorsArray();
4099 * Move this page's subpages to be subpages of $nt
4101 * @param Title $nt Move target
4102 * @param bool $auth Whether $wgUser's permissions should be checked
4103 * @param string $reason The reason for the move
4104 * @param bool $createRedirect Whether to create redirects from the old subpages to
4105 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4106 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4107 * @return array Array with old page titles as keys, and strings (new page titles) or
4108 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4109 * getUserPermissionsErrors()-like error array with numeric indices if
4110 * no pages were moved
4112 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4113 array $changeTags = []
4115 global $wgMaximumMovedPages;
4116 // Check permissions
4117 if ( !$this->userCan( 'move-subpages' ) ) {
4119 [ 'cant-move-subpages' ],
4122 // Do the source and target namespaces support subpages?
4123 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4125 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4128 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4130 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4134 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4137 foreach ( $subpages as $oldSubpage ) {
4139 if ( $count > $wgMaximumMovedPages ) {
4140 $retval[$oldSubpage->getPrefixedText()] = [
4141 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4146 // We don't know whether this function was called before
4147 // or after moving the root page, so check both
4149 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4150 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4152 // When moving a page to a subpage of itself,
4153 // don't move it twice
4156 $newPageName = preg_replace(
4157 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4158 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4159 $oldSubpage->getDBkey() );
4160 if ( $oldSubpage->isTalkPage() ) {
4161 $newNs = $nt->getTalkPage()->getNamespace();
4163 $newNs = $nt->getSubjectPage()->getNamespace();
4165 # T16385: we need makeTitleSafe because the new page names may
4166 # be longer than 255 characters.
4167 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4169 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4170 if ( $success === true ) {
4171 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4173 $retval[$oldSubpage->getPrefixedText()] = $success;
4180 * Checks if this page is just a one-rev redirect.
4181 * Adds lock, so don't use just for light purposes.
4185 public function isSingleRevRedirect() {
4186 global $wgContentHandlerUseDB;
4188 $dbw = wfGetDB( DB_MASTER
);
4191 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4192 if ( $wgContentHandlerUseDB ) {
4193 $fields[] = 'page_content_model';
4196 $row = $dbw->selectRow( 'page',
4202 # Cache some fields we may want
4203 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4204 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4205 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4206 $this->mContentModel
= $row && isset( $row->page_content_model
)
4207 ?
strval( $row->page_content_model
)
4210 if ( !$this->mRedirect
) {
4213 # Does the article have a history?
4214 $row = $dbw->selectField( [ 'page', 'revision' ],
4216 [ 'page_namespace' => $this->mNamespace
,
4217 'page_title' => $this->mDbkeyform
,
4219 'page_latest != rev_id'
4224 # Return true if there was no history
4225 return ( $row === false );
4229 * Checks if $this can be moved to a given Title
4230 * - Selects for update, so don't call it unless you mean business
4232 * @deprecated since 1.25, use MovePage's methods instead
4233 * @param Title $nt The new title to check
4236 public function isValidMoveTarget( $nt ) {
4237 # Is it an existing file?
4238 if ( $nt->getNamespace() == NS_FILE
) {
4239 $file = wfLocalFile( $nt );
4240 $file->load( File
::READ_LATEST
);
4241 if ( $file->exists() ) {
4242 wfDebug( __METHOD__
. ": file exists\n" );
4246 # Is it a redirect with no history?
4247 if ( !$nt->isSingleRevRedirect() ) {
4248 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4251 # Get the article text
4252 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4253 if ( !is_object( $rev ) ) {
4256 $content = $rev->getContent();
4257 # Does the redirect point to the source?
4258 # Or is it a broken self-redirect, usually caused by namespace collisions?
4259 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4261 if ( $redirTitle ) {
4262 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4263 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4264 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4270 # Fail safe (not a redirect after all. strange.)
4271 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4272 " is a redirect, but it doesn't contain a valid redirect.\n" );
4278 * Get categories to which this Title belongs and return an array of
4279 * categories' names.
4281 * @return array Array of parents in the form:
4282 * $parent => $currentarticle
4284 public function getParentCategories() {
4287 $titleKey = $this->getArticleID();
4289 if ( $titleKey === 0 ) {
4293 $dbr = wfGetDB( DB_REPLICA
);
4295 $res = $dbr->select(
4298 [ 'cl_from' => $titleKey ],
4302 if ( $res->numRows() > 0 ) {
4303 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4304 foreach ( $res as $row ) {
4305 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4306 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4307 $this->getFullText();
4314 * Get a tree of parent categories
4316 * @param array $children Array with the children in the keys, to check for circular refs
4317 * @return array Tree of parent categories
4319 public function getParentCategoryTree( $children = [] ) {
4321 $parents = $this->getParentCategories();
4324 foreach ( $parents as $parent => $current ) {
4325 if ( array_key_exists( $parent, $children ) ) {
4326 # Circular reference
4327 $stack[$parent] = [];
4329 $nt = self
::newFromText( $parent );
4331 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4341 * Get an associative array for selecting this title from
4344 * @return array Array suitable for the $where parameter of DB::select()
4346 public function pageCond() {
4347 if ( $this->mArticleID
> 0 ) {
4348 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4349 return [ 'page_id' => $this->mArticleID
];
4351 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4356 * Get next/previous revision ID relative to another revision ID
4357 * @param int $revId Revision ID. Get the revision that was before this one.
4358 * @param int $flags Title::GAID_FOR_UPDATE
4359 * @param string $dir 'next' or 'prev'
4360 * @return int|bool New revision ID, or false if none exists
4362 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4363 $revId = (int)$revId;
4364 if ( $dir === 'next' ) {
4367 } elseif ( $dir === 'prev' ) {
4371 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4374 if ( $flags & self
::GAID_FOR_UPDATE
) {
4375 $db = wfGetDB( DB_MASTER
);
4377 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4380 // Intentionally not caring if the specified revision belongs to this
4381 // page. We only care about the timestamp.
4382 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4383 if ( $ts === false ) {
4384 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4385 if ( $ts === false ) {
4386 // Or should this throw an InvalidArgumentException or something?
4390 $ts = $db->addQuotes( $ts );
4392 $revId = $db->selectField( 'revision', 'rev_id',
4394 'rev_page' => $this->getArticleID( $flags ),
4395 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4399 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4400 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4404 if ( $revId === false ) {
4407 return intval( $revId );
4412 * Get the revision ID of the previous revision
4414 * @param int $revId Revision ID. Get the revision that was before this one.
4415 * @param int $flags Title::GAID_FOR_UPDATE
4416 * @return int|bool Old revision ID, or false if none exists
4418 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4419 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4423 * Get the revision ID of the next revision
4425 * @param int $revId Revision ID. Get the revision that was after this one.
4426 * @param int $flags Title::GAID_FOR_UPDATE
4427 * @return int|bool Next revision ID, or false if none exists
4429 public function getNextRevisionID( $revId, $flags = 0 ) {
4430 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4434 * Get the first revision of the page
4436 * @param int $flags Title::GAID_FOR_UPDATE
4437 * @return Revision|null If page doesn't exist
4439 public function getFirstRevision( $flags = 0 ) {
4440 $pageId = $this->getArticleID( $flags );
4442 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4443 $revQuery = Revision
::getQueryInfo();
4444 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4445 [ 'rev_page' => $pageId ],
4448 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4449 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4454 return new Revision( $row, 0, $this );
4461 * Get the oldest revision timestamp of this page
4463 * @param int $flags Title::GAID_FOR_UPDATE
4464 * @return string|null MW timestamp
4466 public function getEarliestRevTime( $flags = 0 ) {
4467 $rev = $this->getFirstRevision( $flags );
4468 return $rev ?
$rev->getTimestamp() : null;
4472 * Check if this is a new page
4476 public function isNewPage() {
4477 $dbr = wfGetDB( DB_REPLICA
);
4478 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4482 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4486 public function isBigDeletion() {
4487 global $wgDeleteRevisionsLimit;
4489 if ( !$wgDeleteRevisionsLimit ) {
4493 if ( $this->mIsBigDeletion
=== null ) {
4494 $dbr = wfGetDB( DB_REPLICA
);
4496 $revCount = $dbr->selectRowCount(
4499 [ 'rev_page' => $this->getArticleID() ],
4501 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4504 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4507 return $this->mIsBigDeletion
;
4511 * Get the approximate revision count of this page.
4515 public function estimateRevisionCount() {
4516 if ( !$this->exists() ) {
4520 if ( $this->mEstimateRevisions
=== null ) {
4521 $dbr = wfGetDB( DB_REPLICA
);
4522 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4523 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4526 return $this->mEstimateRevisions
;
4530 * Get the number of revisions between the given revision.
4531 * Used for diffs and other things that really need it.
4533 * @param int|Revision $old Old revision or rev ID (first before range)
4534 * @param int|Revision $new New revision or rev ID (first after range)
4535 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4536 * @return int Number of revisions between these revisions.
4538 public function countRevisionsBetween( $old, $new, $max = null ) {
4539 if ( !( $old instanceof Revision
) ) {
4540 $old = Revision
::newFromTitle( $this, (int)$old );
4542 if ( !( $new instanceof Revision
) ) {
4543 $new = Revision
::newFromTitle( $this, (int)$new );
4545 if ( !$old ||
!$new ) {
4546 return 0; // nothing to compare
4548 $dbr = wfGetDB( DB_REPLICA
);
4550 'rev_page' => $this->getArticleID(),
4551 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4552 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4554 if ( $max !== null ) {
4555 return $dbr->selectRowCount( 'revision', '1',
4558 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4561 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4566 * Get the authors between the given revisions or revision IDs.
4567 * Used for diffs and other things that really need it.
4571 * @param int|Revision $old Old revision or rev ID (first before range by default)
4572 * @param int|Revision $new New revision or rev ID (first after range by default)
4573 * @param int $limit Maximum number of authors
4574 * @param string|array $options (Optional): Single option, or an array of options:
4575 * 'include_old' Include $old in the range; $new is excluded.
4576 * 'include_new' Include $new in the range; $old is excluded.
4577 * 'include_both' Include both $old and $new in the range.
4578 * Unknown option values are ignored.
4579 * @return array|null Names of revision authors in the range; null if not both revisions exist
4581 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4582 if ( !( $old instanceof Revision
) ) {
4583 $old = Revision
::newFromTitle( $this, (int)$old );
4585 if ( !( $new instanceof Revision
) ) {
4586 $new = Revision
::newFromTitle( $this, (int)$new );
4588 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4589 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4590 // in the sanity check below?
4591 if ( !$old ||
!$new ) {
4592 return null; // nothing to compare
4597 $options = (array)$options;
4598 if ( in_array( 'include_old', $options ) ) {
4601 if ( in_array( 'include_new', $options ) ) {
4604 if ( in_array( 'include_both', $options ) ) {
4608 // No DB query needed if $old and $new are the same or successive revisions:
4609 if ( $old->getId() === $new->getId() ) {
4610 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4612 [ $old->getUserText( Revision
::RAW
) ];
4613 } elseif ( $old->getId() === $new->getParentId() ) {
4614 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4615 $authors[] = $old->getUserText( Revision
::RAW
);
4616 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4617 $authors[] = $new->getUserText( Revision
::RAW
);
4619 } elseif ( $old_cmp === '>=' ) {
4620 $authors[] = $old->getUserText( Revision
::RAW
);
4621 } elseif ( $new_cmp === '<=' ) {
4622 $authors[] = $new->getUserText( Revision
::RAW
);
4626 $dbr = wfGetDB( DB_REPLICA
);
4627 $revQuery = Revision
::getQueryInfo();
4628 $authors = $dbr->selectFieldValues(
4629 $revQuery['tables'],
4630 $revQuery['fields']['rev_user_text'],
4632 'rev_page' => $this->getArticleID(),
4633 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4634 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4636 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4643 * Get the number of authors between the given revisions or revision IDs.
4644 * Used for diffs and other things that really need it.
4646 * @param int|Revision $old Old revision or rev ID (first before range by default)
4647 * @param int|Revision $new New revision or rev ID (first after range by default)
4648 * @param int $limit Maximum number of authors
4649 * @param string|array $options (Optional): Single option, or an array of options:
4650 * 'include_old' Include $old in the range; $new is excluded.
4651 * 'include_new' Include $new in the range; $old is excluded.
4652 * 'include_both' Include both $old and $new in the range.
4653 * Unknown option values are ignored.
4654 * @return int Number of revision authors in the range; zero if not both revisions exist
4656 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4657 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4658 return $authors ?
count( $authors ) : 0;
4662 * Compare with another title.
4664 * @param Title $title
4667 public function equals( Title
$title ) {
4668 // Note: === is necessary for proper matching of number-like titles.
4669 return $this->mInterwiki
=== $title->mInterwiki
4670 && $this->mNamespace
== $title->mNamespace
4671 && $this->mDbkeyform
=== $title->mDbkeyform
;
4675 * Check if this title is a subpage of another title
4677 * @param Title $title
4680 public function isSubpageOf( Title
$title ) {
4681 return $this->mInterwiki
=== $title->mInterwiki
4682 && $this->mNamespace
== $title->mNamespace
4683 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4687 * Check if page exists. For historical reasons, this function simply
4688 * checks for the existence of the title in the page table, and will
4689 * thus return false for interwiki links, special pages and the like.
4690 * If you want to know if a title can be meaningfully viewed, you should
4691 * probably call the isKnown() method instead.
4693 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4694 * from master/for update
4697 public function exists( $flags = 0 ) {
4698 $exists = $this->getArticleID( $flags ) != 0;
4699 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4704 * Should links to this title be shown as potentially viewable (i.e. as
4705 * "bluelinks"), even if there's no record by this title in the page
4708 * This function is semi-deprecated for public use, as well as somewhat
4709 * misleadingly named. You probably just want to call isKnown(), which
4710 * calls this function internally.
4712 * (ISSUE: Most of these checks are cheap, but the file existence check
4713 * can potentially be quite expensive. Including it here fixes a lot of
4714 * existing code, but we might want to add an optional parameter to skip
4715 * it and any other expensive checks.)
4719 public function isAlwaysKnown() {
4723 * Allows overriding default behavior for determining if a page exists.
4724 * If $isKnown is kept as null, regular checks happen. If it's
4725 * a boolean, this value is returned by the isKnown method.
4729 * @param Title $title
4730 * @param bool|null $isKnown
4732 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4734 if ( !is_null( $isKnown ) ) {
4738 if ( $this->isExternal() ) {
4739 return true; // any interwiki link might be viewable, for all we know
4742 switch ( $this->mNamespace
) {
4745 // file exists, possibly in a foreign repo
4746 return (bool)wfFindFile( $this );
4748 // valid special page
4749 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4750 exists( $this->mDbkeyform
);
4752 // selflink, possibly with fragment
4753 return $this->mDbkeyform
== '';
4755 // known system message
4756 return $this->hasSourceText() !== false;
4763 * Does this title refer to a page that can (or might) be meaningfully
4764 * viewed? In particular, this function may be used to determine if
4765 * links to the title should be rendered as "bluelinks" (as opposed to
4766 * "redlinks" to non-existent pages).
4767 * Adding something else to this function will cause inconsistency
4768 * since LinkHolderArray calls isAlwaysKnown() and does its own
4769 * page existence check.
4773 public function isKnown() {
4774 return $this->isAlwaysKnown() ||
$this->exists();
4778 * Does this page have source text?
4782 public function hasSourceText() {
4783 if ( $this->exists() ) {
4787 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4788 // If the page doesn't exist but is a known system message, default
4789 // message content will be displayed, same for language subpages-
4790 // Use always content language to avoid loading hundreds of languages
4791 // to get the link color.
4792 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4793 list( $name, ) = MessageCache
::singleton()->figureMessage(
4794 $contLang->lcfirst( $this->getText() )
4796 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4797 return $message->exists();
4804 * Get the default (plain) message contents for an page that overrides an
4805 * interface message key.
4807 * Primary use cases:
4810 * - Show default when viewing the page. The Article::getSubstituteContent
4811 * method displays the default message content, instead of the
4812 * 'noarticletext' placeholder message normally used.
4815 * - Title of edit page. When creating an interface message override,
4816 * the editor is told they are "Editing the page", instead of
4817 * "Creating the page". (EditPage::setHeaders)
4818 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4819 * or editing a an interface message override. (EditPage::showIntro)
4820 * - Opening the editor. The contents of the localisation message are used
4821 * as contents of the editor when creating a new page in the MediaWiki
4822 * namespace. This simplifies the process for editors when "changing"
4823 * an interface message by creating an override. (EditPage::getContentObject)
4824 * - Showing a diff. The left-hand side of a diff when an editor is
4825 * previewing their changes before saving the creation of a page in the
4826 * MediaWiki namespace. (EditPage::showDiff)
4827 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4828 * page with the proposed content matching the interface message default,
4829 * the save is rejected, the same way we disallow blank pages from being
4830 * created. (EditPage::internalAttemptSave)
4833 * - Default content, when using the 'prepend' or 'append' feature.
4836 * - Label the create action as "Edit", if the page can be an override.
4838 * @return string|bool
4840 public function getDefaultMessageText() {
4841 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4845 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4846 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4848 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4850 if ( $message->exists() ) {
4851 return $message->plain();
4858 * Updates page_touched for this page; called from LinksUpdate.php
4860 * @param string|null $purgeTime [optional] TS_MW timestamp
4861 * @return bool True if the update succeeded
4863 public function invalidateCache( $purgeTime = null ) {
4864 if ( wfReadOnly() ) {
4866 } elseif ( $this->mArticleID
=== 0 ) {
4867 return true; // avoid gap locking if we know it's not there
4870 $dbw = wfGetDB( DB_MASTER
);
4871 $dbw->onTransactionPreCommitOrIdle(
4872 function () use ( $dbw ) {
4873 ResourceLoaderWikiModule
::invalidateModuleCache(
4874 $this, null, null, $dbw->getDomainId() );
4879 $conds = $this->pageCond();
4880 DeferredUpdates
::addUpdate(
4881 new AutoCommitUpdate(
4884 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4885 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4888 [ 'page_touched' => $dbTimestamp ],
4889 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4892 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4895 DeferredUpdates
::PRESEND
4902 * Update page_touched timestamps and send CDN purge messages for
4903 * pages linking to this title. May be sent to the job queue depending
4904 * on the number of links. Typically called on create and delete.
4906 public function touchLinks() {
4907 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4908 if ( $this->mNamespace
== NS_CATEGORY
) {
4909 DeferredUpdates
::addUpdate(
4910 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4916 * Get the last touched timestamp
4918 * @param IDatabase|null $db
4919 * @return string|false Last-touched timestamp
4921 public function getTouched( $db = null ) {
4922 if ( $db === null ) {
4923 $db = wfGetDB( DB_REPLICA
);
4925 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4930 * Get the timestamp when this page was updated since the user last saw it.
4932 * @param User|null $user
4933 * @return string|null
4935 public function getNotificationTimestamp( $user = null ) {
4938 // Assume current user if none given
4942 // Check cache first
4943 $uid = $user->getId();
4947 // avoid isset here, as it'll return false for null entries
4948 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4949 return $this->mNotificationTimestamp
[$uid];
4951 // Don't cache too much!
4952 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4953 $this->mNotificationTimestamp
= [];
4956 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4957 $watchedItem = $store->getWatchedItem( $user, $this );
4958 if ( $watchedItem ) {
4959 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4961 $this->mNotificationTimestamp
[$uid] = false;
4964 return $this->mNotificationTimestamp
[$uid];
4968 * Generate strings used for xml 'id' names in monobook tabs
4970 * @param string $prepend Defaults to 'nstab-'
4971 * @return string XML 'id' name
4973 public function getNamespaceKey( $prepend = 'nstab-' ) {
4974 // Gets the subject namespace of this title
4975 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4976 // Prefer canonical namespace name for HTML IDs
4977 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4978 if ( $namespaceKey === false ) {
4979 // Fallback to localised text
4980 $namespaceKey = $this->getSubjectNsText();
4982 // Makes namespace key lowercase
4983 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4985 if ( $namespaceKey == '' ) {
4986 $namespaceKey = 'main';
4988 // Changes file to image for backwards compatibility
4989 if ( $namespaceKey == 'file' ) {
4990 $namespaceKey = 'image';
4992 return $prepend . $namespaceKey;
4996 * Get all extant redirects to this Title
4998 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4999 * @return Title[] Array of Title redirects to this title
5001 public function getRedirectsHere( $ns = null ) {
5004 $dbr = wfGetDB( DB_REPLICA
);
5006 'rd_namespace' => $this->mNamespace
,
5007 'rd_title' => $this->mDbkeyform
,
5010 if ( $this->isExternal() ) {
5011 $where['rd_interwiki'] = $this->mInterwiki
;
5013 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
5015 if ( !is_null( $ns ) ) {
5016 $where['page_namespace'] = $ns;
5019 $res = $dbr->select(
5020 [ 'redirect', 'page' ],
5021 [ 'page_namespace', 'page_title' ],
5026 foreach ( $res as $row ) {
5027 $redirs[] = self
::newFromRow( $row );
5033 * Check if this Title is a valid redirect target
5037 public function isValidRedirectTarget() {
5038 global $wgInvalidRedirectTargets;
5040 if ( $this->isSpecialPage() ) {
5041 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5042 if ( $this->isSpecial( 'Userlogout' ) ) {
5046 foreach ( $wgInvalidRedirectTargets as $target ) {
5047 if ( $this->isSpecial( $target ) ) {
5057 * Get a backlink cache object
5059 * @return BacklinkCache
5061 public function getBacklinkCache() {
5062 return BacklinkCache
::get( $this );
5066 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5070 public function canUseNoindex() {
5071 global $wgExemptFromUserRobotsControl;
5073 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
5074 ? MWNamespace
::getContentNamespaces()
5075 : $wgExemptFromUserRobotsControl;
5077 return !in_array( $this->mNamespace
, $bannedNamespaces );
5081 * Returns the raw sort key to be used for categories, with the specified
5082 * prefix. This will be fed to Collation::getSortKey() to get a
5083 * binary sortkey that can be used for actual sorting.
5085 * @param string $prefix The prefix to be used, specified using
5086 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5090 public function getCategorySortkey( $prefix = '' ) {
5091 $unprefixed = $this->getText();
5093 // Anything that uses this hook should only depend
5094 // on the Title object passed in, and should probably
5095 // tell the users to run updateCollations.php --force
5096 // in order to re-sort existing category relations.
5097 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5098 if ( $prefix !== '' ) {
5099 # Separate with a line feed, so the unprefixed part is only used as
5100 # a tiebreaker when two pages have the exact same prefix.
5101 # In UCA, tab is the only character that can sort above LF
5102 # so we strip both of them from the original prefix.
5103 $prefix = strtr( $prefix, "\n\t", ' ' );
5104 return "$prefix\n$unprefixed";
5110 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5111 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5112 * the db, it will return NULL.
5114 * @return string|null|bool
5116 private function getDbPageLanguageCode() {
5117 global $wgPageLanguageUseDB;
5119 // check, if the page language could be saved in the database, and if so and
5120 // the value is not requested already, lookup the page language using LinkCache
5121 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5122 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5123 $linkCache->addLinkObj( $this );
5124 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5127 return $this->mDbPageLanguage
;
5131 * Get the language in which the content of this page is written in
5132 * wikitext. Defaults to content language, but in certain cases it can be
5133 * e.g. $wgLang (such as special pages, which are in the user language).
5138 public function getPageLanguage() {
5139 global $wgLang, $wgLanguageCode;
5140 if ( $this->isSpecialPage() ) {
5141 // special pages are in the user language
5145 // Checking if DB language is set
5146 $dbPageLanguage = $this->getDbPageLanguageCode();
5147 if ( $dbPageLanguage ) {
5148 return wfGetLangObj( $dbPageLanguage );
5151 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5152 // Note that this may depend on user settings, so the cache should
5153 // be only per-request.
5154 // NOTE: ContentHandler::getPageLanguage() may need to load the
5155 // content to determine the page language!
5156 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5158 $contentHandler = ContentHandler
::getForTitle( $this );
5159 $langObj = $contentHandler->getPageLanguage( $this );
5160 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5162 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5169 * Get the language in which the content of this page is written when
5170 * viewed by user. Defaults to content language, but in certain cases it can be
5171 * e.g. $wgLang (such as special pages, which are in the user language).
5176 public function getPageViewLanguage() {
5179 if ( $this->isSpecialPage() ) {
5180 // If the user chooses a variant, the content is actually
5181 // in a language whose code is the variant code.
5182 $variant = $wgLang->getPreferredVariant();
5183 if ( $wgLang->getCode() !== $variant ) {
5184 return Language
::factory( $variant );
5190 // Checking if DB language is set
5191 $dbPageLanguage = $this->getDbPageLanguageCode();
5192 if ( $dbPageLanguage ) {
5193 $pageLang = wfGetLangObj( $dbPageLanguage );
5194 $variant = $pageLang->getPreferredVariant();
5195 if ( $pageLang->getCode() !== $variant ) {
5196 $pageLang = Language
::factory( $variant );
5202 // @note Can't be cached persistently, depends on user settings.
5203 // @note ContentHandler::getPageViewLanguage() may need to load the
5204 // content to determine the page language!
5205 $contentHandler = ContentHandler
::getForTitle( $this );
5206 $pageLang = $contentHandler->getPageViewLanguage( $this );
5211 * Get a list of rendered edit notices for this page.
5213 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5214 * they will already be wrapped in paragraphs.
5217 * @param int $oldid Revision ID that's being edited
5220 public function getEditNotices( $oldid = 0 ) {
5223 // Optional notice for the entire namespace
5224 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5225 $msg = wfMessage( $editnotice_ns );
5226 if ( $msg->exists() ) {
5227 $html = $msg->parseAsBlock();
5228 // Edit notices may have complex logic, but output nothing (T91715)
5229 if ( trim( $html ) !== '' ) {
5230 $notices[$editnotice_ns] = Html
::rawElement(
5234 'mw-editnotice-namespace',
5235 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5242 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5243 // Optional notice for page itself and any parent page
5244 $editnotice_base = $editnotice_ns;
5245 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
5246 $editnotice_base .= '-' . $part;
5247 $msg = wfMessage( $editnotice_base );
5248 if ( $msg->exists() ) {
5249 $html = $msg->parseAsBlock();
5250 if ( trim( $html ) !== '' ) {
5251 $notices[$editnotice_base] = Html
::rawElement(
5255 'mw-editnotice-base',
5256 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5264 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5265 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5266 $msg = wfMessage( $editnoticeText );
5267 if ( $msg->exists() ) {
5268 $html = $msg->parseAsBlock();
5269 if ( trim( $html ) !== '' ) {
5270 $notices[$editnoticeText] = Html
::rawElement(
5274 'mw-editnotice-page',
5275 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5283 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5290 public function __sleep() {
5298 'mDefaultNamespace',
5302 public function __wakeup() {
5303 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5304 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5305 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );