3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
{
40 /** @var 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
958 * @return string DB key
960 function getUserCaseDBKey() {
961 if ( !is_null( $this->mUserCaseDBKey
) ) {
962 return $this->mUserCaseDBKey
;
964 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
965 return $this->mDbkeyform
;
970 * Get the namespace index, i.e. one of the NS_xxxx constants.
972 * @return int Namespace index
974 public function getNamespace() {
975 return $this->mNamespace
;
979 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
981 * @todo Deprecate this in favor of SlotRecord::getModel()
983 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
984 * @return string Content model id
986 public function getContentModel( $flags = 0 ) {
987 if ( !$this->mForcedContentModel
988 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
989 && $this->getArticleID( $flags )
991 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
992 $linkCache->addLinkObj( $this ); # in case we already had an article ID
993 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
996 if ( !$this->mContentModel
) {
997 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1000 return $this->mContentModel
;
1004 * Convenience method for checking a title's content model name
1006 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1007 * @return bool True if $this->getContentModel() == $id
1009 public function hasContentModel( $id ) {
1010 return $this->getContentModel() == $id;
1014 * Set a proposed content model for the page for permissions
1015 * checking. This does not actually change the content model
1018 * Additionally, you should make sure you've checked
1019 * ContentHandler::canBeUsedOn() first.
1022 * @param string $model CONTENT_MODEL_XXX constant
1024 public function setContentModel( $model ) {
1025 $this->mContentModel
= $model;
1026 $this->mForcedContentModel
= true;
1030 * Get the namespace text
1032 * @return string|false Namespace text
1034 public function getNsText() {
1035 if ( $this->isExternal() ) {
1036 // This probably shouldn't even happen, except for interwiki transclusion.
1037 // If possible, use the canonical name for the foreign namespace.
1038 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1039 if ( $nsText !== false ) {
1045 $formatter = self
::getTitleFormatter();
1046 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1047 } catch ( InvalidArgumentException
$ex ) {
1048 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1054 * Get the namespace text of the subject (rather than talk) page
1056 * @return string Namespace text
1058 public function getSubjectNsText() {
1059 return MediaWikiServices
::getInstance()->getContentLanguage()->
1060 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1064 * Get the namespace text of the talk page
1066 * @return string Namespace text
1068 public function getTalkNsText() {
1069 return MediaWikiServices
::getInstance()->getContentLanguage()->
1070 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1074 * Can this title have a corresponding talk page?
1076 * @deprecated since 1.30, use canHaveTalkPage() instead.
1078 * @return bool True if this title either is a talk page or can have a talk page associated.
1080 public function canTalk() {
1081 return $this->canHaveTalkPage();
1085 * Can this title have a corresponding talk page?
1087 * @see MWNamespace::hasTalkNamespace
1090 * @return bool True if this title either is a talk page or can have a talk page associated.
1092 public function canHaveTalkPage() {
1093 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1097 * Is this in a namespace that allows actual pages?
1101 public function canExist() {
1102 return $this->mNamespace
>= NS_MAIN
;
1106 * Can this title be added to a user's watchlist?
1110 public function isWatchable() {
1111 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1115 * Returns true if this is a special page.
1119 public function isSpecialPage() {
1120 return $this->mNamespace
== NS_SPECIAL
;
1124 * Returns true if this title resolves to the named special page
1126 * @param string $name The special page name
1129 public function isSpecial( $name ) {
1130 if ( $this->isSpecialPage() ) {
1131 list( $thisName, /* $subpage */ ) =
1132 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1133 resolveAlias( $this->mDbkeyform
);
1134 if ( $name == $thisName ) {
1142 * If the Title refers to a special page alias which is not the local default, resolve
1143 * the alias, and localise the name as necessary. Otherwise, return $this
1147 public function fixSpecialName() {
1148 if ( $this->isSpecialPage() ) {
1149 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1150 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1151 if ( $canonicalName ) {
1152 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1153 if ( $localName != $this->mDbkeyform
) {
1154 return self
::makeTitle( NS_SPECIAL
, $localName );
1162 * Returns true if the title is inside the specified namespace.
1164 * Please make use of this instead of comparing to getNamespace()
1165 * This function is much more resistant to changes we may make
1166 * to namespaces than code that makes direct comparisons.
1167 * @param int $ns The namespace
1171 public function inNamespace( $ns ) {
1172 return MWNamespace
::equals( $this->mNamespace
, $ns );
1176 * Returns true if the title is inside one of the specified namespaces.
1178 * @param int|int[] $namespaces,... The namespaces to check for
1182 public function inNamespaces( /* ... */ ) {
1183 $namespaces = func_get_args();
1184 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1185 $namespaces = $namespaces[0];
1188 foreach ( $namespaces as $ns ) {
1189 if ( $this->inNamespace( $ns ) ) {
1198 * Returns true if the title has the same subject namespace as the
1199 * namespace specified.
1200 * For example this method will take NS_USER and return true if namespace
1201 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1202 * as their subject namespace.
1204 * This is MUCH simpler than individually testing for equivalence
1205 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1210 public function hasSubjectNamespace( $ns ) {
1211 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1215 * Is this Title in a namespace which contains content?
1216 * In other words, is this a content page, for the purposes of calculating
1221 public function isContentPage() {
1222 return MWNamespace
::isContent( $this->mNamespace
);
1226 * Would anybody with sufficient privileges be able to move this page?
1227 * Some pages just aren't movable.
1231 public function isMovable() {
1232 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1233 // Interwiki title or immovable namespace. Hooks don't get to override here
1238 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1243 * Is this the mainpage?
1244 * @note Title::newFromText seems to be sufficiently optimized by the title
1245 * cache that we don't need to over-optimize by doing direct comparisons and
1246 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1247 * ends up reporting something differently than $title->isMainPage();
1252 public function isMainPage() {
1253 return $this->equals( self
::newMainPage() );
1257 * Is this a subpage?
1261 public function isSubpage() {
1262 return MWNamespace
::hasSubpages( $this->mNamespace
)
1263 ?
strpos( $this->getText(), '/' ) !== false
1268 * Is this a conversion table for the LanguageConverter?
1272 public function isConversionTable() {
1273 // @todo ConversionTable should become a separate content model.
1275 return $this->mNamespace
== NS_MEDIAWIKI
&&
1276 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1280 * Does that page contain wikitext, or it is JS, CSS or whatever?
1284 public function isWikitextPage() {
1285 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1289 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1290 * global UI. This is generally true for pages in the MediaWiki namespace having
1291 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1293 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1296 * Note that this method should not return true for pages that contain and show
1297 * "inactive" CSS, JSON, or JS.
1302 public function isSiteConfigPage() {
1304 $this->isSiteCssConfigPage()
1305 ||
$this->isSiteJsonConfigPage()
1306 ||
$this->isSiteJsConfigPage()
1312 * @deprecated Since 1.31; use ::isSiteConfigPage() instead (which also checks for JSON pages)
1314 public function isCssOrJsPage() {
1315 wfDeprecated( __METHOD__
, '1.31' );
1316 return ( NS_MEDIAWIKI
== $this->mNamespace
1317 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1318 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1322 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1327 public function isUserConfigPage() {
1329 $this->isUserCssConfigPage()
1330 ||
$this->isUserJsonConfigPage()
1331 ||
$this->isUserJsConfigPage()
1337 * @deprecated Since 1.31; use ::isUserConfigPage() instead (which also checks for JSON pages)
1339 public function isCssJsSubpage() {
1340 wfDeprecated( __METHOD__
, '1.31' );
1341 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1342 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1343 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1347 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1349 * @return string Containing skin name from .css, .json, or .js subpage title
1352 public function getSkinFromConfigSubpage() {
1353 $subpage = explode( '/', $this->mTextform
);
1354 $subpage = $subpage[count( $subpage ) - 1];
1355 $lastdot = strrpos( $subpage, '.' );
1356 if ( $lastdot === false ) {
1357 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1359 return substr( $subpage, 0, $lastdot );
1363 * @deprecated Since 1.31; use ::getSkinFromConfigSubpage() instead
1364 * @return string Containing skin name from .css, .json, or .js subpage title
1366 public function getSkinFromCssJsSubpage() {
1367 wfDeprecated( __METHOD__
, '1.31' );
1368 return $this->getSkinFromConfigSubpage();
1372 * Is this a CSS "config" sub-page of a user page?
1377 public function isUserCssConfigPage() {
1379 NS_USER
== $this->mNamespace
1380 && $this->isSubpage()
1381 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1386 * @deprecated Since 1.31; use ::isUserCssConfigPage()
1389 public function isCssSubpage() {
1390 wfDeprecated( __METHOD__
, '1.31' );
1391 return $this->isUserCssConfigPage();
1395 * Is this a JSON "config" sub-page of a user page?
1400 public function isUserJsonConfigPage() {
1402 NS_USER
== $this->mNamespace
1403 && $this->isSubpage()
1404 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1409 * Is this a JS "config" sub-page of a user page?
1414 public function isUserJsConfigPage() {
1416 NS_USER
== $this->mNamespace
1417 && $this->isSubpage()
1418 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1423 * @deprecated Since 1.31; use ::isUserJsConfigPage()
1426 public function isJsSubpage() {
1427 wfDeprecated( __METHOD__
, '1.31' );
1428 return $this->isUserJsConfigPage();
1432 * Is this a sitewide CSS "config" page?
1437 public function isSiteCssConfigPage() {
1439 NS_MEDIAWIKI
== $this->mNamespace
1441 $this->hasContentModel( CONTENT_MODEL_CSS
)
1442 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1443 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1444 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1450 * Is this a sitewide JSON "config" page?
1455 public function isSiteJsonConfigPage() {
1457 NS_MEDIAWIKI
== $this->mNamespace
1459 $this->hasContentModel( CONTENT_MODEL_JSON
)
1460 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1461 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1462 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1468 * Is this a sitewide JS "config" page?
1473 public function isSiteJsConfigPage() {
1475 NS_MEDIAWIKI
== $this->mNamespace
1477 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1478 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1479 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1480 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1486 * Is this a message which can contain raw HTML?
1491 public function isRawHtmlMessage() {
1492 global $wgRawHtmlMessages;
1494 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1497 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1498 return in_array( $message, $wgRawHtmlMessages, true );
1502 * Is this a talk page of some sort?
1506 public function isTalkPage() {
1507 return MWNamespace
::isTalk( $this->mNamespace
);
1511 * Get a Title object associated with the talk page of this article
1513 * @return Title The object for the talk page
1515 public function getTalkPage() {
1516 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1520 * Get a Title object associated with the talk page of this article,
1521 * if such a talk page can exist.
1525 * @return Title|null The object for the talk page,
1526 * or null if no associated talk page can exist, according to canHaveTalkPage().
1528 public function getTalkPageIfDefined() {
1529 if ( !$this->canHaveTalkPage() ) {
1533 return $this->getTalkPage();
1537 * Get a title object associated with the subject page of this
1540 * @return Title The object for the subject page
1542 public function getSubjectPage() {
1543 // Is this the same title?
1544 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1545 if ( $this->mNamespace
== $subjectNS ) {
1548 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1552 * Get the other title for this page, if this is a subject page
1553 * get the talk page, if it is a subject page get the talk page
1556 * @throws MWException If the page doesn't have an other page
1559 public function getOtherPage() {
1560 if ( $this->isSpecialPage() ) {
1561 throw new MWException( 'Special pages cannot have other pages' );
1563 if ( $this->isTalkPage() ) {
1564 return $this->getSubjectPage();
1566 if ( !$this->canHaveTalkPage() ) {
1567 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1569 return $this->getTalkPage();
1574 * Get the default namespace index, for when there is no namespace
1576 * @return int Default namespace index
1578 public function getDefaultNamespace() {
1579 return $this->mDefaultNamespace
;
1583 * Get the Title fragment (i.e.\ the bit after the #) in text form
1585 * Use Title::hasFragment to check for a fragment
1587 * @return string Title fragment
1589 public function getFragment() {
1590 return $this->mFragment
;
1594 * Check if a Title fragment is set
1599 public function hasFragment() {
1600 return $this->mFragment
!== '';
1604 * Get the fragment in URL form, including the "#" character if there is one
1606 * @return string Fragment in URL form
1608 public function getFragmentForURL() {
1609 if ( !$this->hasFragment() ) {
1611 } elseif ( $this->isExternal()
1612 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1614 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1616 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1620 * Set the fragment for this title. Removes the first character from the
1621 * specified fragment before setting, so it assumes you're passing it with
1624 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1625 * or Title::createFragmentTarget().
1626 * Still in active use privately.
1629 * @param string $fragment Text
1631 public function setFragment( $fragment ) {
1632 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1636 * Creates a new Title for a different fragment of the same page.
1639 * @param string $fragment
1642 public function createFragmentTarget( $fragment ) {
1643 return self
::makeTitle(
1652 * Prefix some arbitrary text with the namespace or interwiki prefix
1655 * @param string $name The text
1656 * @return string The prefixed text
1658 private function prefix( $name ) {
1660 if ( $this->isExternal() ) {
1661 $p = $this->mInterwiki
. ':';
1664 if ( $this->mNamespace
!= 0 ) {
1665 $nsText = $this->getNsText();
1667 if ( $nsText === false ) {
1668 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1669 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1670 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1673 $p .= $nsText . ':';
1679 * Get the prefixed database key form
1681 * @return string The prefixed title, with underscores and
1682 * any interwiki and namespace prefixes
1684 public function getPrefixedDBkey() {
1685 $s = $this->prefix( $this->mDbkeyform
);
1686 $s = strtr( $s, ' ', '_' );
1691 * Get the prefixed title with spaces.
1692 * This is the form usually used for display
1694 * @return string The prefixed title, with spaces
1696 public function getPrefixedText() {
1697 if ( $this->prefixedText
=== null ) {
1698 $s = $this->prefix( $this->mTextform
);
1699 $s = strtr( $s, '_', ' ' );
1700 $this->prefixedText
= $s;
1702 return $this->prefixedText
;
1706 * Return a string representation of this title
1708 * @return string Representation of this title
1710 public function __toString() {
1711 return $this->getPrefixedText();
1715 * Get the prefixed title with spaces, plus any fragment
1716 * (part beginning with '#')
1718 * @return string The prefixed title, with spaces and the fragment, including '#'
1720 public function getFullText() {
1721 $text = $this->getPrefixedText();
1722 if ( $this->hasFragment() ) {
1723 $text .= '#' . $this->mFragment
;
1729 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1733 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1737 * @return string Root name
1740 public function getRootText() {
1741 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1742 return $this->getText();
1745 return strtok( $this->getText(), '/' );
1749 * Get the root page name title, i.e. the leftmost part before any slashes
1753 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1754 * # returns: Title{User:Foo}
1757 * @return Title Root title
1760 public function getRootTitle() {
1761 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1765 * Get the base page name without a namespace, i.e. the part before the subpage name
1769 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1770 * # returns: 'Foo/Bar'
1773 * @return string Base name
1775 public function getBaseText() {
1776 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1777 return $this->getText();
1780 $parts = explode( '/', $this->getText() );
1781 # Don't discard the real title if there's no subpage involved
1782 if ( count( $parts ) > 1 ) {
1783 unset( $parts[count( $parts ) - 1] );
1785 return implode( '/', $parts );
1789 * Get the base page name title, i.e. the part before the subpage name
1793 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1794 * # returns: Title{User:Foo/Bar}
1797 * @return Title Base title
1800 public function getBaseTitle() {
1801 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1805 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1809 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1813 * @return string Subpage name
1815 public function getSubpageText() {
1816 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1817 return $this->mTextform
;
1819 $parts = explode( '/', $this->mTextform
);
1820 return $parts[count( $parts ) - 1];
1824 * Get the title for a subpage of the current page
1828 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1829 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1832 * @param string $text The subpage name to add to the title
1833 * @return Title Subpage title
1836 public function getSubpage( $text ) {
1837 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1841 * Get a URL-encoded form of the subpage text
1843 * @return string URL-encoded subpage name
1845 public function getSubpageUrlForm() {
1846 $text = $this->getSubpageText();
1847 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1852 * Get a URL-encoded title (not an actual URL) including interwiki
1854 * @return string The URL-encoded form
1856 public function getPrefixedURL() {
1857 $s = $this->prefix( $this->mDbkeyform
);
1858 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1863 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1864 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1865 * second argument named variant. This was deprecated in favor
1866 * of passing an array of option with a "variant" key
1867 * Once $query2 is removed for good, this helper can be dropped
1868 * and the wfArrayToCgi moved to getLocalURL();
1870 * @since 1.19 (r105919)
1871 * @param array|string $query
1872 * @param string|string[]|bool $query2
1875 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1876 if ( $query2 !== false ) {
1877 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1878 "method called with a second parameter is deprecated. Add your " .
1879 "parameter to an array passed as the first parameter.", "1.19" );
1881 if ( is_array( $query ) ) {
1882 $query = wfArrayToCgi( $query );
1885 if ( is_string( $query2 ) ) {
1886 // $query2 is a string, we will consider this to be
1887 // a deprecated $variant argument and add it to the query
1888 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1890 $query2 = wfArrayToCgi( $query2 );
1892 // If we have $query content add a & to it first
1896 // Now append the queries together
1903 * Get a real URL referring to this title, with interwiki link and
1906 * @see self::getLocalURL for the arguments.
1908 * @param string|string[] $query
1909 * @param string|string[]|bool $query2
1910 * @param string|int|null $proto Protocol type to use in URL
1911 * @return string The URL
1913 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1914 $query = self
::fixUrlQueryArgs( $query, $query2 );
1916 # Hand off all the decisions on urls to getLocalURL
1917 $url = $this->getLocalURL( $query );
1919 # Expand the url to make it a full url. Note that getLocalURL has the
1920 # potential to output full urls for a variety of reasons, so we use
1921 # wfExpandUrl instead of simply prepending $wgServer
1922 $url = wfExpandUrl( $url, $proto );
1924 # Finally, add the fragment.
1925 $url .= $this->getFragmentForURL();
1926 // Avoid PHP 7.1 warning from passing $this by reference
1928 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1933 * Get a url appropriate for making redirects based on an untrusted url arg
1935 * This is basically the same as getFullUrl(), but in the case of external
1936 * interwikis, we send the user to a landing page, to prevent possible
1937 * phishing attacks and the like.
1939 * @note Uses current protocol by default, since technically relative urls
1940 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1941 * places where the url gets cached, as might pollute between
1942 * https and non-https users.
1943 * @see self::getLocalURL for the arguments.
1944 * @param array|string $query
1945 * @param string $proto Protocol type to use in URL
1946 * @return string A url suitable to use in an HTTP location header.
1948 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1950 if ( $this->isExternal() ) {
1951 $target = SpecialPage
::getTitleFor(
1953 $this->getPrefixedDBkey()
1956 return $target->getFullURL( $query, false, $proto );
1960 * Get a URL with no fragment or server name (relative URL) from a Title object.
1961 * If this page is generated with action=render, however,
1962 * $wgServer is prepended to make an absolute URL.
1964 * @see self::getFullURL to always get an absolute URL.
1965 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1966 * valid to link, locally, to the current Title.
1967 * @see self::newFromText to produce a Title object.
1969 * @param string|string[] $query An optional query string,
1970 * not used for interwiki links. Can be specified as an associative array as well,
1971 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1972 * Some query patterns will trigger various shorturl path replacements.
1973 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1974 * be an array. If a string is passed it will be interpreted as a deprecated
1975 * variant argument and urlencoded into a variant= argument.
1976 * This second query argument will be added to the $query
1977 * The second parameter is deprecated since 1.19. Pass it as a key,value
1978 * pair in the first parameter array instead.
1980 * @return string String of the URL.
1982 public function getLocalURL( $query = '', $query2 = false ) {
1983 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1985 $query = self
::fixUrlQueryArgs( $query, $query2 );
1987 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1989 $namespace = $this->getNsText();
1990 if ( $namespace != '' ) {
1991 # Can this actually happen? Interwikis shouldn't be parsed.
1992 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1995 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1996 $url = wfAppendQuery( $url, $query );
1998 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1999 if ( $query == '' ) {
2000 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2001 // Avoid PHP 7.1 warning from passing $this by reference
2003 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2005 global $wgVariantArticlePath, $wgActionPaths;
2009 if ( !empty( $wgActionPaths )
2010 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2012 $action = urldecode( $matches[2] );
2013 if ( isset( $wgActionPaths[$action] ) ) {
2014 $query = $matches[1];
2015 if ( isset( $matches[4] ) ) {
2016 $query .= $matches[4];
2018 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2019 if ( $query != '' ) {
2020 $url = wfAppendQuery( $url, $query );
2026 && $wgVariantArticlePath
2027 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2028 && $this->getPageLanguage()->equals(
2029 MediaWikiServices
::getInstance()->getContentLanguage() )
2030 && $this->getPageLanguage()->hasVariants()
2032 $variant = urldecode( $matches[1] );
2033 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2034 // Only do the variant replacement if the given variant is a valid
2035 // variant for the page's language.
2036 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2037 $url = str_replace( '$1', $dbkey, $url );
2041 if ( $url === false ) {
2042 if ( $query == '-' ) {
2045 $url = "{$wgScript}?title={$dbkey}&{$query}";
2048 // Avoid PHP 7.1 warning from passing $this by reference
2050 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2052 // @todo FIXME: This causes breakage in various places when we
2053 // actually expected a local URL and end up with dupe prefixes.
2054 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2055 $url = $wgServer . $url;
2058 // Avoid PHP 7.1 warning from passing $this by reference
2060 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2065 * Get a URL that's the simplest URL that will be valid to link, locally,
2066 * to the current Title. It includes the fragment, but does not include
2067 * the server unless action=render is used (or the link is external). If
2068 * there's a fragment but the prefixed text is empty, we just return a link
2071 * The result obviously should not be URL-escaped, but does need to be
2072 * HTML-escaped if it's being output in HTML.
2074 * @param string|string[] $query
2075 * @param bool $query2
2076 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2077 * or false (default) for no expansion
2078 * @see self::getLocalURL for the arguments.
2079 * @return string The URL
2081 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2082 if ( $this->isExternal() ||
$proto !== false ) {
2083 $ret = $this->getFullURL( $query, $query2, $proto );
2084 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2085 $ret = $this->getFragmentForURL();
2087 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2093 * Get the URL form for an internal link.
2094 * - Used in various CDN-related code, in case we have a different
2095 * internal hostname for the server from the exposed one.
2097 * This uses $wgInternalServer to qualify the path, or $wgServer
2098 * if $wgInternalServer is not set. If the server variable used is
2099 * protocol-relative, the URL will be expanded to http://
2101 * @see self::getLocalURL for the arguments.
2102 * @param string $query
2103 * @param string|bool $query2
2104 * @return string The URL
2106 public function getInternalURL( $query = '', $query2 = false ) {
2107 global $wgInternalServer, $wgServer;
2108 $query = self
::fixUrlQueryArgs( $query, $query2 );
2109 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2110 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2111 // Avoid PHP 7.1 warning from passing $this by reference
2113 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2118 * Get the URL for a canonical link, for use in things like IRC and
2119 * e-mail notifications. Uses $wgCanonicalServer and the
2120 * GetCanonicalURL hook.
2122 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2124 * @see self::getLocalURL for the arguments.
2125 * @param string $query
2126 * @param string|bool $query2
2127 * @return string The URL
2130 public function getCanonicalURL( $query = '', $query2 = false ) {
2131 $query = self
::fixUrlQueryArgs( $query, $query2 );
2132 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2133 // Avoid PHP 7.1 warning from passing $this by reference
2135 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2140 * Get the edit URL for this Title
2142 * @return string The URL, or a null string if this is an interwiki link
2144 public function getEditURL() {
2145 if ( $this->isExternal() ) {
2148 $s = $this->getLocalURL( 'action=edit' );
2154 * Can $user perform $action on this page?
2155 * This skips potentially expensive cascading permission checks
2156 * as well as avoids expensive error formatting
2158 * Suitable for use for nonessential UI controls in common cases, but
2159 * _not_ for functional access control.
2161 * May provide false positives, but should never provide a false negative.
2163 * @param string $action Action that permission needs to be checked for
2164 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2167 public function quickUserCan( $action, $user = null ) {
2168 return $this->userCan( $action, $user, false );
2172 * Can $user perform $action on this page?
2174 * @param string $action Action that permission needs to be checked for
2175 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2177 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2180 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2181 if ( !$user instanceof User
) {
2186 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2190 * Can $user perform $action on this page?
2192 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2194 * @param string $action Action that permission needs to be checked for
2195 * @param User $user User to check
2196 * @param string $rigor One of (quick,full,secure)
2197 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2198 * - full : does cheap and expensive checks possibly from a replica DB
2199 * - secure : does cheap and expensive checks, using the master as needed
2200 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2201 * whose corresponding errors may be ignored.
2202 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2204 public function getUserPermissionsErrors(
2205 $action, $user, $rigor = 'secure', $ignoreErrors = []
2207 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2209 // Remove the errors being ignored.
2210 foreach ( $errors as $index => $error ) {
2211 $errKey = is_array( $error ) ?
$error[0] : $error;
2213 if ( in_array( $errKey, $ignoreErrors ) ) {
2214 unset( $errors[$index] );
2216 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2217 unset( $errors[$index] );
2225 * Permissions checks that fail most often, and which are easiest to test.
2227 * @param string $action The action to check
2228 * @param User $user User to check
2229 * @param array $errors List of current errors
2230 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2231 * @param bool $short Short circuit on first error
2233 * @return array List of errors
2235 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2236 if ( !Hooks
::run( 'TitleQuickPermissions',
2237 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2242 if ( $action == 'create' ) {
2244 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2245 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2247 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2249 } elseif ( $action == 'move' ) {
2250 if ( !$user->isAllowed( 'move-rootuserpages' )
2251 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2252 // Show user page-specific message only if the user can move other pages
2253 $errors[] = [ 'cant-move-user-page' ];
2256 // Check if user is allowed to move files if it's a file
2257 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2258 $errors[] = [ 'movenotallowedfile' ];
2261 // Check if user is allowed to move category pages if it's a category page
2262 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2263 $errors[] = [ 'cant-move-category-page' ];
2266 if ( !$user->isAllowed( 'move' ) ) {
2267 // User can't move anything
2268 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2269 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2270 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2271 // custom message if logged-in users without any special rights can move
2272 $errors[] = [ 'movenologintext' ];
2274 $errors[] = [ 'movenotallowed' ];
2277 } elseif ( $action == 'move-target' ) {
2278 if ( !$user->isAllowed( 'move' ) ) {
2279 // User can't move anything
2280 $errors[] = [ 'movenotallowed' ];
2281 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2282 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2283 // Show user page-specific message only if the user can move other pages
2284 $errors[] = [ 'cant-move-to-user-page' ];
2285 } elseif ( !$user->isAllowed( 'move-categorypages' )
2286 && $this->mNamespace
== NS_CATEGORY
) {
2287 // Show category page-specific message only if the user can move other pages
2288 $errors[] = [ 'cant-move-to-category-page' ];
2290 } elseif ( !$user->isAllowed( $action ) ) {
2291 $errors[] = $this->missingPermissionError( $action, $short );
2298 * Add the resulting error code to the errors array
2300 * @param array $errors List of current errors
2301 * @param array $result Result of errors
2303 * @return array List of errors
2305 private function resultToError( $errors, $result ) {
2306 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2307 // A single array representing an error
2308 $errors[] = $result;
2309 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2310 // A nested array representing multiple errors
2311 $errors = array_merge( $errors, $result );
2312 } elseif ( $result !== '' && is_string( $result ) ) {
2313 // A string representing a message-id
2314 $errors[] = [ $result ];
2315 } elseif ( $result instanceof MessageSpecifier
) {
2316 // A message specifier representing an error
2317 $errors[] = [ $result ];
2318 } elseif ( $result === false ) {
2319 // a generic "We don't want them to do that"
2320 $errors[] = [ 'badaccess-group0' ];
2326 * Check various permission hooks
2328 * @param string $action The action to check
2329 * @param User $user User to check
2330 * @param array $errors List of current errors
2331 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2332 * @param bool $short Short circuit on first error
2334 * @return array List of errors
2336 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2337 // Use getUserPermissionsErrors instead
2339 // Avoid PHP 7.1 warning from passing $this by reference
2341 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2342 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2344 // Check getUserPermissionsErrors hook
2345 // Avoid PHP 7.1 warning from passing $this by reference
2347 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2348 $errors = $this->resultToError( $errors, $result );
2350 // Check getUserPermissionsErrorsExpensive hook
2353 && !( $short && count( $errors ) > 0 )
2354 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2356 $errors = $this->resultToError( $errors, $result );
2363 * Check permissions on special pages & namespaces
2365 * @param string $action The action to check
2366 * @param User $user User to check
2367 * @param array $errors List of current errors
2368 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2369 * @param bool $short Short circuit on first error
2371 * @return array List of errors
2373 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2374 # Only 'createaccount' can be performed on special pages,
2375 # which don't actually exist in the DB.
2376 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2377 $errors[] = [ 'ns-specialprotected' ];
2380 # Check $wgNamespaceProtection for restricted namespaces
2381 if ( $this->isNamespaceProtected( $user ) ) {
2382 $ns = $this->mNamespace
== NS_MAIN ?
2383 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2384 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2385 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2392 * Check sitewide CSS/JSON/JS permissions
2394 * @param string $action The action to check
2395 * @param User $user User to check
2396 * @param array $errors List of current errors
2397 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2398 * @param bool $short Short circuit on first error
2400 * @return array List of errors
2402 private function checkSiteConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2403 if ( $action != 'patrol' ) {
2405 // Sitewide CSS/JSON/JS changes, like all NS_MEDIAWIKI changes, also require the
2406 // editinterface right. That's implemented as a restriction so no check needed here.
2407 if ( $this->isSiteCssConfigPage() && !$user->isAllowed( 'editsitecss' ) ) {
2408 $error = [ 'sitecssprotected', $action ];
2409 } elseif ( $this->isSiteJsonConfigPage() && !$user->isAllowed( 'editsitejson' ) ) {
2410 $error = [ 'sitejsonprotected', $action ];
2411 } elseif ( $this->isSiteJsConfigPage() && !$user->isAllowed( 'editsitejs' ) ) {
2412 $error = [ 'sitejsprotected', $action ];
2413 } elseif ( $this->isRawHtmlMessage() ) {
2414 // Raw HTML can be used to deploy CSS or JS so require rights for both.
2415 if ( !$user->isAllowed( 'editsitejs' ) ) {
2416 $error = [ 'sitejsprotected', $action ];
2417 } elseif ( !$user->isAllowed( 'editsitecss' ) ) {
2418 $error = [ 'sitecssprotected', $action ];
2423 if ( $user->isAllowed( 'editinterface' ) ) {
2424 // Most users / site admins will probably find out about the new, more restrictive
2425 // permissions by failing to edit something. Give them more info.
2426 // TODO remove this a few release cycles after 1.32
2427 $error = [ 'interfaceadmin-info', wfMessage( $error[0], $error[1] ) ];
2437 * Check CSS/JSON/JS sub-page permissions
2439 * @param string $action The action to check
2440 * @param User $user User to check
2441 * @param array $errors List of current errors
2442 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2443 * @param bool $short Short circuit on first error
2445 * @return array List of errors
2447 private function checkUserConfigPermissions( $action, $user, $errors, $rigor, $short ) {
2448 # Protect css/json/js subpages of user pages
2449 # XXX: this might be better using restrictions
2451 if ( $action === 'patrol' ) {
2455 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2456 // Users need editmyuser* to edit their own CSS/JSON/JS subpages.
2458 $this->isUserCssConfigPage()
2459 && !$user->isAllowedAny( 'editmyusercss', 'editusercss' )
2461 $errors[] = [ 'mycustomcssprotected', $action ];
2463 $this->isUserJsonConfigPage()
2464 && !$user->isAllowedAny( 'editmyuserjson', 'edituserjson' )
2466 $errors[] = [ 'mycustomjsonprotected', $action ];
2468 $this->isUserJsConfigPage()
2469 && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' )
2471 $errors[] = [ 'mycustomjsprotected', $action ];
2474 // Users need editmyuser* to edit their own CSS/JSON/JS subpages, except for
2475 // deletion/suppression which cannot be used for attacks and we want to avoid the
2476 // situation where an unprivileged user can post abusive content on their subpages
2477 // and only very highly privileged users could remove it.
2478 if ( !in_array( $action, [ 'delete', 'deleterevision', 'suppressrevision' ], true ) ) {
2480 $this->isUserCssConfigPage()
2481 && !$user->isAllowed( 'editusercss' )
2483 $errors[] = [ 'customcssprotected', $action ];
2485 $this->isUserJsonConfigPage()
2486 && !$user->isAllowed( 'edituserjson' )
2488 $errors[] = [ 'customjsonprotected', $action ];
2490 $this->isUserJsConfigPage()
2491 && !$user->isAllowed( 'edituserjs' )
2493 $errors[] = [ 'customjsprotected', $action ];
2502 * Check against page_restrictions table requirements on this
2503 * page. The user must possess all required rights for this
2506 * @param string $action The action to check
2507 * @param User $user User to check
2508 * @param array $errors List of current errors
2509 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2510 * @param bool $short Short circuit on first error
2512 * @return array List of errors
2514 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2515 foreach ( $this->getRestrictions( $action ) as $right ) {
2516 // Backwards compatibility, rewrite sysop -> editprotected
2517 if ( $right == 'sysop' ) {
2518 $right = 'editprotected';
2520 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2521 if ( $right == 'autoconfirmed' ) {
2522 $right = 'editsemiprotected';
2524 if ( $right == '' ) {
2527 if ( !$user->isAllowed( $right ) ) {
2528 $errors[] = [ 'protectedpagetext', $right, $action ];
2529 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2530 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2538 * Check restrictions on cascading pages.
2540 * @param string $action The action to check
2541 * @param User $user User to check
2542 * @param array $errors List of current errors
2543 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2544 * @param bool $short Short circuit on first error
2546 * @return array List of errors
2548 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2549 if ( $rigor !== 'quick' && !$this->isUserConfigPage() ) {
2550 # We /could/ use the protection level on the source page, but it's
2551 # fairly ugly as we have to establish a precedence hierarchy for pages
2552 # included by multiple cascade-protected pages. So just restrict
2553 # it to people with 'protect' permission, as they could remove the
2554 # protection anyway.
2555 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2556 # Cascading protection depends on more than this page...
2557 # Several cascading protected pages may include this page...
2558 # Check each cascading level
2559 # This is only for protection restrictions, not for all actions
2560 if ( isset( $restrictions[$action] ) ) {
2561 foreach ( $restrictions[$action] as $right ) {
2562 // Backwards compatibility, rewrite sysop -> editprotected
2563 if ( $right == 'sysop' ) {
2564 $right = 'editprotected';
2566 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2567 if ( $right == 'autoconfirmed' ) {
2568 $right = 'editsemiprotected';
2570 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2572 foreach ( $cascadingSources as $page ) {
2573 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2575 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2585 * Check action permissions not already checked in checkQuickPermissions
2587 * @param string $action The action to check
2588 * @param User $user User to check
2589 * @param array $errors List of current errors
2590 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2591 * @param bool $short Short circuit on first error
2593 * @return array List of errors
2595 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2596 global $wgDeleteRevisionsLimit, $wgLang;
2598 if ( $action == 'protect' ) {
2599 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2600 // If they can't edit, they shouldn't protect.
2601 $errors[] = [ 'protect-cantedit' ];
2603 } elseif ( $action == 'create' ) {
2604 $title_protection = $this->getTitleProtection();
2605 if ( $title_protection ) {
2606 if ( $title_protection['permission'] == ''
2607 ||
!$user->isAllowed( $title_protection['permission'] )
2611 User
::whoIs( $title_protection['user'] ),
2612 $title_protection['reason']
2616 } elseif ( $action == 'move' ) {
2617 // Check for immobile pages
2618 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2619 // Specific message for this case
2620 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2621 } elseif ( !$this->isMovable() ) {
2622 // Less specific message for rarer cases
2623 $errors[] = [ 'immobile-source-page' ];
2625 } elseif ( $action == 'move-target' ) {
2626 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2627 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2628 } elseif ( !$this->isMovable() ) {
2629 $errors[] = [ 'immobile-target-page' ];
2631 } elseif ( $action == 'delete' ) {
2632 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2633 if ( !$tempErrors ) {
2634 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2635 $user, $tempErrors, $rigor, true );
2637 if ( $tempErrors ) {
2638 // If protection keeps them from editing, they shouldn't be able to delete.
2639 $errors[] = [ 'deleteprotected' ];
2641 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2642 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2644 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2646 } elseif ( $action === 'undelete' ) {
2647 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2648 // Undeleting implies editing
2649 $errors[] = [ 'undelete-cantedit' ];
2651 if ( !$this->exists()
2652 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2654 // Undeleting where nothing currently exists implies creating
2655 $errors[] = [ 'undelete-cantcreate' ];
2662 * Check that the user isn't blocked from editing.
2664 * @param string $action The action to check
2665 * @param User $user User to check
2666 * @param array $errors List of current errors
2667 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2668 * @param bool $short Short circuit on first error
2670 * @return array List of errors
2672 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2673 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2674 // Account creation blocks handled at userlogin.
2675 // Unblocking handled in SpecialUnblock
2676 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2680 // Optimize for a very common case
2681 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2685 if ( $wgEmailConfirmToEdit
2686 && !$user->isEmailConfirmed()
2687 && $action === 'edit'
2689 $errors[] = [ 'confirmedittext' ];
2692 $useReplica = ( $rigor !== 'secure' );
2693 if ( ( $action == 'edit' ||
$action == 'create' )
2694 && !$user->isBlockedFrom( $this, $useReplica )
2696 // Don't block the user from editing their own talk page unless they've been
2697 // explicitly blocked from that too.
2698 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2699 // @todo FIXME: Pass the relevant context into this function.
2700 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2707 * Check that the user is allowed to read this page.
2709 * @param string $action The action to check
2710 * @param User $user User to check
2711 * @param array $errors List of current errors
2712 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2713 * @param bool $short Short circuit on first error
2715 * @return array List of errors
2717 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2718 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2720 $whitelisted = false;
2721 if ( User
::isEveryoneAllowed( 'read' ) ) {
2722 # Shortcut for public wikis, allows skipping quite a bit of code
2723 $whitelisted = true;
2724 } elseif ( $user->isAllowed( 'read' ) ) {
2725 # If the user is allowed to read pages, he is allowed to read all pages
2726 $whitelisted = true;
2727 } elseif ( $this->isSpecial( 'Userlogin' )
2728 ||
$this->isSpecial( 'PasswordReset' )
2729 ||
$this->isSpecial( 'Userlogout' )
2731 # Always grant access to the login page.
2732 # Even anons need to be able to log in.
2733 $whitelisted = true;
2734 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2735 # Time to check the whitelist
2736 # Only do these checks is there's something to check against
2737 $name = $this->getPrefixedText();
2738 $dbName = $this->getPrefixedDBkey();
2740 // Check for explicit whitelisting with and without underscores
2741 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2742 $whitelisted = true;
2743 } elseif ( $this->mNamespace
== NS_MAIN
) {
2744 # Old settings might have the title prefixed with
2745 # a colon for main-namespace pages
2746 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2747 $whitelisted = true;
2749 } elseif ( $this->isSpecialPage() ) {
2750 # If it's a special page, ditch the subpage bit and check again
2751 $name = $this->mDbkeyform
;
2752 list( $name, /* $subpage */ ) =
2753 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
2754 resolveAlias( $name );
2756 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2757 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2758 $whitelisted = true;
2764 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2765 $name = $this->getPrefixedText();
2766 // Check for regex whitelisting
2767 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2768 if ( preg_match( $listItem, $name ) ) {
2769 $whitelisted = true;
2775 if ( !$whitelisted ) {
2776 # If the title is not whitelisted, give extensions a chance to do so...
2777 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2778 if ( !$whitelisted ) {
2779 $errors[] = $this->missingPermissionError( $action, $short );
2787 * Get a description array when the user doesn't have the right to perform
2788 * $action (i.e. when User::isAllowed() returns false)
2790 * @param string $action The action to check
2791 * @param bool $short Short circuit on first error
2792 * @return array Array containing an error message key and any parameters
2794 private function missingPermissionError( $action, $short ) {
2795 // We avoid expensive display logic for quickUserCan's and such
2797 return [ 'badaccess-group0' ];
2800 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2804 * Can $user perform $action on this page? This is an internal function,
2805 * with multiple levels of checks depending on performance needs; see $rigor below.
2806 * It does not check wfReadOnly().
2808 * @param string $action Action that permission needs to be checked for
2809 * @param User $user User to check
2810 * @param string $rigor One of (quick,full,secure)
2811 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2812 * - full : does cheap and expensive checks possibly from a replica DB
2813 * - secure : does cheap and expensive checks, using the master as needed
2814 * @param bool $short Set this to true to stop after the first permission error.
2815 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2817 protected function getUserPermissionsErrorsInternal(
2818 $action, $user, $rigor = 'secure', $short = false
2820 if ( $rigor === true ) {
2821 $rigor = 'secure'; // b/c
2822 } elseif ( $rigor === false ) {
2823 $rigor = 'quick'; // b/c
2824 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2825 throw new Exception( "Invalid rigor parameter '$rigor'." );
2828 # Read has special handling
2829 if ( $action == 'read' ) {
2831 'checkPermissionHooks',
2832 'checkReadPermissions',
2833 'checkUserBlock', // for wgBlockDisablesLogin
2835 # Don't call checkSpecialsAndNSPermissions, checkSiteConfigPermissions
2836 # or checkUserConfigPermissions here as it will lead to duplicate
2837 # error messages. This is okay to do since anywhere that checks for
2838 # create will also check for edit, and those checks are called for edit.
2839 } elseif ( $action == 'create' ) {
2841 'checkQuickPermissions',
2842 'checkPermissionHooks',
2843 'checkPageRestrictions',
2844 'checkCascadingSourcesRestrictions',
2845 'checkActionPermissions',
2850 'checkQuickPermissions',
2851 'checkPermissionHooks',
2852 'checkSpecialsAndNSPermissions',
2853 'checkSiteConfigPermissions',
2854 'checkUserConfigPermissions',
2855 'checkPageRestrictions',
2856 'checkCascadingSourcesRestrictions',
2857 'checkActionPermissions',
2863 while ( count( $checks ) > 0 &&
2864 !( $short && count( $errors ) > 0 ) ) {
2865 $method = array_shift( $checks );
2866 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2873 * Get a filtered list of all restriction types supported by this wiki.
2874 * @param bool $exists True to get all restriction types that apply to
2875 * titles that do exist, False for all restriction types that apply to
2876 * titles that do not exist
2879 public static function getFilteredRestrictionTypes( $exists = true ) {
2880 global $wgRestrictionTypes;
2881 $types = $wgRestrictionTypes;
2883 # Remove the create restriction for existing titles
2884 $types = array_diff( $types, [ 'create' ] );
2886 # Only the create and upload restrictions apply to non-existing titles
2887 $types = array_intersect( $types, [ 'create', 'upload' ] );
2893 * Returns restriction types for the current Title
2895 * @return array Applicable restriction types
2897 public function getRestrictionTypes() {
2898 if ( $this->isSpecialPage() ) {
2902 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2904 if ( $this->mNamespace
!= NS_FILE
) {
2905 # Remove the upload restriction for non-file titles
2906 $types = array_diff( $types, [ 'upload' ] );
2909 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2911 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2912 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2918 * Is this title subject to title protection?
2919 * Title protection is the one applied against creation of such title.
2921 * @return array|bool An associative array representing any existent title
2922 * protection, or false if there's none.
2924 public function getTitleProtection() {
2925 $protection = $this->getTitleProtectionInternal();
2926 if ( $protection ) {
2927 if ( $protection['permission'] == 'sysop' ) {
2928 $protection['permission'] = 'editprotected'; // B/C
2930 if ( $protection['permission'] == 'autoconfirmed' ) {
2931 $protection['permission'] = 'editsemiprotected'; // B/C
2938 * Fetch title protection settings
2940 * To work correctly, $this->loadRestrictions() needs to have access to the
2941 * actual protections in the database without munging 'sysop' =>
2942 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2943 * callers probably want $this->getTitleProtection() instead.
2945 * @return array|bool
2947 protected function getTitleProtectionInternal() {
2948 // Can't protect pages in special namespaces
2949 if ( $this->mNamespace
< 0 ) {
2953 // Can't protect pages that exist.
2954 if ( $this->exists() ) {
2958 if ( $this->mTitleProtection
=== null ) {
2959 $dbr = wfGetDB( DB_REPLICA
);
2960 $commentStore = CommentStore
::getStore();
2961 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2962 $res = $dbr->select(
2963 [ 'protected_titles' ] +
$commentQuery['tables'],
2965 'user' => 'pt_user',
2966 'expiry' => 'pt_expiry',
2967 'permission' => 'pt_create_perm'
2968 ] +
$commentQuery['fields'],
2969 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2972 $commentQuery['joins']
2975 // fetchRow returns false if there are no rows.
2976 $row = $dbr->fetchRow( $res );
2978 $this->mTitleProtection
= [
2979 'user' => $row['user'],
2980 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2981 'permission' => $row['permission'],
2982 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2985 $this->mTitleProtection
= false;
2988 return $this->mTitleProtection
;
2992 * Remove any title protection due to page existing
2994 public function deleteTitleProtection() {
2995 $dbw = wfGetDB( DB_MASTER
);
2999 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
3002 $this->mTitleProtection
= false;
3006 * Is this page "semi-protected" - the *only* protection levels are listed
3007 * in $wgSemiprotectedRestrictionLevels?
3009 * @param string $action Action to check (default: edit)
3012 public function isSemiProtected( $action = 'edit' ) {
3013 global $wgSemiprotectedRestrictionLevels;
3015 $restrictions = $this->getRestrictions( $action );
3016 $semi = $wgSemiprotectedRestrictionLevels;
3017 if ( !$restrictions ||
!$semi ) {
3018 // Not protected, or all protection is full protection
3022 // Remap autoconfirmed to editsemiprotected for BC
3023 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
3024 $semi[$key] = 'editsemiprotected';
3026 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
3027 $restrictions[$key] = 'editsemiprotected';
3030 return !array_diff( $restrictions, $semi );
3034 * Does the title correspond to a protected article?
3036 * @param string $action The action the page is protected from,
3037 * by default checks all actions.
3040 public function isProtected( $action = '' ) {
3041 global $wgRestrictionLevels;
3043 $restrictionTypes = $this->getRestrictionTypes();
3045 # Special pages have inherent protection
3046 if ( $this->isSpecialPage() ) {
3050 # Check regular protection levels
3051 foreach ( $restrictionTypes as $type ) {
3052 if ( $action == $type ||
$action == '' ) {
3053 $r = $this->getRestrictions( $type );
3054 foreach ( $wgRestrictionLevels as $level ) {
3055 if ( in_array( $level, $r ) && $level != '' ) {
3066 * Determines if $user is unable to edit this page because it has been protected
3067 * by $wgNamespaceProtection.
3069 * @param User $user User object to check permissions
3072 public function isNamespaceProtected( User
$user ) {
3073 global $wgNamespaceProtection;
3075 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
3076 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
3077 if ( $right != '' && !$user->isAllowed( $right ) ) {
3086 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
3088 * @return bool If the page is subject to cascading restrictions.
3090 public function isCascadeProtected() {
3091 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
3092 return ( $sources > 0 );
3096 * Determines whether cascading protection sources have already been loaded from
3099 * @param bool $getPages True to check if the pages are loaded, or false to check
3100 * if the status is loaded.
3101 * @return bool Whether or not the specified information has been loaded
3104 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
3105 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
3109 * Cascading protection: Get the source of any cascading restrictions on this page.
3111 * @param bool $getPages Whether or not to retrieve the actual pages
3112 * that the restrictions have come from and the actual restrictions
3114 * @return array Two elements: First is an array of Title objects of the
3115 * pages from which cascading restrictions have come, false for
3116 * none, or true if such restrictions exist but $getPages was not
3117 * set. Second is an array like that returned by
3118 * Title::getAllRestrictions(), or an empty array if $getPages is
3121 public function getCascadeProtectionSources( $getPages = true ) {
3122 $pagerestrictions = [];
3124 if ( $this->mCascadeSources
!== null && $getPages ) {
3125 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
3126 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
3127 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
3130 $dbr = wfGetDB( DB_REPLICA
);
3132 if ( $this->mNamespace
== NS_FILE
) {
3133 $tables = [ 'imagelinks', 'page_restrictions' ];
3135 'il_to' => $this->mDbkeyform
,
3140 $tables = [ 'templatelinks', 'page_restrictions' ];
3142 'tl_namespace' => $this->mNamespace
,
3143 'tl_title' => $this->mDbkeyform
,
3150 $cols = [ 'pr_page', 'page_namespace', 'page_title',
3151 'pr_expiry', 'pr_type', 'pr_level' ];
3152 $where_clauses[] = 'page_id=pr_page';
3155 $cols = [ 'pr_expiry' ];
3158 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
3160 $sources = $getPages ?
[] : false;
3161 $now = wfTimestampNow();
3163 foreach ( $res as $row ) {
3164 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3165 if ( $expiry > $now ) {
3167 $page_id = $row->pr_page
;
3168 $page_ns = $row->page_namespace
;
3169 $page_title = $row->page_title
;
3170 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
3171 # Add groups needed for each restriction type if its not already there
3172 # Make sure this restriction type still exists
3174 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
3175 $pagerestrictions[$row->pr_type
] = [];
3179 isset( $pagerestrictions[$row->pr_type
] )
3180 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
3182 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
3191 $this->mCascadeSources
= $sources;
3192 $this->mCascadingRestrictions
= $pagerestrictions;
3194 $this->mHasCascadingRestrictions
= $sources;
3197 return [ $sources, $pagerestrictions ];
3201 * Accessor for mRestrictionsLoaded
3203 * @return bool Whether or not the page's restrictions have already been
3204 * loaded from the database
3207 public function areRestrictionsLoaded() {
3208 return $this->mRestrictionsLoaded
;
3212 * Accessor/initialisation for mRestrictions
3214 * @param string $action Action that permission needs to be checked for
3215 * @return array Restriction levels needed to take the action. All levels are
3216 * required. Note that restriction levels are normally user rights, but 'sysop'
3217 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
3218 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
3220 public function getRestrictions( $action ) {
3221 if ( !$this->mRestrictionsLoaded
) {
3222 $this->loadRestrictions();
3224 return $this->mRestrictions
[$action] ??
[];
3228 * Accessor/initialisation for mRestrictions
3230 * @return array Keys are actions, values are arrays as returned by
3231 * Title::getRestrictions()
3234 public function getAllRestrictions() {
3235 if ( !$this->mRestrictionsLoaded
) {
3236 $this->loadRestrictions();
3238 return $this->mRestrictions
;
3242 * Get the expiry time for the restriction against a given action
3244 * @param string $action
3245 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3246 * or not protected at all, or false if the action is not recognised.
3248 public function getRestrictionExpiry( $action ) {
3249 if ( !$this->mRestrictionsLoaded
) {
3250 $this->loadRestrictions();
3252 return $this->mRestrictionsExpiry
[$action] ??
false;
3256 * Returns cascading restrictions for the current article
3260 function areRestrictionsCascading() {
3261 if ( !$this->mRestrictionsLoaded
) {
3262 $this->loadRestrictions();
3265 return $this->mCascadeRestriction
;
3269 * Compiles list of active page restrictions from both page table (pre 1.10)
3270 * and page_restrictions table for this existing page.
3271 * Public for usage by LiquidThreads.
3273 * @param array $rows Array of db result objects
3274 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3275 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3276 * Edit and move sections are separated by a colon
3277 * Example: "edit=autoconfirmed,sysop:move=sysop"
3279 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3280 $dbr = wfGetDB( DB_REPLICA
);
3282 $restrictionTypes = $this->getRestrictionTypes();
3284 foreach ( $restrictionTypes as $type ) {
3285 $this->mRestrictions
[$type] = [];
3286 $this->mRestrictionsExpiry
[$type] = 'infinity';
3289 $this->mCascadeRestriction
= false;
3291 # Backwards-compatibility: also load the restrictions from the page record (old format).
3292 if ( $oldFashionedRestrictions !== null ) {
3293 $this->mOldRestrictions
= $oldFashionedRestrictions;
3296 if ( $this->mOldRestrictions
=== false ) {
3297 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3298 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3301 if ( $this->mOldRestrictions
!= '' ) {
3302 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3303 $temp = explode( '=', trim( $restrict ) );
3304 if ( count( $temp ) == 1 ) {
3305 // old old format should be treated as edit/move restriction
3306 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3307 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3309 $restriction = trim( $temp[1] );
3310 if ( $restriction != '' ) { // some old entries are empty
3311 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3317 if ( count( $rows ) ) {
3318 # Current system - load second to make them override.
3319 $now = wfTimestampNow();
3321 # Cycle through all the restrictions.
3322 foreach ( $rows as $row ) {
3323 // Don't take care of restrictions types that aren't allowed
3324 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3328 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3330 // Only apply the restrictions if they haven't expired!
3331 if ( !$expiry ||
$expiry > $now ) {
3332 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3333 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3335 $this->mCascadeRestriction |
= $row->pr_cascade
;
3340 $this->mRestrictionsLoaded
= true;
3344 * Load restrictions from the page_restrictions table
3346 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
3347 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3348 * Edit and move sections are separated by a colon
3349 * Example: "edit=autoconfirmed,sysop:move=sysop"
3351 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3352 if ( $this->mRestrictionsLoaded
) {
3356 $id = $this->getArticleID();
3358 $cache = ObjectCache
::getMainWANInstance();
3359 $fname = __METHOD__
;
3360 $rows = $cache->getWithSetCallback(
3361 // Page protections always leave a new null revision
3362 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3364 function ( $curValue, &$ttl, array &$setOpts ) use ( $fname ) {
3365 $dbr = wfGetDB( DB_REPLICA
);
3367 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3369 return iterator_to_array(
3371 'page_restrictions',
3372 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3373 [ 'pr_page' => $this->getArticleID() ],
3380 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3382 $title_protection = $this->getTitleProtectionInternal();
3384 if ( $title_protection ) {
3385 $now = wfTimestampNow();
3386 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3388 if ( !$expiry ||
$expiry > $now ) {
3389 // Apply the restrictions
3390 $this->mRestrictionsExpiry
['create'] = $expiry;
3391 $this->mRestrictions
['create'] =
3392 explode( ',', trim( $title_protection['permission'] ) );
3393 } else { // Get rid of the old restrictions
3394 $this->mTitleProtection
= false;
3397 $this->mRestrictionsExpiry
['create'] = 'infinity';
3399 $this->mRestrictionsLoaded
= true;
3404 * Flush the protection cache in this object and force reload from the database.
3405 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3407 public function flushRestrictions() {
3408 $this->mRestrictionsLoaded
= false;
3409 $this->mTitleProtection
= null;
3413 * Purge expired restrictions from the page_restrictions table
3415 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3417 static function purgeExpiredRestrictions() {
3418 if ( wfReadOnly() ) {
3422 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3423 wfGetDB( DB_MASTER
),
3425 function ( IDatabase
$dbw, $fname ) {
3426 $config = MediaWikiServices
::getInstance()->getMainConfig();
3427 $ids = $dbw->selectFieldValues(
3428 'page_restrictions',
3430 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3432 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3435 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3440 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3441 wfGetDB( DB_MASTER
),
3443 function ( IDatabase
$dbw, $fname ) {
3446 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3454 * Does this have subpages? (Warning, usually requires an extra DB query.)
3458 public function hasSubpages() {
3459 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3464 # We dynamically add a member variable for the purpose of this method
3465 # alone to cache the result. There's no point in having it hanging
3466 # around uninitialized in every Title object; therefore we only add it
3467 # if needed and don't declare it statically.
3468 if ( $this->mHasSubpages
=== null ) {
3469 $this->mHasSubpages
= false;
3470 $subpages = $this->getSubpages( 1 );
3471 if ( $subpages instanceof TitleArray
) {
3472 $this->mHasSubpages
= (bool)$subpages->count();
3476 return $this->mHasSubpages
;
3480 * Get all subpages of this page.
3482 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3483 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3484 * doesn't allow subpages
3486 public function getSubpages( $limit = -1 ) {
3487 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3491 $dbr = wfGetDB( DB_REPLICA
);
3492 $conds['page_namespace'] = $this->mNamespace
;
3493 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3495 if ( $limit > -1 ) {
3496 $options['LIMIT'] = $limit;
3498 return TitleArray
::newFromResult(
3499 $dbr->select( 'page',
3500 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3509 * Is there a version of this page in the deletion archive?
3511 * @return int The number of archived revisions
3513 public function isDeleted() {
3514 if ( $this->mNamespace
< 0 ) {
3517 $dbr = wfGetDB( DB_REPLICA
);
3519 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3520 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3523 if ( $this->mNamespace
== NS_FILE
) {
3524 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3525 [ 'fa_name' => $this->mDbkeyform
],
3534 * Is there a version of this page in the deletion archive?
3538 public function isDeletedQuick() {
3539 if ( $this->mNamespace
< 0 ) {
3542 $dbr = wfGetDB( DB_REPLICA
);
3543 $deleted = (bool)$dbr->selectField( 'archive', '1',
3544 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3547 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3548 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3549 [ 'fa_name' => $this->mDbkeyform
],
3557 * Get the article ID for this Title from the link cache,
3558 * adding it if necessary
3560 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3562 * @return int The ID
3564 public function getArticleID( $flags = 0 ) {
3565 if ( $this->mNamespace
< 0 ) {
3566 $this->mArticleID
= 0;
3567 return $this->mArticleID
;
3569 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3570 if ( $flags & self
::GAID_FOR_UPDATE
) {
3571 $oldUpdate = $linkCache->forUpdate( true );
3572 $linkCache->clearLink( $this );
3573 $this->mArticleID
= $linkCache->addLinkObj( $this );
3574 $linkCache->forUpdate( $oldUpdate );
3576 if ( $this->mArticleID
== -1 ) {
3577 $this->mArticleID
= $linkCache->addLinkObj( $this );
3580 return $this->mArticleID
;
3584 * Is this an article that is a redirect page?
3585 * Uses link cache, adding it if necessary
3587 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3590 public function isRedirect( $flags = 0 ) {
3591 if ( !is_null( $this->mRedirect
) ) {
3592 return $this->mRedirect
;
3594 if ( !$this->getArticleID( $flags ) ) {
3595 $this->mRedirect
= false;
3596 return $this->mRedirect
;
3599 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3600 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3601 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3602 if ( $cached === null ) {
3603 # Trust LinkCache's state over our own
3604 # LinkCache is telling us that the page doesn't exist, despite there being cached
3605 # data relating to an existing page in $this->mArticleID. Updaters should clear
3606 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3607 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3608 # LinkCache to refresh its data from the master.
3609 $this->mRedirect
= false;
3610 return $this->mRedirect
;
3613 $this->mRedirect
= (bool)$cached;
3615 return $this->mRedirect
;
3619 * What is the length of this page?
3620 * Uses link cache, adding it if necessary
3622 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3625 public function getLength( $flags = 0 ) {
3626 if ( $this->mLength
!= -1 ) {
3627 return $this->mLength
;
3629 if ( !$this->getArticleID( $flags ) ) {
3631 return $this->mLength
;
3633 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3634 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3635 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3636 if ( $cached === null ) {
3637 # Trust LinkCache's state over our own, as for isRedirect()
3639 return $this->mLength
;
3642 $this->mLength
= intval( $cached );
3644 return $this->mLength
;
3648 * What is the page_latest field for this page?
3650 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3651 * @return int Int or 0 if the page doesn't exist
3653 public function getLatestRevID( $flags = 0 ) {
3654 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3655 return intval( $this->mLatestID
);
3657 if ( !$this->getArticleID( $flags ) ) {
3658 $this->mLatestID
= 0;
3659 return $this->mLatestID
;
3661 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3662 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3663 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3664 if ( $cached === null ) {
3665 # Trust LinkCache's state over our own, as for isRedirect()
3666 $this->mLatestID
= 0;
3667 return $this->mLatestID
;
3670 $this->mLatestID
= intval( $cached );
3672 return $this->mLatestID
;
3676 * This clears some fields in this object, and clears any associated
3677 * keys in the "bad links" section of the link cache.
3679 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3680 * loading of the new page_id. It's also called from
3681 * WikiPage::doDeleteArticleReal()
3683 * @param int $newid The new Article ID
3685 public function resetArticleID( $newid ) {
3686 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3687 $linkCache->clearLink( $this );
3689 if ( $newid === false ) {
3690 $this->mArticleID
= -1;
3692 $this->mArticleID
= intval( $newid );
3694 $this->mRestrictionsLoaded
= false;
3695 $this->mRestrictions
= [];
3696 $this->mOldRestrictions
= false;
3697 $this->mRedirect
= null;
3698 $this->mLength
= -1;
3699 $this->mLatestID
= false;
3700 $this->mContentModel
= false;
3701 $this->mEstimateRevisions
= null;
3702 $this->mPageLanguage
= false;
3703 $this->mDbPageLanguage
= false;
3704 $this->mIsBigDeletion
= null;
3707 public static function clearCaches() {
3708 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3709 $linkCache->clear();
3711 $titleCache = self
::getTitleCache();
3712 $titleCache->clear();
3716 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3718 * @param string $text Containing title to capitalize
3719 * @param int $ns Namespace index, defaults to NS_MAIN
3720 * @return string Containing capitalized title
3722 public static function capitalize( $text, $ns = NS_MAIN
) {
3723 if ( MWNamespace
::isCapitalized( $ns ) ) {
3724 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3731 * Secure and split - main initialisation function for this object
3733 * Assumes that mDbkeyform has been set, and is urldecoded
3734 * and uses underscores, but not otherwise munged. This function
3735 * removes illegal characters, splits off the interwiki and
3736 * namespace prefixes, sets the other forms, and canonicalizes
3739 * @throws MalformedTitleException On invalid titles
3740 * @return bool True on success
3742 private function secureAndSplit() {
3743 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3744 // the parsing code with Title, while avoiding massive refactoring.
3745 // @todo: get rid of secureAndSplit, refactor parsing code.
3746 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3747 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3748 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3749 // MalformedTitleException can be thrown here
3750 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3753 $this->setFragment( '#' . $parts['fragment'] );
3754 $this->mInterwiki
= $parts['interwiki'];
3755 $this->mLocalInterwiki
= $parts['local_interwiki'];
3756 $this->mNamespace
= $parts['namespace'];
3757 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3759 $this->mDbkeyform
= $parts['dbkey'];
3760 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3761 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3763 # We already know that some pages won't be in the database!
3764 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3765 $this->mArticleID
= 0;
3772 * Get an array of Title objects linking to this Title
3773 * Also stores the IDs in the link cache.
3775 * WARNING: do not use this function on arbitrary user-supplied titles!
3776 * On heavily-used templates it will max out the memory.
3778 * @param array $options May be FOR UPDATE
3779 * @param string $table Table name
3780 * @param string $prefix Fields prefix
3781 * @return Title[] Array of Title objects linking here
3783 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3784 if ( count( $options ) > 0 ) {
3785 $db = wfGetDB( DB_MASTER
);
3787 $db = wfGetDB( DB_REPLICA
);
3792 self
::getSelectFields(),
3794 "{$prefix}_from=page_id",
3795 "{$prefix}_namespace" => $this->mNamespace
,
3796 "{$prefix}_title" => $this->mDbkeyform
],
3802 if ( $res->numRows() ) {
3803 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3804 foreach ( $res as $row ) {
3805 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3807 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3808 $retVal[] = $titleObj;
3816 * Get an array of Title objects using this Title as a template
3817 * Also stores the IDs in the link cache.
3819 * WARNING: do not use this function on arbitrary user-supplied titles!
3820 * On heavily-used templates it will max out the memory.
3822 * @param array $options Query option to Database::select()
3823 * @return Title[] Array of Title the Title objects linking here
3825 public function getTemplateLinksTo( $options = [] ) {
3826 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3830 * Get an array of Title objects linked from this Title
3831 * Also stores the IDs in the link cache.
3833 * WARNING: do not use this function on arbitrary user-supplied titles!
3834 * On heavily-used templates it will max out the memory.
3836 * @param array $options Query option to Database::select()
3837 * @param string $table Table name
3838 * @param string $prefix Fields prefix
3839 * @return array Array of Title objects linking here
3841 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3842 $id = $this->getArticleID();
3844 # If the page doesn't exist; there can't be any link from this page
3849 $db = wfGetDB( DB_REPLICA
);
3851 $blNamespace = "{$prefix}_namespace";
3852 $blTitle = "{$prefix}_title";
3854 $pageQuery = WikiPage
::getQueryInfo();
3856 [ $table, 'nestpage' => $pageQuery['tables'] ],
3858 [ $blNamespace, $blTitle ],
3859 $pageQuery['fields']
3861 [ "{$prefix}_from" => $id ],
3866 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3867 ] ] +
$pageQuery['joins']
3871 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3872 foreach ( $res as $row ) {
3873 if ( $row->page_id
) {
3874 $titleObj = self
::newFromRow( $row );
3876 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3877 $linkCache->addBadLinkObj( $titleObj );
3879 $retVal[] = $titleObj;
3886 * Get an array of Title objects used on this Title as a template
3887 * Also stores the IDs in the link cache.
3889 * WARNING: do not use this function on arbitrary user-supplied titles!
3890 * On heavily-used templates it will max out the memory.
3892 * @param array $options May be FOR UPDATE
3893 * @return Title[] Array of Title the Title objects used here
3895 public function getTemplateLinksFrom( $options = [] ) {
3896 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3900 * Get an array of Title objects referring to non-existent articles linked
3903 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3904 * should use redirect table in this case).
3905 * @return Title[] Array of Title the Title objects
3907 public function getBrokenLinksFrom() {
3908 if ( $this->getArticleID() == 0 ) {
3909 # All links from article ID 0 are false positives
3913 $dbr = wfGetDB( DB_REPLICA
);
3914 $res = $dbr->select(
3915 [ 'page', 'pagelinks' ],
3916 [ 'pl_namespace', 'pl_title' ],
3918 'pl_from' => $this->getArticleID(),
3919 'page_namespace IS NULL'
3925 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3931 foreach ( $res as $row ) {
3932 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3938 * Get a list of URLs to purge from the CDN cache when this
3941 * @return string[] Array of String the URLs
3943 public function getCdnUrls() {
3945 $this->getInternalURL(),
3946 $this->getInternalURL( 'action=history' )
3949 $pageLang = $this->getPageLanguage();
3950 if ( $pageLang->hasVariants() ) {
3951 $variants = $pageLang->getVariants();
3952 foreach ( $variants as $vCode ) {
3953 $urls[] = $this->getInternalURL( $vCode );
3957 // If we are looking at a css/js user subpage, purge the action=raw.
3958 if ( $this->isUserJsConfigPage() ) {
3959 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3960 } elseif ( $this->isUserJsonConfigPage() ) {
3961 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3962 } elseif ( $this->isUserCssConfigPage() ) {
3963 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3966 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3971 * @deprecated since 1.27 use getCdnUrls()
3973 public function getSquidURLs() {
3974 return $this->getCdnUrls();
3978 * Purge all applicable CDN URLs
3980 public function purgeSquid() {
3981 DeferredUpdates
::addUpdate(
3982 new CdnCacheUpdate( $this->getCdnUrls() ),
3983 DeferredUpdates
::PRESEND
3988 * Check whether a given move operation would be valid.
3989 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3991 * @deprecated since 1.25, use MovePage's methods instead
3992 * @param Title &$nt The new title
3993 * @param bool $auth Whether to check user permissions (uses $wgUser)
3994 * @param string $reason Is the log summary of the move, used for spam checking
3995 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3997 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
4000 if ( !( $nt instanceof Title
) ) {
4001 // Normally we'd add this to $errors, but we'll get
4002 // lots of syntax errors if $nt is not an object
4003 return [ [ 'badtitletext' ] ];
4006 $mp = new MovePage( $this, $nt );
4007 $errors = $mp->isValidMove()->getErrorsArray();
4009 $errors = wfMergeErrorArrays(
4011 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
4015 return $errors ?
: true;
4019 * Check if the requested move target is a valid file move target
4020 * @todo move this to MovePage
4021 * @param Title $nt Target title
4022 * @return array List of errors
4024 protected function validateFileMoveOperation( $nt ) {
4029 $destFile = wfLocalFile( $nt );
4030 $destFile->load( File
::READ_LATEST
);
4031 if ( !$wgUser->isAllowed( 'reupload-shared' )
4032 && !$destFile->exists() && wfFindFile( $nt )
4034 $errors[] = [ 'file-exists-sharedrepo' ];
4041 * Move a title to a new location
4043 * @deprecated since 1.25, use the MovePage class instead
4044 * @param Title &$nt The new title
4045 * @param bool $auth Indicates whether $wgUser's permissions
4047 * @param string $reason The reason for the move
4048 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
4049 * Ignored if the user doesn't have the suppressredirect right.
4050 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4051 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
4053 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
4054 array $changeTags = []
4057 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
4058 if ( is_array( $err ) ) {
4059 // Auto-block user's IP if the account was "hard" blocked
4060 $wgUser->spreadAnyEditBlock();
4063 // Check suppressredirect permission
4064 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
4065 $createRedirect = true;
4068 $mp = new MovePage( $this, $nt );
4069 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
4070 if ( $status->isOK() ) {
4073 return $status->getErrorsArray();
4078 * Move this page's subpages to be subpages of $nt
4080 * @param Title $nt Move target
4081 * @param bool $auth Whether $wgUser's permissions should be checked
4082 * @param string $reason The reason for the move
4083 * @param bool $createRedirect Whether to create redirects from the old subpages to
4084 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
4085 * @param array $changeTags Applied to the entry in the move log and redirect page revision
4086 * @return array Array with old page titles as keys, and strings (new page titles) or
4087 * getUserPermissionsErrors()-like arrays (errors) as values, or a
4088 * getUserPermissionsErrors()-like error array with numeric indices if
4089 * no pages were moved
4091 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
4092 array $changeTags = []
4094 global $wgMaximumMovedPages;
4095 // Check permissions
4096 if ( !$this->userCan( 'move-subpages' ) ) {
4098 [ 'cant-move-subpages' ],
4101 // Do the source and target namespaces support subpages?
4102 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4104 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
4107 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
4109 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
4113 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
4116 foreach ( $subpages as $oldSubpage ) {
4118 if ( $count > $wgMaximumMovedPages ) {
4119 $retval[$oldSubpage->getPrefixedText()] = [
4120 [ 'movepage-max-pages', $wgMaximumMovedPages ],
4125 // We don't know whether this function was called before
4126 // or after moving the root page, so check both
4128 if ( $oldSubpage->getArticleID() == $this->getArticleID()
4129 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
4131 // When moving a page to a subpage of itself,
4132 // don't move it twice
4135 $newPageName = preg_replace(
4136 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
4137 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
4138 $oldSubpage->getDBkey() );
4139 if ( $oldSubpage->isTalkPage() ) {
4140 $newNs = $nt->getTalkPage()->getNamespace();
4142 $newNs = $nt->getSubjectPage()->getNamespace();
4144 # T16385: we need makeTitleSafe because the new page names may
4145 # be longer than 255 characters.
4146 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
4148 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
4149 if ( $success === true ) {
4150 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
4152 $retval[$oldSubpage->getPrefixedText()] = $success;
4159 * Checks if this page is just a one-rev redirect.
4160 * Adds lock, so don't use just for light purposes.
4164 public function isSingleRevRedirect() {
4165 global $wgContentHandlerUseDB;
4167 $dbw = wfGetDB( DB_MASTER
);
4170 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
4171 if ( $wgContentHandlerUseDB ) {
4172 $fields[] = 'page_content_model';
4175 $row = $dbw->selectRow( 'page',
4181 # Cache some fields we may want
4182 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
4183 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
4184 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
4185 $this->mContentModel
= $row && isset( $row->page_content_model
)
4186 ?
strval( $row->page_content_model
)
4189 if ( !$this->mRedirect
) {
4192 # Does the article have a history?
4193 $row = $dbw->selectField( [ 'page', 'revision' ],
4195 [ 'page_namespace' => $this->mNamespace
,
4196 'page_title' => $this->mDbkeyform
,
4198 'page_latest != rev_id'
4203 # Return true if there was no history
4204 return ( $row === false );
4208 * Checks if $this can be moved to a given Title
4209 * - Selects for update, so don't call it unless you mean business
4211 * @deprecated since 1.25, use MovePage's methods instead
4212 * @param Title $nt The new title to check
4215 public function isValidMoveTarget( $nt ) {
4216 # Is it an existing file?
4217 if ( $nt->getNamespace() == NS_FILE
) {
4218 $file = wfLocalFile( $nt );
4219 $file->load( File
::READ_LATEST
);
4220 if ( $file->exists() ) {
4221 wfDebug( __METHOD__
. ": file exists\n" );
4225 # Is it a redirect with no history?
4226 if ( !$nt->isSingleRevRedirect() ) {
4227 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4230 # Get the article text
4231 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4232 if ( !is_object( $rev ) ) {
4235 $content = $rev->getContent();
4236 # Does the redirect point to the source?
4237 # Or is it a broken self-redirect, usually caused by namespace collisions?
4238 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4240 if ( $redirTitle ) {
4241 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4242 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4243 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4249 # Fail safe (not a redirect after all. strange.)
4250 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4251 " is a redirect, but it doesn't contain a valid redirect.\n" );
4257 * Get categories to which this Title belongs and return an array of
4258 * categories' names.
4260 * @return array Array of parents in the form:
4261 * $parent => $currentarticle
4263 public function getParentCategories() {
4266 $titleKey = $this->getArticleID();
4268 if ( $titleKey === 0 ) {
4272 $dbr = wfGetDB( DB_REPLICA
);
4274 $res = $dbr->select(
4277 [ 'cl_from' => $titleKey ],
4281 if ( $res->numRows() > 0 ) {
4282 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4283 foreach ( $res as $row ) {
4284 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4285 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
4286 $this->getFullText();
4293 * Get a tree of parent categories
4295 * @param array $children Array with the children in the keys, to check for circular refs
4296 * @return array Tree of parent categories
4298 public function getParentCategoryTree( $children = [] ) {
4300 $parents = $this->getParentCategories();
4303 foreach ( $parents as $parent => $current ) {
4304 if ( array_key_exists( $parent, $children ) ) {
4305 # Circular reference
4306 $stack[$parent] = [];
4308 $nt = self
::newFromText( $parent );
4310 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4320 * Get an associative array for selecting this title from
4323 * @return array Array suitable for the $where parameter of DB::select()
4325 public function pageCond() {
4326 if ( $this->mArticleID
> 0 ) {
4327 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4328 return [ 'page_id' => $this->mArticleID
];
4330 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4335 * Get next/previous revision ID relative to another revision ID
4336 * @param int $revId Revision ID. Get the revision that was before this one.
4337 * @param int $flags Title::GAID_FOR_UPDATE
4338 * @param string $dir 'next' or 'prev'
4339 * @return int|bool New revision ID, or false if none exists
4341 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4342 $revId = (int)$revId;
4343 if ( $dir === 'next' ) {
4346 } elseif ( $dir === 'prev' ) {
4350 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4353 if ( $flags & self
::GAID_FOR_UPDATE
) {
4354 $db = wfGetDB( DB_MASTER
);
4356 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4359 // Intentionally not caring if the specified revision belongs to this
4360 // page. We only care about the timestamp.
4361 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4362 if ( $ts === false ) {
4363 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4364 if ( $ts === false ) {
4365 // Or should this throw an InvalidArgumentException or something?
4369 $ts = $db->addQuotes( $ts );
4371 $revId = $db->selectField( 'revision', 'rev_id',
4373 'rev_page' => $this->getArticleID( $flags ),
4374 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4378 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4379 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4383 if ( $revId === false ) {
4386 return intval( $revId );
4391 * Get the revision ID of the previous revision
4393 * @param int $revId Revision ID. Get the revision that was before this one.
4394 * @param int $flags Title::GAID_FOR_UPDATE
4395 * @return int|bool Old revision ID, or false if none exists
4397 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4398 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4402 * Get the revision ID of the next revision
4404 * @param int $revId Revision ID. Get the revision that was after this one.
4405 * @param int $flags Title::GAID_FOR_UPDATE
4406 * @return int|bool Next revision ID, or false if none exists
4408 public function getNextRevisionID( $revId, $flags = 0 ) {
4409 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4413 * Get the first revision of the page
4415 * @param int $flags Title::GAID_FOR_UPDATE
4416 * @return Revision|null If page doesn't exist
4418 public function getFirstRevision( $flags = 0 ) {
4419 $pageId = $this->getArticleID( $flags );
4421 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4422 $revQuery = Revision
::getQueryInfo();
4423 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4424 [ 'rev_page' => $pageId ],
4427 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4428 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4433 return new Revision( $row, 0, $this );
4440 * Get the oldest revision timestamp of this page
4442 * @param int $flags Title::GAID_FOR_UPDATE
4443 * @return string|null MW timestamp
4445 public function getEarliestRevTime( $flags = 0 ) {
4446 $rev = $this->getFirstRevision( $flags );
4447 return $rev ?
$rev->getTimestamp() : null;
4451 * Check if this is a new page
4455 public function isNewPage() {
4456 $dbr = wfGetDB( DB_REPLICA
);
4457 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4461 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4465 public function isBigDeletion() {
4466 global $wgDeleteRevisionsLimit;
4468 if ( !$wgDeleteRevisionsLimit ) {
4472 if ( $this->mIsBigDeletion
=== null ) {
4473 $dbr = wfGetDB( DB_REPLICA
);
4475 $revCount = $dbr->selectRowCount(
4478 [ 'rev_page' => $this->getArticleID() ],
4480 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4483 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4486 return $this->mIsBigDeletion
;
4490 * Get the approximate revision count of this page.
4494 public function estimateRevisionCount() {
4495 if ( !$this->exists() ) {
4499 if ( $this->mEstimateRevisions
=== null ) {
4500 $dbr = wfGetDB( DB_REPLICA
);
4501 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4502 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4505 return $this->mEstimateRevisions
;
4509 * Get the number of revisions between the given revision.
4510 * Used for diffs and other things that really need it.
4512 * @param int|Revision $old Old revision or rev ID (first before range)
4513 * @param int|Revision $new New revision or rev ID (first after range)
4514 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4515 * @return int Number of revisions between these revisions.
4517 public function countRevisionsBetween( $old, $new, $max = null ) {
4518 if ( !( $old instanceof Revision
) ) {
4519 $old = Revision
::newFromTitle( $this, (int)$old );
4521 if ( !( $new instanceof Revision
) ) {
4522 $new = Revision
::newFromTitle( $this, (int)$new );
4524 if ( !$old ||
!$new ) {
4525 return 0; // nothing to compare
4527 $dbr = wfGetDB( DB_REPLICA
);
4529 'rev_page' => $this->getArticleID(),
4530 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4531 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4533 if ( $max !== null ) {
4534 return $dbr->selectRowCount( 'revision', '1',
4537 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4540 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4545 * Get the authors between the given revisions or revision IDs.
4546 * Used for diffs and other things that really need it.
4550 * @param int|Revision $old Old revision or rev ID (first before range by default)
4551 * @param int|Revision $new New revision or rev ID (first after range by default)
4552 * @param int $limit Maximum number of authors
4553 * @param string|array $options (Optional): Single option, or an array of options:
4554 * 'include_old' Include $old in the range; $new is excluded.
4555 * 'include_new' Include $new in the range; $old is excluded.
4556 * 'include_both' Include both $old and $new in the range.
4557 * Unknown option values are ignored.
4558 * @return array|null Names of revision authors in the range; null if not both revisions exist
4560 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4561 if ( !( $old instanceof Revision
) ) {
4562 $old = Revision
::newFromTitle( $this, (int)$old );
4564 if ( !( $new instanceof Revision
) ) {
4565 $new = Revision
::newFromTitle( $this, (int)$new );
4567 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4568 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4569 // in the sanity check below?
4570 if ( !$old ||
!$new ) {
4571 return null; // nothing to compare
4576 $options = (array)$options;
4577 if ( in_array( 'include_old', $options ) ) {
4580 if ( in_array( 'include_new', $options ) ) {
4583 if ( in_array( 'include_both', $options ) ) {
4587 // No DB query needed if $old and $new are the same or successive revisions:
4588 if ( $old->getId() === $new->getId() ) {
4589 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4591 [ $old->getUserText( Revision
::RAW
) ];
4592 } elseif ( $old->getId() === $new->getParentId() ) {
4593 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4594 $authors[] = $old->getUserText( Revision
::RAW
);
4595 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4596 $authors[] = $new->getUserText( Revision
::RAW
);
4598 } elseif ( $old_cmp === '>=' ) {
4599 $authors[] = $old->getUserText( Revision
::RAW
);
4600 } elseif ( $new_cmp === '<=' ) {
4601 $authors[] = $new->getUserText( Revision
::RAW
);
4605 $dbr = wfGetDB( DB_REPLICA
);
4606 $revQuery = Revision
::getQueryInfo();
4607 $authors = $dbr->selectFieldValues(
4608 $revQuery['tables'],
4609 $revQuery['fields']['rev_user_text'],
4611 'rev_page' => $this->getArticleID(),
4612 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4613 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4615 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4622 * Get the number of authors between the given revisions or revision IDs.
4623 * Used for diffs and other things that really need it.
4625 * @param int|Revision $old Old revision or rev ID (first before range by default)
4626 * @param int|Revision $new New revision or rev ID (first after range by default)
4627 * @param int $limit Maximum number of authors
4628 * @param string|array $options (Optional): Single option, or an array of options:
4629 * 'include_old' Include $old in the range; $new is excluded.
4630 * 'include_new' Include $new in the range; $old is excluded.
4631 * 'include_both' Include both $old and $new in the range.
4632 * Unknown option values are ignored.
4633 * @return int Number of revision authors in the range; zero if not both revisions exist
4635 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4636 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4637 return $authors ?
count( $authors ) : 0;
4641 * Compare with another title.
4643 * @param Title $title
4646 public function equals( Title
$title ) {
4647 // Note: === is necessary for proper matching of number-like titles.
4648 return $this->mInterwiki
=== $title->mInterwiki
4649 && $this->mNamespace
== $title->mNamespace
4650 && $this->mDbkeyform
=== $title->mDbkeyform
;
4654 * Check if this title is a subpage of another title
4656 * @param Title $title
4659 public function isSubpageOf( Title
$title ) {
4660 return $this->mInterwiki
=== $title->mInterwiki
4661 && $this->mNamespace
== $title->mNamespace
4662 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4666 * Check if page exists. For historical reasons, this function simply
4667 * checks for the existence of the title in the page table, and will
4668 * thus return false for interwiki links, special pages and the like.
4669 * If you want to know if a title can be meaningfully viewed, you should
4670 * probably call the isKnown() method instead.
4672 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4673 * from master/for update
4676 public function exists( $flags = 0 ) {
4677 $exists = $this->getArticleID( $flags ) != 0;
4678 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4683 * Should links to this title be shown as potentially viewable (i.e. as
4684 * "bluelinks"), even if there's no record by this title in the page
4687 * This function is semi-deprecated for public use, as well as somewhat
4688 * misleadingly named. You probably just want to call isKnown(), which
4689 * calls this function internally.
4691 * (ISSUE: Most of these checks are cheap, but the file existence check
4692 * can potentially be quite expensive. Including it here fixes a lot of
4693 * existing code, but we might want to add an optional parameter to skip
4694 * it and any other expensive checks.)
4698 public function isAlwaysKnown() {
4702 * Allows overriding default behavior for determining if a page exists.
4703 * If $isKnown is kept as null, regular checks happen. If it's
4704 * a boolean, this value is returned by the isKnown method.
4708 * @param Title $title
4709 * @param bool|null $isKnown
4711 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4713 if ( !is_null( $isKnown ) ) {
4717 if ( $this->isExternal() ) {
4718 return true; // any interwiki link might be viewable, for all we know
4721 switch ( $this->mNamespace
) {
4724 // file exists, possibly in a foreign repo
4725 return (bool)wfFindFile( $this );
4727 // valid special page
4728 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4729 exists( $this->mDbkeyform
);
4731 // selflink, possibly with fragment
4732 return $this->mDbkeyform
== '';
4734 // known system message
4735 return $this->hasSourceText() !== false;
4742 * Does this title refer to a page that can (or might) be meaningfully
4743 * viewed? In particular, this function may be used to determine if
4744 * links to the title should be rendered as "bluelinks" (as opposed to
4745 * "redlinks" to non-existent pages).
4746 * Adding something else to this function will cause inconsistency
4747 * since LinkHolderArray calls isAlwaysKnown() and does its own
4748 * page existence check.
4752 public function isKnown() {
4753 return $this->isAlwaysKnown() ||
$this->exists();
4757 * Does this page have source text?
4761 public function hasSourceText() {
4762 if ( $this->exists() ) {
4766 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4767 // If the page doesn't exist but is a known system message, default
4768 // message content will be displayed, same for language subpages-
4769 // Use always content language to avoid loading hundreds of languages
4770 // to get the link color.
4771 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4772 list( $name, ) = MessageCache
::singleton()->figureMessage(
4773 $contLang->lcfirst( $this->getText() )
4775 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4776 return $message->exists();
4783 * Get the default (plain) message contents for an page that overrides an
4784 * interface message key.
4786 * Primary use cases:
4789 * - Show default when viewing the page. The Article::getSubstituteContent
4790 * method displays the default message content, instead of the
4791 * 'noarticletext' placeholder message normally used.
4794 * - Title of edit page. When creating an interface message override,
4795 * the editor is told they are "Editing the page", instead of
4796 * "Creating the page". (EditPage::setHeaders)
4797 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4798 * or editing a an interface message override. (EditPage::showIntro)
4799 * - Opening the editor. The contents of the localisation message are used
4800 * as contents of the editor when creating a new page in the MediaWiki
4801 * namespace. This simplifies the process for editors when "changing"
4802 * an interface message by creating an override. (EditPage::getContentObject)
4803 * - Showing a diff. The left-hand side of a diff when an editor is
4804 * previewing their changes before saving the creation of a page in the
4805 * MediaWiki namespace. (EditPage::showDiff)
4806 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4807 * page with the proposed content matching the interface message default,
4808 * the save is rejected, the same way we disallow blank pages from being
4809 * created. (EditPage::internalAttemptSave)
4812 * - Default content, when using the 'prepend' or 'append' feature.
4815 * - Label the create action as "Edit", if the page can be an override.
4817 * @return string|bool
4819 public function getDefaultMessageText() {
4820 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4824 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4825 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4827 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4829 if ( $message->exists() ) {
4830 return $message->plain();
4837 * Updates page_touched for this page; called from LinksUpdate.php
4839 * @param string|null $purgeTime [optional] TS_MW timestamp
4840 * @return bool True if the update succeeded
4842 public function invalidateCache( $purgeTime = null ) {
4843 if ( wfReadOnly() ) {
4845 } elseif ( $this->mArticleID
=== 0 ) {
4846 return true; // avoid gap locking if we know it's not there
4849 $dbw = wfGetDB( DB_MASTER
);
4850 $dbw->onTransactionPreCommitOrIdle(
4851 function () use ( $dbw ) {
4852 ResourceLoaderWikiModule
::invalidateModuleCache(
4853 $this, null, null, $dbw->getDomainId() );
4858 $conds = $this->pageCond();
4859 DeferredUpdates
::addUpdate(
4860 new AutoCommitUpdate(
4863 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4864 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4867 [ 'page_touched' => $dbTimestamp ],
4868 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4871 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4874 DeferredUpdates
::PRESEND
4881 * Update page_touched timestamps and send CDN purge messages for
4882 * pages linking to this title. May be sent to the job queue depending
4883 * on the number of links. Typically called on create and delete.
4885 public function touchLinks() {
4886 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4887 if ( $this->mNamespace
== NS_CATEGORY
) {
4888 DeferredUpdates
::addUpdate(
4889 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4895 * Get the last touched timestamp
4897 * @param IDatabase|null $db
4898 * @return string|false Last-touched timestamp
4900 public function getTouched( $db = null ) {
4901 if ( $db === null ) {
4902 $db = wfGetDB( DB_REPLICA
);
4904 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4909 * Get the timestamp when this page was updated since the user last saw it.
4911 * @param User|null $user
4912 * @return string|null
4914 public function getNotificationTimestamp( $user = null ) {
4917 // Assume current user if none given
4921 // Check cache first
4922 $uid = $user->getId();
4926 // avoid isset here, as it'll return false for null entries
4927 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4928 return $this->mNotificationTimestamp
[$uid];
4930 // Don't cache too much!
4931 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4932 $this->mNotificationTimestamp
= [];
4935 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4936 $watchedItem = $store->getWatchedItem( $user, $this );
4937 if ( $watchedItem ) {
4938 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4940 $this->mNotificationTimestamp
[$uid] = false;
4943 return $this->mNotificationTimestamp
[$uid];
4947 * Generate strings used for xml 'id' names in monobook tabs
4949 * @param string $prepend Defaults to 'nstab-'
4950 * @return string XML 'id' name
4952 public function getNamespaceKey( $prepend = 'nstab-' ) {
4953 // Gets the subject namespace of this title
4954 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4955 // Prefer canonical namespace name for HTML IDs
4956 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4957 if ( $namespaceKey === false ) {
4958 // Fallback to localised text
4959 $namespaceKey = $this->getSubjectNsText();
4961 // Makes namespace key lowercase
4962 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4964 if ( $namespaceKey == '' ) {
4965 $namespaceKey = 'main';
4967 // Changes file to image for backwards compatibility
4968 if ( $namespaceKey == 'file' ) {
4969 $namespaceKey = 'image';
4971 return $prepend . $namespaceKey;
4975 * Get all extant redirects to this Title
4977 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4978 * @return Title[] Array of Title redirects to this title
4980 public function getRedirectsHere( $ns = null ) {
4983 $dbr = wfGetDB( DB_REPLICA
);
4985 'rd_namespace' => $this->mNamespace
,
4986 'rd_title' => $this->mDbkeyform
,
4989 if ( $this->isExternal() ) {
4990 $where['rd_interwiki'] = $this->mInterwiki
;
4992 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4994 if ( !is_null( $ns ) ) {
4995 $where['page_namespace'] = $ns;
4998 $res = $dbr->select(
4999 [ 'redirect', 'page' ],
5000 [ 'page_namespace', 'page_title' ],
5005 foreach ( $res as $row ) {
5006 $redirs[] = self
::newFromRow( $row );
5012 * Check if this Title is a valid redirect target
5016 public function isValidRedirectTarget() {
5017 global $wgInvalidRedirectTargets;
5019 if ( $this->isSpecialPage() ) {
5020 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
5021 if ( $this->isSpecial( 'Userlogout' ) ) {
5025 foreach ( $wgInvalidRedirectTargets as $target ) {
5026 if ( $this->isSpecial( $target ) ) {
5036 * Get a backlink cache object
5038 * @return BacklinkCache
5040 public function getBacklinkCache() {
5041 return BacklinkCache
::get( $this );
5045 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
5049 public function canUseNoindex() {
5050 global $wgExemptFromUserRobotsControl;
5052 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
5053 ? MWNamespace
::getContentNamespaces()
5054 : $wgExemptFromUserRobotsControl;
5056 return !in_array( $this->mNamespace
, $bannedNamespaces );
5060 * Returns the raw sort key to be used for categories, with the specified
5061 * prefix. This will be fed to Collation::getSortKey() to get a
5062 * binary sortkey that can be used for actual sorting.
5064 * @param string $prefix The prefix to be used, specified using
5065 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
5069 public function getCategorySortkey( $prefix = '' ) {
5070 $unprefixed = $this->getText();
5072 // Anything that uses this hook should only depend
5073 // on the Title object passed in, and should probably
5074 // tell the users to run updateCollations.php --force
5075 // in order to re-sort existing category relations.
5076 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
5077 if ( $prefix !== '' ) {
5078 # Separate with a line feed, so the unprefixed part is only used as
5079 # a tiebreaker when two pages have the exact same prefix.
5080 # In UCA, tab is the only character that can sort above LF
5081 # so we strip both of them from the original prefix.
5082 $prefix = strtr( $prefix, "\n\t", ' ' );
5083 return "$prefix\n$unprefixed";
5089 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
5090 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
5091 * the db, it will return NULL.
5093 * @return string|null|bool
5095 private function getDbPageLanguageCode() {
5096 global $wgPageLanguageUseDB;
5098 // check, if the page language could be saved in the database, and if so and
5099 // the value is not requested already, lookup the page language using LinkCache
5100 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
5101 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
5102 $linkCache->addLinkObj( $this );
5103 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
5106 return $this->mDbPageLanguage
;
5110 * Get the language in which the content of this page is written in
5111 * wikitext. Defaults to content language, but in certain cases it can be
5112 * e.g. $wgLang (such as special pages, which are in the user language).
5117 public function getPageLanguage() {
5118 global $wgLang, $wgLanguageCode;
5119 if ( $this->isSpecialPage() ) {
5120 // special pages are in the user language
5124 // Checking if DB language is set
5125 $dbPageLanguage = $this->getDbPageLanguageCode();
5126 if ( $dbPageLanguage ) {
5127 return wfGetLangObj( $dbPageLanguage );
5130 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
5131 // Note that this may depend on user settings, so the cache should
5132 // be only per-request.
5133 // NOTE: ContentHandler::getPageLanguage() may need to load the
5134 // content to determine the page language!
5135 // Checking $wgLanguageCode hasn't changed for the benefit of unit
5137 $contentHandler = ContentHandler
::getForTitle( $this );
5138 $langObj = $contentHandler->getPageLanguage( $this );
5139 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
5141 $langObj = Language
::factory( $this->mPageLanguage
[0] );
5148 * Get the language in which the content of this page is written when
5149 * viewed by user. Defaults to content language, but in certain cases it can be
5150 * e.g. $wgLang (such as special pages, which are in the user language).
5155 public function getPageViewLanguage() {
5158 if ( $this->isSpecialPage() ) {
5159 // If the user chooses a variant, the content is actually
5160 // in a language whose code is the variant code.
5161 $variant = $wgLang->getPreferredVariant();
5162 if ( $wgLang->getCode() !== $variant ) {
5163 return Language
::factory( $variant );
5169 // Checking if DB language is set
5170 $dbPageLanguage = $this->getDbPageLanguageCode();
5171 if ( $dbPageLanguage ) {
5172 $pageLang = wfGetLangObj( $dbPageLanguage );
5173 $variant = $pageLang->getPreferredVariant();
5174 if ( $pageLang->getCode() !== $variant ) {
5175 $pageLang = Language
::factory( $variant );
5181 // @note Can't be cached persistently, depends on user settings.
5182 // @note ContentHandler::getPageViewLanguage() may need to load the
5183 // content to determine the page language!
5184 $contentHandler = ContentHandler
::getForTitle( $this );
5185 $pageLang = $contentHandler->getPageViewLanguage( $this );
5190 * Get a list of rendered edit notices for this page.
5192 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
5193 * they will already be wrapped in paragraphs.
5196 * @param int $oldid Revision ID that's being edited
5199 public function getEditNotices( $oldid = 0 ) {
5202 // Optional notice for the entire namespace
5203 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
5204 $msg = wfMessage( $editnotice_ns );
5205 if ( $msg->exists() ) {
5206 $html = $msg->parseAsBlock();
5207 // Edit notices may have complex logic, but output nothing (T91715)
5208 if ( trim( $html ) !== '' ) {
5209 $notices[$editnotice_ns] = Html
::rawElement(
5213 'mw-editnotice-namespace',
5214 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
5221 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
5222 // Optional notice for page itself and any parent page
5223 $parts = explode( '/', $this->mDbkeyform
);
5224 $editnotice_base = $editnotice_ns;
5225 while ( count( $parts ) > 0 ) {
5226 $editnotice_base .= '-' . array_shift( $parts );
5227 $msg = wfMessage( $editnotice_base );
5228 if ( $msg->exists() ) {
5229 $html = $msg->parseAsBlock();
5230 if ( trim( $html ) !== '' ) {
5231 $notices[$editnotice_base] = Html
::rawElement(
5235 'mw-editnotice-base',
5236 Sanitizer
::escapeClass( "mw-$editnotice_base" )
5244 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
5245 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
5246 $msg = wfMessage( $editnoticeText );
5247 if ( $msg->exists() ) {
5248 $html = $msg->parseAsBlock();
5249 if ( trim( $html ) !== '' ) {
5250 $notices[$editnoticeText] = Html
::rawElement(
5254 'mw-editnotice-page',
5255 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5263 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5270 public function __sleep() {
5278 'mDefaultNamespace',
5282 public function __wakeup() {
5283 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5284 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5285 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );