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
24 use MediaWiki\Linker\LinkTarget
;
25 use MediaWiki\Interwiki\InterwikiLookup
;
26 use MediaWiki\MediaWikiServices
;
29 * Represents a title within MediaWiki.
30 * Optionally may contain an interwiki designation or namespace.
31 * @note This class can fetch various kinds of data from the database;
32 * however, it does so inefficiently.
33 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
34 * and does not rely on global state or the database.
36 class Title
implements LinkTarget
{
37 /** @var HashBagOStuff */
38 static private $titleCache = null;
41 * Title::newFromText maintains a cache to avoid expensive re-normalization of
42 * commonly used titles. On a batch operation this can become a memory leak
43 * if not bounded. After hitting this many titles reset the cache.
45 const CACHE_MAX
= 1000;
48 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
49 * to use the master DB
51 const GAID_FOR_UPDATE
= 1;
54 * @name Private member variables
55 * Please use the accessor functions instead.
60 /** @var string Text form (spaces not underscores) of the main part */
61 public $mTextform = '';
63 /** @var string URL-encoded form of the main part */
64 public $mUrlform = '';
66 /** @var string Main part with underscores */
67 public $mDbkeyform = '';
69 /** @var string Database key with the initial letter in the case specified by the user */
70 protected $mUserCaseDBKey;
72 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
73 public $mNamespace = NS_MAIN
;
75 /** @var string Interwiki prefix */
76 public $mInterwiki = '';
78 /** @var bool Was this Title created from a string with a local interwiki prefix? */
79 private $mLocalInterwiki = false;
81 /** @var string Title fragment (i.e. the bit after the #) */
82 public $mFragment = '';
84 /** @var int Article ID, fetched from the link cache on demand */
85 public $mArticleID = -1;
87 /** @var bool|int ID of most recent revision */
88 protected $mLatestID = false;
91 * @var bool|string ID of the page's content model, i.e. one of the
92 * CONTENT_MODEL_XXX constants
94 public $mContentModel = false;
96 /** @var int Estimated number of revisions; null of not loaded */
97 private $mEstimateRevisions;
99 /** @var array Array of groups allowed to edit this article */
100 public $mRestrictions = [];
102 /** @var string|bool */
103 protected $mOldRestrictions = false;
105 /** @var bool Cascade restrictions on this page to included templates and images? */
106 public $mCascadeRestriction;
108 /** Caching the results of getCascadeProtectionSources */
109 public $mCascadingRestrictions;
111 /** @var array When do the restrictions on this page expire? */
112 protected $mRestrictionsExpiry = [];
114 /** @var bool Are cascading restrictions in effect on this page? */
115 protected $mHasCascadingRestrictions;
117 /** @var array Where are the cascading restrictions coming from on this page? */
118 public $mCascadeSources;
120 /** @var bool Boolean for initialisation on demand */
121 public $mRestrictionsLoaded = false;
123 /** @var string Text form including namespace/interwiki, initialised on demand */
124 protected $mPrefixedText = null;
126 /** @var mixed Cached value for getTitleProtection (create protection) */
127 public $mTitleProtection;
130 * @var int Namespace index when there is no namespace. Don't change the
131 * following default, NS_MAIN is hardcoded in several places. See bug 696.
132 * Zero except in {{transclusion}} tags.
134 public $mDefaultNamespace = NS_MAIN
;
136 /** @var int The page length, 0 for special pages */
137 protected $mLength = -1;
139 /** @var null Is the article at this title a redirect? */
140 public $mRedirect = null;
142 /** @var array Associative array of user ID -> timestamp/false */
143 private $mNotificationTimestamp = [];
145 /** @var bool Whether a page has any subpages */
146 private $mHasSubpages;
148 /** @var bool The (string) language code of the page's language and content code. */
149 private $mPageLanguage = false;
151 /** @var string|bool|null The page language code from the database, null if not saved in
152 * the database or false if not loaded, yet. */
153 private $mDbPageLanguage = false;
155 /** @var TitleValue A corresponding TitleValue object */
156 private $mTitleValue = null;
158 /** @var bool Would deleting this page be a big deletion? */
159 private $mIsBigDeletion = null;
163 * B/C kludge: provide a TitleParser for use by Title.
164 * Ideally, Title would have no methods that need this.
165 * Avoid usage of this singleton by using TitleValue
166 * and the associated services when possible.
168 * @return TitleFormatter
170 private static function getTitleFormatter() {
171 return MediaWikiServices
::getInstance()->getTitleFormatter();
175 * B/C kludge: provide an InterwikiLookup for use by Title.
176 * Ideally, Title would have no methods that need this.
177 * Avoid usage of this singleton by using TitleValue
178 * and the associated services when possible.
180 * @return InterwikiLookup
182 private static function getInterwikiLookup() {
183 return MediaWikiServices
::getInstance()->getInterwikiLookup();
189 function __construct() {
193 * Create a new Title from a prefixed DB key
195 * @param string $key The database key, which has underscores
196 * instead of spaces, possibly including namespace and
198 * @return Title|null Title, or null on an error
200 public static function newFromDBkey( $key ) {
202 $t->mDbkeyform
= $key;
205 $t->secureAndSplit();
207 } catch ( MalformedTitleException
$ex ) {
213 * Create a new Title from a TitleValue
215 * @param TitleValue $titleValue Assumed to be safe.
219 public static function newFromTitleValue( TitleValue
$titleValue ) {
220 return self
::newFromLinkTarget( $titleValue );
224 * Create a new Title from a LinkTarget
226 * @param LinkTarget $linkTarget Assumed to be safe.
230 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
231 if ( $linkTarget instanceof Title
) {
232 // Special case if it's already a Title object
235 return self
::makeTitle(
236 $linkTarget->getNamespace(),
237 $linkTarget->getText(),
238 $linkTarget->getFragment(),
239 $linkTarget->getInterwiki()
244 * Create a new Title from text, such as what one would find in a link. De-
245 * codes any HTML entities in the text.
247 * @param string|int|null $text The link text; spaces, prefixes, and an
248 * initial ':' indicating the main namespace are accepted.
249 * @param int $defaultNamespace The namespace to use if none is specified
250 * by a prefix. If you want to force a specific namespace even if
251 * $text might begin with a namespace prefix, use makeTitle() or
253 * @throws InvalidArgumentException
254 * @return Title|null Title or null on an error.
256 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
257 // DWIM: Integers can be passed in here when page titles are used as array keys.
258 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
259 throw new InvalidArgumentException( '$text must be a string.' );
261 if ( $text === null ) {
266 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
267 } catch ( MalformedTitleException
$ex ) {
273 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
274 * rather than returning null.
276 * The exception subclasses encode detailed information about why the title is invalid.
278 * @see Title::newFromText
281 * @param string $text Title text to check
282 * @param int $defaultNamespace
283 * @throws MalformedTitleException If the title is invalid
286 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
287 if ( is_object( $text ) ) {
288 throw new MWException( '$text must be a string, given an object' );
291 $titleCache = self
::getTitleCache();
293 // Wiki pages often contain multiple links to the same page.
294 // Title normalization and parsing can become expensive on pages with many
295 // links, so we can save a little time by caching them.
296 // In theory these are value objects and won't get changed...
297 if ( $defaultNamespace == NS_MAIN
) {
298 $t = $titleCache->get( $text );
304 // Convert things like é ā or 〗 into normalized (bug 14952) text
305 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
308 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
309 $t->mDefaultNamespace
= intval( $defaultNamespace );
311 $t->secureAndSplit();
312 if ( $defaultNamespace == NS_MAIN
) {
313 $titleCache->set( $text, $t );
319 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
321 * Example of wrong and broken code:
322 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
324 * Example of right code:
325 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
327 * Create a new Title from URL-encoded text. Ensures that
328 * the given title's length does not exceed the maximum.
330 * @param string $url The title, as might be taken from a URL
331 * @return Title|null The new object, or null on an error
333 public static function newFromURL( $url ) {
336 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
337 # but some URLs used it as a space replacement and they still come
338 # from some external search tools.
339 if ( strpos( self
::legalChars(), '+' ) === false ) {
340 $url = strtr( $url, '+', ' ' );
343 $t->mDbkeyform
= strtr( $url, ' ', '_' );
346 $t->secureAndSplit();
348 } catch ( MalformedTitleException
$ex ) {
354 * @return HashBagOStuff
356 private static function getTitleCache() {
357 if ( self
::$titleCache == null ) {
358 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
360 return self
::$titleCache;
364 * Returns a list of fields that are to be selected for initializing Title
365 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
366 * whether to include page_content_model.
370 protected static function getSelectFields() {
371 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
374 'page_namespace', 'page_title', 'page_id',
375 'page_len', 'page_is_redirect', 'page_latest',
378 if ( $wgContentHandlerUseDB ) {
379 $fields[] = 'page_content_model';
382 if ( $wgPageLanguageUseDB ) {
383 $fields[] = 'page_lang';
390 * Create a new Title from an article ID
392 * @param int $id The page_id corresponding to the Title to create
393 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
394 * @return Title|null The new object, or null on an error
396 public static function newFromID( $id, $flags = 0 ) {
397 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
398 $row = $db->selectRow(
400 self
::getSelectFields(),
401 [ 'page_id' => $id ],
404 if ( $row !== false ) {
405 $title = Title
::newFromRow( $row );
413 * Make an array of titles from an array of IDs
415 * @param int[] $ids Array of IDs
416 * @return Title[] Array of Titles
418 public static function newFromIDs( $ids ) {
419 if ( !count( $ids ) ) {
422 $dbr = wfGetDB( DB_SLAVE
);
426 self
::getSelectFields(),
427 [ 'page_id' => $ids ],
432 foreach ( $res as $row ) {
433 $titles[] = Title
::newFromRow( $row );
439 * Make a Title object from a DB row
441 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
442 * @return Title Corresponding Title
444 public static function newFromRow( $row ) {
445 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
446 $t->loadFromRow( $row );
451 * Load Title object fields from a DB row.
452 * If false is given, the title will be treated as non-existing.
454 * @param stdClass|bool $row Database row
456 public function loadFromRow( $row ) {
457 if ( $row ) { // page found
458 if ( isset( $row->page_id
) ) {
459 $this->mArticleID
= (int)$row->page_id
;
461 if ( isset( $row->page_len
) ) {
462 $this->mLength
= (int)$row->page_len
;
464 if ( isset( $row->page_is_redirect
) ) {
465 $this->mRedirect
= (bool)$row->page_is_redirect
;
467 if ( isset( $row->page_latest
) ) {
468 $this->mLatestID
= (int)$row->page_latest
;
470 if ( isset( $row->page_content_model
) ) {
471 $this->mContentModel
= strval( $row->page_content_model
);
473 $this->mContentModel
= false; # initialized lazily in getContentModel()
475 if ( isset( $row->page_lang
) ) {
476 $this->mDbPageLanguage
= (string)$row->page_lang
;
478 if ( isset( $row->page_restrictions
) ) {
479 $this->mOldRestrictions
= $row->page_restrictions
;
481 } else { // page not found
482 $this->mArticleID
= 0;
484 $this->mRedirect
= false;
485 $this->mLatestID
= 0;
486 $this->mContentModel
= false; # initialized lazily in getContentModel()
491 * Create a new Title from a namespace index and a DB key.
492 * It's assumed that $ns and $title are *valid*, for instance when
493 * they came directly from the database or a special page name.
494 * For convenience, spaces are converted to underscores so that
495 * eg user_text fields can be used directly.
497 * @param int $ns The namespace of the article
498 * @param string $title The unprefixed database key form
499 * @param string $fragment The link fragment (after the "#")
500 * @param string $interwiki The interwiki prefix
501 * @return Title The new object
503 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
505 $t->mInterwiki
= $interwiki;
506 $t->mFragment
= $fragment;
507 $t->mNamespace
= $ns = intval( $ns );
508 $t->mDbkeyform
= strtr( $title, ' ', '_' );
509 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
510 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
511 $t->mTextform
= strtr( $title, '_', ' ' );
512 $t->mContentModel
= false; # initialized lazily in getContentModel()
517 * Create a new Title from a namespace index and a DB key.
518 * The parameters will be checked for validity, which is a bit slower
519 * than makeTitle() but safer for user-provided data.
521 * @param int $ns The namespace of the article
522 * @param string $title Database key form
523 * @param string $fragment The link fragment (after the "#")
524 * @param string $interwiki Interwiki prefix
525 * @return Title|null The new object, or null on an error
527 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
528 if ( !MWNamespace
::exists( $ns ) ) {
533 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
536 $t->secureAndSplit();
538 } catch ( MalformedTitleException
$ex ) {
544 * Create a new Title for the Main Page
546 * @return Title The new object
548 public static function newMainPage() {
549 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
550 // Don't give fatal errors if the message is broken
552 $title = Title
::newFromText( 'Main Page' );
558 * Get the prefixed DB key associated with an ID
560 * @param int $id The page_id of the article
561 * @return Title|null An object representing the article, or null if no such article was found
563 public static function nameOf( $id ) {
564 $dbr = wfGetDB( DB_SLAVE
);
566 $s = $dbr->selectRow(
568 [ 'page_namespace', 'page_title' ],
569 [ 'page_id' => $id ],
572 if ( $s === false ) {
576 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
581 * Get a regex character class describing the legal characters in a link
583 * @return string The list of characters, not delimited
585 public static function legalChars() {
586 global $wgLegalTitleChars;
587 return $wgLegalTitleChars;
591 * Returns a simple regex that will match on characters and sequences invalid in titles.
592 * Note that this doesn't pick up many things that could be wrong with titles, but that
593 * replacing this regex with something valid will make many titles valid.
595 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
597 * @return string Regex string
599 static function getTitleInvalidRegex() {
600 wfDeprecated( __METHOD__
, '1.25' );
601 return MediaWikiTitleCodec
::getTitleInvalidRegex();
605 * Utility method for converting a character sequence from bytes to Unicode.
607 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
608 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
610 * @param string $byteClass
613 public static function convertByteClassToUnicodeClass( $byteClass ) {
614 $length = strlen( $byteClass );
616 $x0 = $x1 = $x2 = '';
618 $d0 = $d1 = $d2 = '';
619 // Decoded integer codepoints
620 $ord0 = $ord1 = $ord2 = 0;
622 $r0 = $r1 = $r2 = '';
626 $allowUnicode = false;
627 for ( $pos = 0; $pos < $length; $pos++
) {
628 // Shift the queues down
637 // Load the current input token and decoded values
638 $inChar = $byteClass[$pos];
639 if ( $inChar == '\\' ) {
640 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
641 $x0 = $inChar . $m[0];
642 $d0 = chr( hexdec( $m[1] ) );
643 $pos +
= strlen( $m[0] );
644 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
645 $x0 = $inChar . $m[0];
646 $d0 = chr( octdec( $m[0] ) );
647 $pos +
= strlen( $m[0] );
648 } elseif ( $pos +
1 >= $length ) {
651 $d0 = $byteClass[$pos +
1];
659 // Load the current re-encoded value
660 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
661 $r0 = sprintf( '\x%02x', $ord0 );
662 } elseif ( $ord0 >= 0x80 ) {
663 // Allow unicode if a single high-bit character appears
664 $r0 = sprintf( '\x%02x', $ord0 );
665 $allowUnicode = true;
666 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
672 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
674 if ( $ord2 > $ord0 ) {
676 } elseif ( $ord0 >= 0x80 ) {
678 $allowUnicode = true;
679 if ( $ord2 < 0x80 ) {
680 // Keep the non-unicode section of the range
687 // Reset state to the initial value
688 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
689 } elseif ( $ord2 < 0x80 ) {
694 if ( $ord1 < 0x80 ) {
697 if ( $ord0 < 0x80 ) {
700 if ( $allowUnicode ) {
701 $out .= '\u0080-\uFFFF';
707 * Make a prefixed DB key from a DB key and a namespace index
709 * @param int $ns Numerical representation of the namespace
710 * @param string $title The DB key form the title
711 * @param string $fragment The link fragment (after the "#")
712 * @param string $interwiki The interwiki prefix
713 * @param bool $canonicalNamespace If true, use the canonical name for
714 * $ns instead of the localized version.
715 * @return string The prefixed form of the title
717 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
718 $canonicalNamespace = false
722 if ( $canonicalNamespace ) {
723 $namespace = MWNamespace
::getCanonicalName( $ns );
725 $namespace = $wgContLang->getNsText( $ns );
727 $name = $namespace == '' ?
$title : "$namespace:$title";
728 if ( strval( $interwiki ) != '' ) {
729 $name = "$interwiki:$name";
731 if ( strval( $fragment ) != '' ) {
732 $name .= '#' . $fragment;
738 * Escape a text fragment, say from a link, for a URL
740 * @param string $fragment Containing a URL or link fragment (after the "#")
741 * @return string Escaped string
743 static function escapeFragmentForURL( $fragment ) {
744 # Note that we don't urlencode the fragment. urlencoded Unicode
745 # fragments appear not to work in IE (at least up to 7) or in at least
746 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
747 # to care if they aren't encoded.
748 return Sanitizer
::escapeId( $fragment, 'noninitial' );
752 * Callback for usort() to do title sorts by (namespace, title)
757 * @return int Result of string comparison, or namespace comparison
759 public static function compare( $a, $b ) {
760 if ( $a->getNamespace() == $b->getNamespace() ) {
761 return strcmp( $a->getText(), $b->getText() );
763 return $a->getNamespace() - $b->getNamespace();
768 * Determine whether the object refers to a page within
769 * this project (either this wiki or a wiki with a local
770 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
772 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
774 public function isLocal() {
775 if ( $this->isExternal() ) {
776 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
778 return $iw->isLocal();
785 * Is this Title interwiki?
789 public function isExternal() {
790 return $this->mInterwiki
!== '';
794 * Get the interwiki prefix
796 * Use Title::isExternal to check if a interwiki is set
798 * @return string Interwiki prefix
800 public function getInterwiki() {
801 return $this->mInterwiki
;
805 * Was this a local interwiki link?
809 public function wasLocalInterwiki() {
810 return $this->mLocalInterwiki
;
814 * Determine whether the object refers to a page within
815 * this project and is transcludable.
817 * @return bool True if this is transcludable
819 public function isTrans() {
820 if ( !$this->isExternal() ) {
824 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
828 * Returns the DB name of the distant wiki which owns the object.
830 * @return string The DB name
832 public function getTransWikiID() {
833 if ( !$this->isExternal() ) {
837 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
841 * Get a TitleValue object representing this Title.
843 * @note Not all valid Titles have a corresponding valid TitleValue
844 * (e.g. TitleValues cannot represent page-local links that have a
845 * fragment but no title text).
847 * @return TitleValue|null
849 public function getTitleValue() {
850 if ( $this->mTitleValue
=== null ) {
852 $this->mTitleValue
= new TitleValue(
853 $this->getNamespace(),
855 $this->getFragment(),
856 $this->getInterwiki()
858 } catch ( InvalidArgumentException
$ex ) {
859 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
860 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
864 return $this->mTitleValue
;
868 * Get the text form (spaces not underscores) of the main part
870 * @return string Main part of the title
872 public function getText() {
873 return $this->mTextform
;
877 * Get the URL-encoded form of the main part
879 * @return string Main part of the title, URL-encoded
881 public function getPartialURL() {
882 return $this->mUrlform
;
886 * Get the main part with underscores
888 * @return string Main part of the title, with underscores
890 public function getDBkey() {
891 return $this->mDbkeyform
;
895 * Get the DB key with the initial letter case as specified by the user
897 * @return string DB key
899 function getUserCaseDBKey() {
900 if ( !is_null( $this->mUserCaseDBKey
) ) {
901 return $this->mUserCaseDBKey
;
903 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
904 return $this->mDbkeyform
;
909 * Get the namespace index, i.e. one of the NS_xxxx constants.
911 * @return int Namespace index
913 public function getNamespace() {
914 return $this->mNamespace
;
918 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
920 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
921 * @return string Content model id
923 public function getContentModel( $flags = 0 ) {
924 if ( ( !$this->mContentModel ||
$flags === Title
::GAID_FOR_UPDATE
) &&
925 $this->getArticleID( $flags )
927 $linkCache = LinkCache
::singleton();
928 $linkCache->addLinkObj( $this ); # in case we already had an article ID
929 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
932 if ( !$this->mContentModel
) {
933 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
936 return $this->mContentModel
;
940 * Convenience method for checking a title's content model name
942 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
943 * @return bool True if $this->getContentModel() == $id
945 public function hasContentModel( $id ) {
946 return $this->getContentModel() == $id;
950 * Get the namespace text
952 * @return string Namespace text
954 public function getNsText() {
955 if ( $this->isExternal() ) {
956 // This probably shouldn't even happen,
957 // but for interwiki transclusion it sometimes does.
958 // Use the canonical namespaces if possible to try to
959 // resolve a foreign namespace.
960 if ( MWNamespace
::exists( $this->mNamespace
) ) {
961 return MWNamespace
::getCanonicalName( $this->mNamespace
);
966 $formatter = self
::getTitleFormatter();
967 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
968 } catch ( InvalidArgumentException
$ex ) {
969 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
975 * Get the namespace text of the subject (rather than talk) page
977 * @return string Namespace text
979 public function getSubjectNsText() {
981 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
985 * Get the namespace text of the talk page
987 * @return string Namespace text
989 public function getTalkNsText() {
991 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
995 * Could this title have a corresponding talk page?
999 public function canTalk() {
1000 return MWNamespace
::canTalk( $this->mNamespace
);
1004 * Is this in a namespace that allows actual pages?
1008 public function canExist() {
1009 return $this->mNamespace
>= NS_MAIN
;
1013 * Can this title be added to a user's watchlist?
1017 public function isWatchable() {
1018 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1022 * Returns true if this is a special page.
1026 public function isSpecialPage() {
1027 return $this->getNamespace() == NS_SPECIAL
;
1031 * Returns true if this title resolves to the named special page
1033 * @param string $name The special page name
1036 public function isSpecial( $name ) {
1037 if ( $this->isSpecialPage() ) {
1038 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1039 if ( $name == $thisName ) {
1047 * If the Title refers to a special page alias which is not the local default, resolve
1048 * the alias, and localise the name as necessary. Otherwise, return $this
1052 public function fixSpecialName() {
1053 if ( $this->isSpecialPage() ) {
1054 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1055 if ( $canonicalName ) {
1056 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1057 if ( $localName != $this->mDbkeyform
) {
1058 return Title
::makeTitle( NS_SPECIAL
, $localName );
1066 * Returns true if the title is inside the specified namespace.
1068 * Please make use of this instead of comparing to getNamespace()
1069 * This function is much more resistant to changes we may make
1070 * to namespaces than code that makes direct comparisons.
1071 * @param int $ns The namespace
1075 public function inNamespace( $ns ) {
1076 return MWNamespace
::equals( $this->getNamespace(), $ns );
1080 * Returns true if the title is inside one of the specified namespaces.
1082 * @param int $namespaces,... The namespaces to check for
1086 public function inNamespaces( /* ... */ ) {
1087 $namespaces = func_get_args();
1088 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1089 $namespaces = $namespaces[0];
1092 foreach ( $namespaces as $ns ) {
1093 if ( $this->inNamespace( $ns ) ) {
1102 * Returns true if the title has the same subject namespace as the
1103 * namespace specified.
1104 * For example this method will take NS_USER and return true if namespace
1105 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1106 * as their subject namespace.
1108 * This is MUCH simpler than individually testing for equivalence
1109 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1114 public function hasSubjectNamespace( $ns ) {
1115 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1119 * Is this Title in a namespace which contains content?
1120 * In other words, is this a content page, for the purposes of calculating
1125 public function isContentPage() {
1126 return MWNamespace
::isContent( $this->getNamespace() );
1130 * Would anybody with sufficient privileges be able to move this page?
1131 * Some pages just aren't movable.
1135 public function isMovable() {
1136 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1137 // Interwiki title or immovable namespace. Hooks don't get to override here
1142 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1147 * Is this the mainpage?
1148 * @note Title::newFromText seems to be sufficiently optimized by the title
1149 * cache that we don't need to over-optimize by doing direct comparisons and
1150 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1151 * ends up reporting something differently than $title->isMainPage();
1156 public function isMainPage() {
1157 return $this->equals( Title
::newMainPage() );
1161 * Is this a subpage?
1165 public function isSubpage() {
1166 return MWNamespace
::hasSubpages( $this->mNamespace
)
1167 ?
strpos( $this->getText(), '/' ) !== false
1172 * Is this a conversion table for the LanguageConverter?
1176 public function isConversionTable() {
1177 // @todo ConversionTable should become a separate content model.
1179 return $this->getNamespace() == NS_MEDIAWIKI
&&
1180 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1184 * Does that page contain wikitext, or it is JS, CSS or whatever?
1188 public function isWikitextPage() {
1189 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1193 * Could this page contain custom CSS or JavaScript for the global UI.
1194 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1195 * or CONTENT_MODEL_JAVASCRIPT.
1197 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1200 * Note that this method should not return true for pages that contain and
1201 * show "inactive" CSS or JS.
1204 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1206 public function isCssOrJsPage() {
1207 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1208 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1209 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1211 # @note This hook is also called in ContentHandler::getDefaultModel.
1212 # It's called here again to make sure hook functions can force this
1213 # method to return true even outside the MediaWiki namespace.
1215 Hooks
::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1217 return $isCssOrJsPage;
1221 * Is this a .css or .js subpage of a user page?
1223 * @todo FIXME: Rename to isUserConfigPage()
1225 public function isCssJsSubpage() {
1226 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1227 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1228 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1232 * Trim down a .css or .js subpage title to get the corresponding skin name
1234 * @return string Containing skin name from .css or .js subpage title
1236 public function getSkinFromCssJsSubpage() {
1237 $subpage = explode( '/', $this->mTextform
);
1238 $subpage = $subpage[count( $subpage ) - 1];
1239 $lastdot = strrpos( $subpage, '.' );
1240 if ( $lastdot === false ) {
1241 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1243 return substr( $subpage, 0, $lastdot );
1247 * Is this a .css subpage of a user page?
1251 public function isCssSubpage() {
1252 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1253 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1257 * Is this a .js subpage of a user page?
1261 public function isJsSubpage() {
1262 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1263 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1267 * Is this a talk page of some sort?
1271 public function isTalkPage() {
1272 return MWNamespace
::isTalk( $this->getNamespace() );
1276 * Get a Title object associated with the talk page of this article
1278 * @return Title The object for the talk page
1280 public function getTalkPage() {
1281 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1285 * Get a title object associated with the subject page of this
1288 * @return Title The object for the subject page
1290 public function getSubjectPage() {
1291 // Is this the same title?
1292 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1293 if ( $this->getNamespace() == $subjectNS ) {
1296 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1300 * Get the other title for this page, if this is a subject page
1301 * get the talk page, if it is a subject page get the talk page
1304 * @throws MWException
1307 public function getOtherPage() {
1308 if ( $this->isSpecialPage() ) {
1309 throw new MWException( 'Special pages cannot have other pages' );
1311 if ( $this->isTalkPage() ) {
1312 return $this->getSubjectPage();
1314 return $this->getTalkPage();
1319 * Get the default namespace index, for when there is no namespace
1321 * @return int Default namespace index
1323 public function getDefaultNamespace() {
1324 return $this->mDefaultNamespace
;
1328 * Get the Title fragment (i.e.\ the bit after the #) in text form
1330 * Use Title::hasFragment to check for a fragment
1332 * @return string Title fragment
1334 public function getFragment() {
1335 return $this->mFragment
;
1339 * Check if a Title fragment is set
1344 public function hasFragment() {
1345 return $this->mFragment
!== '';
1349 * Get the fragment in URL form, including the "#" character if there is one
1350 * @return string Fragment in URL form
1352 public function getFragmentForURL() {
1353 if ( !$this->hasFragment() ) {
1356 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1361 * Set the fragment for this title. Removes the first character from the
1362 * specified fragment before setting, so it assumes you're passing it with
1365 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1366 * or Title::createFragmentTarget().
1367 * Still in active use privately.
1370 * @param string $fragment Text
1372 public function setFragment( $fragment ) {
1373 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1377 * Creates a new Title for a different fragment of the same page.
1380 * @param string $fragment
1383 public function createFragmentTarget( $fragment ) {
1384 return self
::makeTitle(
1385 $this->getNamespace(),
1388 $this->getInterwiki()
1394 * Prefix some arbitrary text with the namespace or interwiki prefix
1397 * @param string $name The text
1398 * @return string The prefixed text
1400 private function prefix( $name ) {
1402 if ( $this->isExternal() ) {
1403 $p = $this->mInterwiki
. ':';
1406 if ( 0 != $this->mNamespace
) {
1407 $p .= $this->getNsText() . ':';
1413 * Get the prefixed database key form
1415 * @return string The prefixed title, with underscores and
1416 * any interwiki and namespace prefixes
1418 public function getPrefixedDBkey() {
1419 $s = $this->prefix( $this->mDbkeyform
);
1420 $s = strtr( $s, ' ', '_' );
1425 * Get the prefixed title with spaces.
1426 * This is the form usually used for display
1428 * @return string The prefixed title, with spaces
1430 public function getPrefixedText() {
1431 if ( $this->mPrefixedText
=== null ) {
1432 $s = $this->prefix( $this->mTextform
);
1433 $s = strtr( $s, '_', ' ' );
1434 $this->mPrefixedText
= $s;
1436 return $this->mPrefixedText
;
1440 * Return a string representation of this title
1442 * @return string Representation of this title
1444 public function __toString() {
1445 return $this->getPrefixedText();
1449 * Get the prefixed title with spaces, plus any fragment
1450 * (part beginning with '#')
1452 * @return string The prefixed title, with spaces and the fragment, including '#'
1454 public function getFullText() {
1455 $text = $this->getPrefixedText();
1456 if ( $this->hasFragment() ) {
1457 $text .= '#' . $this->getFragment();
1463 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1467 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1471 * @return string Root name
1474 public function getRootText() {
1475 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1476 return $this->getText();
1479 return strtok( $this->getText(), '/' );
1483 * Get the root page name title, i.e. the leftmost part before any slashes
1487 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1488 * # returns: Title{User:Foo}
1491 * @return Title Root title
1494 public function getRootTitle() {
1495 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1499 * Get the base page name without a namespace, i.e. the part before the subpage name
1503 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1504 * # returns: 'Foo/Bar'
1507 * @return string Base name
1509 public function getBaseText() {
1510 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1511 return $this->getText();
1514 $parts = explode( '/', $this->getText() );
1515 # Don't discard the real title if there's no subpage involved
1516 if ( count( $parts ) > 1 ) {
1517 unset( $parts[count( $parts ) - 1] );
1519 return implode( '/', $parts );
1523 * Get the base page name title, i.e. the part before the subpage name
1527 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1528 * # returns: Title{User:Foo/Bar}
1531 * @return Title Base title
1534 public function getBaseTitle() {
1535 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1539 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1543 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1547 * @return string Subpage name
1549 public function getSubpageText() {
1550 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1551 return $this->mTextform
;
1553 $parts = explode( '/', $this->mTextform
);
1554 return $parts[count( $parts ) - 1];
1558 * Get the title for a subpage of the current page
1562 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1563 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1566 * @param string $text The subpage name to add to the title
1567 * @return Title Subpage title
1570 public function getSubpage( $text ) {
1571 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1575 * Get a URL-encoded form of the subpage text
1577 * @return string URL-encoded subpage name
1579 public function getSubpageUrlForm() {
1580 $text = $this->getSubpageText();
1581 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1586 * Get a URL-encoded title (not an actual URL) including interwiki
1588 * @return string The URL-encoded form
1590 public function getPrefixedURL() {
1591 $s = $this->prefix( $this->mDbkeyform
);
1592 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1597 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1598 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1599 * second argument named variant. This was deprecated in favor
1600 * of passing an array of option with a "variant" key
1601 * Once $query2 is removed for good, this helper can be dropped
1602 * and the wfArrayToCgi moved to getLocalURL();
1604 * @since 1.19 (r105919)
1605 * @param array|string $query
1606 * @param bool $query2
1609 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1610 if ( $query2 !== false ) {
1611 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1612 "method called with a second parameter is deprecated. Add your " .
1613 "parameter to an array passed as the first parameter.", "1.19" );
1615 if ( is_array( $query ) ) {
1616 $query = wfArrayToCgi( $query );
1619 if ( is_string( $query2 ) ) {
1620 // $query2 is a string, we will consider this to be
1621 // a deprecated $variant argument and add it to the query
1622 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1624 $query2 = wfArrayToCgi( $query2 );
1626 // If we have $query content add a & to it first
1630 // Now append the queries together
1637 * Get a real URL referring to this title, with interwiki link and
1640 * @see self::getLocalURL for the arguments.
1642 * @param array|string $query
1643 * @param bool $query2
1644 * @param string $proto Protocol type to use in URL
1645 * @return string The URL
1647 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1648 $query = self
::fixUrlQueryArgs( $query, $query2 );
1650 # Hand off all the decisions on urls to getLocalURL
1651 $url = $this->getLocalURL( $query );
1653 # Expand the url to make it a full url. Note that getLocalURL has the
1654 # potential to output full urls for a variety of reasons, so we use
1655 # wfExpandUrl instead of simply prepending $wgServer
1656 $url = wfExpandUrl( $url, $proto );
1658 # Finally, add the fragment.
1659 $url .= $this->getFragmentForURL();
1661 Hooks
::run( 'GetFullURL', [ &$this, &$url, $query ] );
1666 * Get a URL with no fragment or server name (relative URL) from a Title object.
1667 * If this page is generated with action=render, however,
1668 * $wgServer is prepended to make an absolute URL.
1670 * @see self::getFullURL to always get an absolute URL.
1671 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1672 * valid to link, locally, to the current Title.
1673 * @see self::newFromText to produce a Title object.
1675 * @param string|array $query An optional query string,
1676 * not used for interwiki links. Can be specified as an associative array as well,
1677 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1678 * Some query patterns will trigger various shorturl path replacements.
1679 * @param array $query2 An optional secondary query array. This one MUST
1680 * be an array. If a string is passed it will be interpreted as a deprecated
1681 * variant argument and urlencoded into a variant= argument.
1682 * This second query argument will be added to the $query
1683 * The second parameter is deprecated since 1.19. Pass it as a key,value
1684 * pair in the first parameter array instead.
1686 * @return string String of the URL.
1688 public function getLocalURL( $query = '', $query2 = false ) {
1689 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1691 $query = self
::fixUrlQueryArgs( $query, $query2 );
1693 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1695 $namespace = $this->getNsText();
1696 if ( $namespace != '' ) {
1697 # Can this actually happen? Interwikis shouldn't be parsed.
1698 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1701 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1702 $url = wfAppendQuery( $url, $query );
1704 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1705 if ( $query == '' ) {
1706 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1707 Hooks
::run( 'GetLocalURL::Article', [ &$this, &$url ] );
1709 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1713 if ( !empty( $wgActionPaths )
1714 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1716 $action = urldecode( $matches[2] );
1717 if ( isset( $wgActionPaths[$action] ) ) {
1718 $query = $matches[1];
1719 if ( isset( $matches[4] ) ) {
1720 $query .= $matches[4];
1722 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1723 if ( $query != '' ) {
1724 $url = wfAppendQuery( $url, $query );
1730 && $wgVariantArticlePath
1731 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1732 && $this->getPageLanguage()->equals( $wgContLang )
1733 && $this->getPageLanguage()->hasVariants()
1735 $variant = urldecode( $matches[1] );
1736 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1737 // Only do the variant replacement if the given variant is a valid
1738 // variant for the page's language.
1739 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1740 $url = str_replace( '$1', $dbkey, $url );
1744 if ( $url === false ) {
1745 if ( $query == '-' ) {
1748 $url = "{$wgScript}?title={$dbkey}&{$query}";
1752 Hooks
::run( 'GetLocalURL::Internal', [ &$this, &$url, $query ] );
1754 // @todo FIXME: This causes breakage in various places when we
1755 // actually expected a local URL and end up with dupe prefixes.
1756 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1757 $url = $wgServer . $url;
1760 Hooks
::run( 'GetLocalURL', [ &$this, &$url, $query ] );
1765 * Get a URL that's the simplest URL that will be valid to link, locally,
1766 * to the current Title. It includes the fragment, but does not include
1767 * the server unless action=render is used (or the link is external). If
1768 * there's a fragment but the prefixed text is empty, we just return a link
1771 * The result obviously should not be URL-escaped, but does need to be
1772 * HTML-escaped if it's being output in HTML.
1774 * @param array $query
1775 * @param bool $query2
1776 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1777 * or false (default) for no expansion
1778 * @see self::getLocalURL for the arguments.
1779 * @return string The URL
1781 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1782 if ( $this->isExternal() ||
$proto !== false ) {
1783 $ret = $this->getFullURL( $query, $query2, $proto );
1784 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1785 $ret = $this->getFragmentForURL();
1787 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1793 * Get the URL form for an internal link.
1794 * - Used in various CDN-related code, in case we have a different
1795 * internal hostname for the server from the exposed one.
1797 * This uses $wgInternalServer to qualify the path, or $wgServer
1798 * if $wgInternalServer is not set. If the server variable used is
1799 * protocol-relative, the URL will be expanded to http://
1801 * @see self::getLocalURL for the arguments.
1802 * @return string The URL
1804 public function getInternalURL( $query = '', $query2 = false ) {
1805 global $wgInternalServer, $wgServer;
1806 $query = self
::fixUrlQueryArgs( $query, $query2 );
1807 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1808 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1809 Hooks
::run( 'GetInternalURL', [ &$this, &$url, $query ] );
1814 * Get the URL for a canonical link, for use in things like IRC and
1815 * e-mail notifications. Uses $wgCanonicalServer and the
1816 * GetCanonicalURL hook.
1818 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1820 * @see self::getLocalURL for the arguments.
1821 * @return string The URL
1824 public function getCanonicalURL( $query = '', $query2 = false ) {
1825 $query = self
::fixUrlQueryArgs( $query, $query2 );
1826 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1827 Hooks
::run( 'GetCanonicalURL', [ &$this, &$url, $query ] );
1832 * Get the edit URL for this Title
1834 * @return string The URL, or a null string if this is an interwiki link
1836 public function getEditURL() {
1837 if ( $this->isExternal() ) {
1840 $s = $this->getLocalURL( 'action=edit' );
1846 * Can $user perform $action on this page?
1847 * This skips potentially expensive cascading permission checks
1848 * as well as avoids expensive error formatting
1850 * Suitable for use for nonessential UI controls in common cases, but
1851 * _not_ for functional access control.
1853 * May provide false positives, but should never provide a false negative.
1855 * @param string $action Action that permission needs to be checked for
1856 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1859 public function quickUserCan( $action, $user = null ) {
1860 return $this->userCan( $action, $user, false );
1864 * Can $user perform $action on this page?
1866 * @param string $action Action that permission needs to be checked for
1867 * @param User $user User to check (since 1.19); $wgUser will be used if not
1869 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1872 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1873 if ( !$user instanceof User
) {
1878 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1882 * Can $user perform $action on this page?
1884 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1886 * @param string $action Action that permission needs to be checked for
1887 * @param User $user User to check
1888 * @param string $rigor One of (quick,full,secure)
1889 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1890 * - full : does cheap and expensive checks possibly from a slave
1891 * - secure : does cheap and expensive checks, using the master as needed
1892 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1893 * whose corresponding errors may be ignored.
1894 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1896 public function getUserPermissionsErrors(
1897 $action, $user, $rigor = 'secure', $ignoreErrors = []
1899 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1901 // Remove the errors being ignored.
1902 foreach ( $errors as $index => $error ) {
1903 $errKey = is_array( $error ) ?
$error[0] : $error;
1905 if ( in_array( $errKey, $ignoreErrors ) ) {
1906 unset( $errors[$index] );
1908 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1909 unset( $errors[$index] );
1917 * Permissions checks that fail most often, and which are easiest to test.
1919 * @param string $action The action to check
1920 * @param User $user User to check
1921 * @param array $errors List of current errors
1922 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1923 * @param bool $short Short circuit on first error
1925 * @return array List of errors
1927 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1928 if ( !Hooks
::run( 'TitleQuickPermissions',
1929 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1934 if ( $action == 'create' ) {
1936 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1937 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1939 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1941 } elseif ( $action == 'move' ) {
1942 if ( !$user->isAllowed( 'move-rootuserpages' )
1943 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1944 // Show user page-specific message only if the user can move other pages
1945 $errors[] = [ 'cant-move-user-page' ];
1948 // Check if user is allowed to move files if it's a file
1949 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1950 $errors[] = [ 'movenotallowedfile' ];
1953 // Check if user is allowed to move category pages if it's a category page
1954 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1955 $errors[] = [ 'cant-move-category-page' ];
1958 if ( !$user->isAllowed( 'move' ) ) {
1959 // User can't move anything
1960 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1961 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1962 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1963 // custom message if logged-in users without any special rights can move
1964 $errors[] = [ 'movenologintext' ];
1966 $errors[] = [ 'movenotallowed' ];
1969 } elseif ( $action == 'move-target' ) {
1970 if ( !$user->isAllowed( 'move' ) ) {
1971 // User can't move anything
1972 $errors[] = [ 'movenotallowed' ];
1973 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1974 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1975 // Show user page-specific message only if the user can move other pages
1976 $errors[] = [ 'cant-move-to-user-page' ];
1977 } elseif ( !$user->isAllowed( 'move-categorypages' )
1978 && $this->mNamespace
== NS_CATEGORY
) {
1979 // Show category page-specific message only if the user can move other pages
1980 $errors[] = [ 'cant-move-to-category-page' ];
1982 } elseif ( !$user->isAllowed( $action ) ) {
1983 $errors[] = $this->missingPermissionError( $action, $short );
1990 * Add the resulting error code to the errors array
1992 * @param array $errors List of current errors
1993 * @param array $result Result of errors
1995 * @return array List of errors
1997 private function resultToError( $errors, $result ) {
1998 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1999 // A single array representing an error
2000 $errors[] = $result;
2001 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2002 // A nested array representing multiple errors
2003 $errors = array_merge( $errors, $result );
2004 } elseif ( $result !== '' && is_string( $result ) ) {
2005 // A string representing a message-id
2006 $errors[] = [ $result ];
2007 } elseif ( $result instanceof MessageSpecifier
) {
2008 // A message specifier representing an error
2009 $errors[] = [ $result ];
2010 } elseif ( $result === false ) {
2011 // a generic "We don't want them to do that"
2012 $errors[] = [ 'badaccess-group0' ];
2018 * Check various permission hooks
2020 * @param string $action The action to check
2021 * @param User $user User to check
2022 * @param array $errors List of current errors
2023 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2024 * @param bool $short Short circuit on first error
2026 * @return array List of errors
2028 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2029 // Use getUserPermissionsErrors instead
2031 if ( !Hooks
::run( 'userCan', [ &$this, &$user, $action, &$result ] ) ) {
2032 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2034 // Check getUserPermissionsErrors hook
2035 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$this, &$user, $action, &$result ] ) ) {
2036 $errors = $this->resultToError( $errors, $result );
2038 // Check getUserPermissionsErrorsExpensive hook
2041 && !( $short && count( $errors ) > 0 )
2042 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$this, &$user, $action, &$result ] )
2044 $errors = $this->resultToError( $errors, $result );
2051 * Check permissions on special pages & namespaces
2053 * @param string $action The action to check
2054 * @param User $user User to check
2055 * @param array $errors List of current errors
2056 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2057 * @param bool $short Short circuit on first error
2059 * @return array List of errors
2061 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2062 # Only 'createaccount' can be performed on special pages,
2063 # which don't actually exist in the DB.
2064 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2065 $errors[] = [ 'ns-specialprotected' ];
2068 # Check $wgNamespaceProtection for restricted namespaces
2069 if ( $this->isNamespaceProtected( $user ) ) {
2070 $ns = $this->mNamespace
== NS_MAIN ?
2071 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2072 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2073 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2080 * Check CSS/JS sub-page permissions
2082 * @param string $action The action to check
2083 * @param User $user User to check
2084 * @param array $errors List of current errors
2085 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2086 * @param bool $short Short circuit on first error
2088 * @return array List of errors
2090 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2091 # Protect css/js subpages of user pages
2092 # XXX: this might be better using restrictions
2093 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2094 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2095 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2096 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2097 $errors[] = [ 'mycustomcssprotected', $action ];
2098 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2099 $errors[] = [ 'mycustomjsprotected', $action ];
2102 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2103 $errors[] = [ 'customcssprotected', $action ];
2104 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2105 $errors[] = [ 'customjsprotected', $action ];
2114 * Check against page_restrictions table requirements on this
2115 * page. The user must possess all required rights for this
2118 * @param string $action The action to check
2119 * @param User $user User to check
2120 * @param array $errors List of current errors
2121 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2122 * @param bool $short Short circuit on first error
2124 * @return array List of errors
2126 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2127 foreach ( $this->getRestrictions( $action ) as $right ) {
2128 // Backwards compatibility, rewrite sysop -> editprotected
2129 if ( $right == 'sysop' ) {
2130 $right = 'editprotected';
2132 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2133 if ( $right == 'autoconfirmed' ) {
2134 $right = 'editsemiprotected';
2136 if ( $right == '' ) {
2139 if ( !$user->isAllowed( $right ) ) {
2140 $errors[] = [ 'protectedpagetext', $right, $action ];
2141 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2142 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2150 * Check restrictions on cascading pages.
2152 * @param string $action The action to check
2153 * @param User $user User to check
2154 * @param array $errors List of current errors
2155 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2156 * @param bool $short Short circuit on first error
2158 * @return array List of errors
2160 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2161 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2162 # We /could/ use the protection level on the source page, but it's
2163 # fairly ugly as we have to establish a precedence hierarchy for pages
2164 # included by multiple cascade-protected pages. So just restrict
2165 # it to people with 'protect' permission, as they could remove the
2166 # protection anyway.
2167 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2168 # Cascading protection depends on more than this page...
2169 # Several cascading protected pages may include this page...
2170 # Check each cascading level
2171 # This is only for protection restrictions, not for all actions
2172 if ( isset( $restrictions[$action] ) ) {
2173 foreach ( $restrictions[$action] as $right ) {
2174 // Backwards compatibility, rewrite sysop -> editprotected
2175 if ( $right == 'sysop' ) {
2176 $right = 'editprotected';
2178 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2179 if ( $right == 'autoconfirmed' ) {
2180 $right = 'editsemiprotected';
2182 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2184 foreach ( $cascadingSources as $page ) {
2185 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2187 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2197 * Check action permissions not already checked in checkQuickPermissions
2199 * @param string $action The action to check
2200 * @param User $user User to check
2201 * @param array $errors List of current errors
2202 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2203 * @param bool $short Short circuit on first error
2205 * @return array List of errors
2207 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2208 global $wgDeleteRevisionsLimit, $wgLang;
2210 if ( $action == 'protect' ) {
2211 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2212 // If they can't edit, they shouldn't protect.
2213 $errors[] = [ 'protect-cantedit' ];
2215 } elseif ( $action == 'create' ) {
2216 $title_protection = $this->getTitleProtection();
2217 if ( $title_protection ) {
2218 if ( $title_protection['permission'] == ''
2219 ||
!$user->isAllowed( $title_protection['permission'] )
2223 User
::whoIs( $title_protection['user'] ),
2224 $title_protection['reason']
2228 } elseif ( $action == 'move' ) {
2229 // Check for immobile pages
2230 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2231 // Specific message for this case
2232 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2233 } elseif ( !$this->isMovable() ) {
2234 // Less specific message for rarer cases
2235 $errors[] = [ 'immobile-source-page' ];
2237 } elseif ( $action == 'move-target' ) {
2238 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2239 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2240 } elseif ( !$this->isMovable() ) {
2241 $errors[] = [ 'immobile-target-page' ];
2243 } elseif ( $action == 'delete' ) {
2244 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2245 if ( !$tempErrors ) {
2246 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2247 $user, $tempErrors, $rigor, true );
2249 if ( $tempErrors ) {
2250 // If protection keeps them from editing, they shouldn't be able to delete.
2251 $errors[] = [ 'deleteprotected' ];
2253 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2254 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2256 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2263 * Check that the user isn't blocked from editing.
2265 * @param string $action The action to check
2266 * @param User $user User to check
2267 * @param array $errors List of current errors
2268 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2269 * @param bool $short Short circuit on first error
2271 * @return array List of errors
2273 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2274 // Account creation blocks handled at userlogin.
2275 // Unblocking handled in SpecialUnblock
2276 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2280 global $wgEmailConfirmToEdit;
2282 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2283 $errors[] = [ 'confirmedittext' ];
2286 $useSlave = ( $rigor !== 'secure' );
2287 if ( ( $action == 'edit' ||
$action == 'create' )
2288 && !$user->isBlockedFrom( $this, $useSlave )
2290 // Don't block the user from editing their own talk page unless they've been
2291 // explicitly blocked from that too.
2292 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2293 // @todo FIXME: Pass the relevant context into this function.
2294 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2301 * Check that the user is allowed to read this page.
2303 * @param string $action The action to check
2304 * @param User $user User to check
2305 * @param array $errors List of current errors
2306 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2307 * @param bool $short Short circuit on first error
2309 * @return array List of errors
2311 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2312 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2314 $whitelisted = false;
2315 if ( User
::isEveryoneAllowed( 'read' ) ) {
2316 # Shortcut for public wikis, allows skipping quite a bit of code
2317 $whitelisted = true;
2318 } elseif ( $user->isAllowed( 'read' ) ) {
2319 # If the user is allowed to read pages, he is allowed to read all pages
2320 $whitelisted = true;
2321 } elseif ( $this->isSpecial( 'Userlogin' )
2322 ||
$this->isSpecial( 'PasswordReset' )
2323 ||
$this->isSpecial( 'Userlogout' )
2325 # Always grant access to the login page.
2326 # Even anons need to be able to log in.
2327 $whitelisted = true;
2328 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2329 # Time to check the whitelist
2330 # Only do these checks is there's something to check against
2331 $name = $this->getPrefixedText();
2332 $dbName = $this->getPrefixedDBkey();
2334 // Check for explicit whitelisting with and without underscores
2335 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2336 $whitelisted = true;
2337 } elseif ( $this->getNamespace() == NS_MAIN
) {
2338 # Old settings might have the title prefixed with
2339 # a colon for main-namespace pages
2340 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2341 $whitelisted = true;
2343 } elseif ( $this->isSpecialPage() ) {
2344 # If it's a special page, ditch the subpage bit and check again
2345 $name = $this->getDBkey();
2346 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2348 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2349 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2350 $whitelisted = true;
2356 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2357 $name = $this->getPrefixedText();
2358 // Check for regex whitelisting
2359 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2360 if ( preg_match( $listItem, $name ) ) {
2361 $whitelisted = true;
2367 if ( !$whitelisted ) {
2368 # If the title is not whitelisted, give extensions a chance to do so...
2369 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2370 if ( !$whitelisted ) {
2371 $errors[] = $this->missingPermissionError( $action, $short );
2379 * Get a description array when the user doesn't have the right to perform
2380 * $action (i.e. when User::isAllowed() returns false)
2382 * @param string $action The action to check
2383 * @param bool $short Short circuit on first error
2384 * @return array List of errors
2386 private function missingPermissionError( $action, $short ) {
2387 // We avoid expensive display logic for quickUserCan's and such
2389 return [ 'badaccess-group0' ];
2392 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2393 User
::getGroupsWithPermission( $action ) );
2395 if ( count( $groups ) ) {
2399 $wgLang->commaList( $groups ),
2403 return [ 'badaccess-group0' ];
2408 * Can $user perform $action on this page? This is an internal function,
2409 * with multiple levels of checks depending on performance needs; see $rigor below.
2410 * It does not check wfReadOnly().
2412 * @param string $action Action that permission needs to be checked for
2413 * @param User $user User to check
2414 * @param string $rigor One of (quick,full,secure)
2415 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2416 * - full : does cheap and expensive checks possibly from a slave
2417 * - secure : does cheap and expensive checks, using the master as needed
2418 * @param bool $short Set this to true to stop after the first permission error.
2419 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2421 protected function getUserPermissionsErrorsInternal(
2422 $action, $user, $rigor = 'secure', $short = false
2424 if ( $rigor === true ) {
2425 $rigor = 'secure'; // b/c
2426 } elseif ( $rigor === false ) {
2427 $rigor = 'quick'; // b/c
2428 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2429 throw new Exception( "Invalid rigor parameter '$rigor'." );
2432 # Read has special handling
2433 if ( $action == 'read' ) {
2435 'checkPermissionHooks',
2436 'checkReadPermissions',
2438 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2439 # here as it will lead to duplicate error messages. This is okay to do
2440 # since anywhere that checks for create will also check for edit, and
2441 # those checks are called for edit.
2442 } elseif ( $action == 'create' ) {
2444 'checkQuickPermissions',
2445 'checkPermissionHooks',
2446 'checkPageRestrictions',
2447 'checkCascadingSourcesRestrictions',
2448 'checkActionPermissions',
2453 'checkQuickPermissions',
2454 'checkPermissionHooks',
2455 'checkSpecialsAndNSPermissions',
2456 'checkCSSandJSPermissions',
2457 'checkPageRestrictions',
2458 'checkCascadingSourcesRestrictions',
2459 'checkActionPermissions',
2465 while ( count( $checks ) > 0 &&
2466 !( $short && count( $errors ) > 0 ) ) {
2467 $method = array_shift( $checks );
2468 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2475 * Get a filtered list of all restriction types supported by this wiki.
2476 * @param bool $exists True to get all restriction types that apply to
2477 * titles that do exist, False for all restriction types that apply to
2478 * titles that do not exist
2481 public static function getFilteredRestrictionTypes( $exists = true ) {
2482 global $wgRestrictionTypes;
2483 $types = $wgRestrictionTypes;
2485 # Remove the create restriction for existing titles
2486 $types = array_diff( $types, [ 'create' ] );
2488 # Only the create and upload restrictions apply to non-existing titles
2489 $types = array_intersect( $types, [ 'create', 'upload' ] );
2495 * Returns restriction types for the current Title
2497 * @return array Applicable restriction types
2499 public function getRestrictionTypes() {
2500 if ( $this->isSpecialPage() ) {
2504 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2506 if ( $this->getNamespace() != NS_FILE
) {
2507 # Remove the upload restriction for non-file titles
2508 $types = array_diff( $types, [ 'upload' ] );
2511 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2513 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2514 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2520 * Is this title subject to title protection?
2521 * Title protection is the one applied against creation of such title.
2523 * @return array|bool An associative array representing any existent title
2524 * protection, or false if there's none.
2526 public function getTitleProtection() {
2527 // Can't protect pages in special namespaces
2528 if ( $this->getNamespace() < 0 ) {
2532 // Can't protect pages that exist.
2533 if ( $this->exists() ) {
2537 if ( $this->mTitleProtection
=== null ) {
2538 $dbr = wfGetDB( DB_SLAVE
);
2539 $res = $dbr->select(
2542 'user' => 'pt_user',
2543 'reason' => 'pt_reason',
2544 'expiry' => 'pt_expiry',
2545 'permission' => 'pt_create_perm'
2547 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2551 // fetchRow returns false if there are no rows.
2552 $row = $dbr->fetchRow( $res );
2554 if ( $row['permission'] == 'sysop' ) {
2555 $row['permission'] = 'editprotected'; // B/C
2557 if ( $row['permission'] == 'autoconfirmed' ) {
2558 $row['permission'] = 'editsemiprotected'; // B/C
2560 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2562 $this->mTitleProtection
= $row;
2564 return $this->mTitleProtection
;
2568 * Remove any title protection due to page existing
2570 public function deleteTitleProtection() {
2571 $dbw = wfGetDB( DB_MASTER
);
2575 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2578 $this->mTitleProtection
= false;
2582 * Is this page "semi-protected" - the *only* protection levels are listed
2583 * in $wgSemiprotectedRestrictionLevels?
2585 * @param string $action Action to check (default: edit)
2588 public function isSemiProtected( $action = 'edit' ) {
2589 global $wgSemiprotectedRestrictionLevels;
2591 $restrictions = $this->getRestrictions( $action );
2592 $semi = $wgSemiprotectedRestrictionLevels;
2593 if ( !$restrictions ||
!$semi ) {
2594 // Not protected, or all protection is full protection
2598 // Remap autoconfirmed to editsemiprotected for BC
2599 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2600 $semi[$key] = 'editsemiprotected';
2602 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2603 $restrictions[$key] = 'editsemiprotected';
2606 return !array_diff( $restrictions, $semi );
2610 * Does the title correspond to a protected article?
2612 * @param string $action The action the page is protected from,
2613 * by default checks all actions.
2616 public function isProtected( $action = '' ) {
2617 global $wgRestrictionLevels;
2619 $restrictionTypes = $this->getRestrictionTypes();
2621 # Special pages have inherent protection
2622 if ( $this->isSpecialPage() ) {
2626 # Check regular protection levels
2627 foreach ( $restrictionTypes as $type ) {
2628 if ( $action == $type ||
$action == '' ) {
2629 $r = $this->getRestrictions( $type );
2630 foreach ( $wgRestrictionLevels as $level ) {
2631 if ( in_array( $level, $r ) && $level != '' ) {
2642 * Determines if $user is unable to edit this page because it has been protected
2643 * by $wgNamespaceProtection.
2645 * @param User $user User object to check permissions
2648 public function isNamespaceProtected( User
$user ) {
2649 global $wgNamespaceProtection;
2651 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2652 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2653 if ( $right != '' && !$user->isAllowed( $right ) ) {
2662 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2664 * @return bool If the page is subject to cascading restrictions.
2666 public function isCascadeProtected() {
2667 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2668 return ( $sources > 0 );
2672 * Determines whether cascading protection sources have already been loaded from
2675 * @param bool $getPages True to check if the pages are loaded, or false to check
2676 * if the status is loaded.
2677 * @return bool Whether or not the specified information has been loaded
2680 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2681 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2685 * Cascading protection: Get the source of any cascading restrictions on this page.
2687 * @param bool $getPages Whether or not to retrieve the actual pages
2688 * that the restrictions have come from and the actual restrictions
2690 * @return array Two elements: First is an array of Title objects of the
2691 * pages from which cascading restrictions have come, false for
2692 * none, or true if such restrictions exist but $getPages was not
2693 * set. Second is an array like that returned by
2694 * Title::getAllRestrictions(), or an empty array if $getPages is
2697 public function getCascadeProtectionSources( $getPages = true ) {
2698 $pagerestrictions = [];
2700 if ( $this->mCascadeSources
!== null && $getPages ) {
2701 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2702 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2703 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2706 $dbr = wfGetDB( DB_SLAVE
);
2708 if ( $this->getNamespace() == NS_FILE
) {
2709 $tables = [ 'imagelinks', 'page_restrictions' ];
2711 'il_to' => $this->getDBkey(),
2716 $tables = [ 'templatelinks', 'page_restrictions' ];
2718 'tl_namespace' => $this->getNamespace(),
2719 'tl_title' => $this->getDBkey(),
2726 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2727 'pr_expiry', 'pr_type', 'pr_level' ];
2728 $where_clauses[] = 'page_id=pr_page';
2731 $cols = [ 'pr_expiry' ];
2734 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2736 $sources = $getPages ?
[] : false;
2737 $now = wfTimestampNow();
2739 foreach ( $res as $row ) {
2740 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2741 if ( $expiry > $now ) {
2743 $page_id = $row->pr_page
;
2744 $page_ns = $row->page_namespace
;
2745 $page_title = $row->page_title
;
2746 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2747 # Add groups needed for each restriction type if its not already there
2748 # Make sure this restriction type still exists
2750 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2751 $pagerestrictions[$row->pr_type
] = [];
2755 isset( $pagerestrictions[$row->pr_type
] )
2756 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2758 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2767 $this->mCascadeSources
= $sources;
2768 $this->mCascadingRestrictions
= $pagerestrictions;
2770 $this->mHasCascadingRestrictions
= $sources;
2773 return [ $sources, $pagerestrictions ];
2777 * Accessor for mRestrictionsLoaded
2779 * @return bool Whether or not the page's restrictions have already been
2780 * loaded from the database
2783 public function areRestrictionsLoaded() {
2784 return $this->mRestrictionsLoaded
;
2788 * Accessor/initialisation for mRestrictions
2790 * @param string $action Action that permission needs to be checked for
2791 * @return array Restriction levels needed to take the action. All levels are
2792 * required. Note that restriction levels are normally user rights, but 'sysop'
2793 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2794 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2796 public function getRestrictions( $action ) {
2797 if ( !$this->mRestrictionsLoaded
) {
2798 $this->loadRestrictions();
2800 return isset( $this->mRestrictions
[$action] )
2801 ?
$this->mRestrictions
[$action]
2806 * Accessor/initialisation for mRestrictions
2808 * @return array Keys are actions, values are arrays as returned by
2809 * Title::getRestrictions()
2812 public function getAllRestrictions() {
2813 if ( !$this->mRestrictionsLoaded
) {
2814 $this->loadRestrictions();
2816 return $this->mRestrictions
;
2820 * Get the expiry time for the restriction against a given action
2822 * @param string $action
2823 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2824 * or not protected at all, or false if the action is not recognised.
2826 public function getRestrictionExpiry( $action ) {
2827 if ( !$this->mRestrictionsLoaded
) {
2828 $this->loadRestrictions();
2830 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2834 * Returns cascading restrictions for the current article
2838 function areRestrictionsCascading() {
2839 if ( !$this->mRestrictionsLoaded
) {
2840 $this->loadRestrictions();
2843 return $this->mCascadeRestriction
;
2847 * Loads a string into mRestrictions array
2849 * @param ResultWrapper $res Resource restrictions as an SQL result.
2850 * @param string $oldFashionedRestrictions Comma-separated list of page
2851 * restrictions from page table (pre 1.10)
2853 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2856 foreach ( $res as $row ) {
2860 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2864 * Compiles list of active page restrictions from both page table (pre 1.10)
2865 * and page_restrictions table for this existing page.
2866 * Public for usage by LiquidThreads.
2868 * @param array $rows Array of db result objects
2869 * @param string $oldFashionedRestrictions Comma-separated list of page
2870 * restrictions from page table (pre 1.10)
2872 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2873 $dbr = wfGetDB( DB_SLAVE
);
2875 $restrictionTypes = $this->getRestrictionTypes();
2877 foreach ( $restrictionTypes as $type ) {
2878 $this->mRestrictions
[$type] = [];
2879 $this->mRestrictionsExpiry
[$type] = 'infinity';
2882 $this->mCascadeRestriction
= false;
2884 # Backwards-compatibility: also load the restrictions from the page record (old format).
2885 if ( $oldFashionedRestrictions !== null ) {
2886 $this->mOldRestrictions
= $oldFashionedRestrictions;
2889 if ( $this->mOldRestrictions
=== false ) {
2890 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2891 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2894 if ( $this->mOldRestrictions
!= '' ) {
2895 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2896 $temp = explode( '=', trim( $restrict ) );
2897 if ( count( $temp ) == 1 ) {
2898 // old old format should be treated as edit/move restriction
2899 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2900 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2902 $restriction = trim( $temp[1] );
2903 if ( $restriction != '' ) { // some old entries are empty
2904 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2910 if ( count( $rows ) ) {
2911 # Current system - load second to make them override.
2912 $now = wfTimestampNow();
2914 # Cycle through all the restrictions.
2915 foreach ( $rows as $row ) {
2917 // Don't take care of restrictions types that aren't allowed
2918 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2922 // This code should be refactored, now that it's being used more generally,
2923 // But I don't really see any harm in leaving it in Block for now -werdna
2924 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2926 // Only apply the restrictions if they haven't expired!
2927 if ( !$expiry ||
$expiry > $now ) {
2928 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2929 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2931 $this->mCascadeRestriction |
= $row->pr_cascade
;
2936 $this->mRestrictionsLoaded
= true;
2940 * Load restrictions from the page_restrictions table
2942 * @param string $oldFashionedRestrictions Comma-separated list of page
2943 * restrictions from page table (pre 1.10)
2945 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2946 if ( !$this->mRestrictionsLoaded
) {
2947 $dbr = wfGetDB( DB_SLAVE
);
2948 if ( $this->exists() ) {
2949 $res = $dbr->select(
2950 'page_restrictions',
2951 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2952 [ 'pr_page' => $this->getArticleID() ],
2956 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2958 $title_protection = $this->getTitleProtection();
2960 if ( $title_protection ) {
2961 $now = wfTimestampNow();
2962 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2964 if ( !$expiry ||
$expiry > $now ) {
2965 // Apply the restrictions
2966 $this->mRestrictionsExpiry
['create'] = $expiry;
2967 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
2968 } else { // Get rid of the old restrictions
2969 $this->mTitleProtection
= false;
2972 $this->mRestrictionsExpiry
['create'] = 'infinity';
2974 $this->mRestrictionsLoaded
= true;
2980 * Flush the protection cache in this object and force reload from the database.
2981 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2983 public function flushRestrictions() {
2984 $this->mRestrictionsLoaded
= false;
2985 $this->mTitleProtection
= null;
2989 * Purge expired restrictions from the page_restrictions table
2991 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2993 static function purgeExpiredRestrictions() {
2994 if ( wfReadOnly() ) {
2998 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2999 wfGetDB( DB_MASTER
),
3001 function ( IDatabase
$dbw, $fname ) {
3002 $config = MediaWikiServices
::getInstance()->getMainConfig();
3003 $ids = $dbw->selectFieldValues(
3004 'page_restrictions',
3006 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3008 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3011 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3016 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3017 wfGetDB( DB_MASTER
),
3019 function ( IDatabase
$dbw, $fname ) {
3022 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3030 * Does this have subpages? (Warning, usually requires an extra DB query.)
3034 public function hasSubpages() {
3035 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3040 # We dynamically add a member variable for the purpose of this method
3041 # alone to cache the result. There's no point in having it hanging
3042 # around uninitialized in every Title object; therefore we only add it
3043 # if needed and don't declare it statically.
3044 if ( $this->mHasSubpages
=== null ) {
3045 $this->mHasSubpages
= false;
3046 $subpages = $this->getSubpages( 1 );
3047 if ( $subpages instanceof TitleArray
) {
3048 $this->mHasSubpages
= (bool)$subpages->count();
3052 return $this->mHasSubpages
;
3056 * Get all subpages of this page.
3058 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3059 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3060 * doesn't allow subpages
3062 public function getSubpages( $limit = -1 ) {
3063 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3067 $dbr = wfGetDB( DB_SLAVE
);
3068 $conds['page_namespace'] = $this->getNamespace();
3069 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3071 if ( $limit > -1 ) {
3072 $options['LIMIT'] = $limit;
3074 $this->mSubpages
= TitleArray
::newFromResult(
3075 $dbr->select( 'page',
3076 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3082 return $this->mSubpages
;
3086 * Is there a version of this page in the deletion archive?
3088 * @return int The number of archived revisions
3090 public function isDeleted() {
3091 if ( $this->getNamespace() < 0 ) {
3094 $dbr = wfGetDB( DB_SLAVE
);
3096 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3097 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3100 if ( $this->getNamespace() == NS_FILE
) {
3101 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3102 [ 'fa_name' => $this->getDBkey() ],
3111 * Is there a version of this page in the deletion archive?
3115 public function isDeletedQuick() {
3116 if ( $this->getNamespace() < 0 ) {
3119 $dbr = wfGetDB( DB_SLAVE
);
3120 $deleted = (bool)$dbr->selectField( 'archive', '1',
3121 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3124 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3125 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3126 [ 'fa_name' => $this->getDBkey() ],
3134 * Get the article ID for this Title from the link cache,
3135 * adding it if necessary
3137 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3139 * @return int The ID
3141 public function getArticleID( $flags = 0 ) {
3142 if ( $this->getNamespace() < 0 ) {
3143 $this->mArticleID
= 0;
3144 return $this->mArticleID
;
3146 $linkCache = LinkCache
::singleton();
3147 if ( $flags & self
::GAID_FOR_UPDATE
) {
3148 $oldUpdate = $linkCache->forUpdate( true );
3149 $linkCache->clearLink( $this );
3150 $this->mArticleID
= $linkCache->addLinkObj( $this );
3151 $linkCache->forUpdate( $oldUpdate );
3153 if ( -1 == $this->mArticleID
) {
3154 $this->mArticleID
= $linkCache->addLinkObj( $this );
3157 return $this->mArticleID
;
3161 * Is this an article that is a redirect page?
3162 * Uses link cache, adding it if necessary
3164 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3167 public function isRedirect( $flags = 0 ) {
3168 if ( !is_null( $this->mRedirect
) ) {
3169 return $this->mRedirect
;
3171 if ( !$this->getArticleID( $flags ) ) {
3172 $this->mRedirect
= false;
3173 return $this->mRedirect
;
3176 $linkCache = LinkCache
::singleton();
3177 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3178 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3179 if ( $cached === null ) {
3180 # Trust LinkCache's state over our own
3181 # LinkCache is telling us that the page doesn't exist, despite there being cached
3182 # data relating to an existing page in $this->mArticleID. Updaters should clear
3183 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3184 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3185 # LinkCache to refresh its data from the master.
3186 $this->mRedirect
= false;
3187 return $this->mRedirect
;
3190 $this->mRedirect
= (bool)$cached;
3192 return $this->mRedirect
;
3196 * What is the length of this page?
3197 * Uses link cache, adding it if necessary
3199 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3202 public function getLength( $flags = 0 ) {
3203 if ( $this->mLength
!= -1 ) {
3204 return $this->mLength
;
3206 if ( !$this->getArticleID( $flags ) ) {
3208 return $this->mLength
;
3210 $linkCache = LinkCache
::singleton();
3211 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3212 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3213 if ( $cached === null ) {
3214 # Trust LinkCache's state over our own, as for isRedirect()
3216 return $this->mLength
;
3219 $this->mLength
= intval( $cached );
3221 return $this->mLength
;
3225 * What is the page_latest field for this page?
3227 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3228 * @return int Int or 0 if the page doesn't exist
3230 public function getLatestRevID( $flags = 0 ) {
3231 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3232 return intval( $this->mLatestID
);
3234 if ( !$this->getArticleID( $flags ) ) {
3235 $this->mLatestID
= 0;
3236 return $this->mLatestID
;
3238 $linkCache = LinkCache
::singleton();
3239 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3240 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3241 if ( $cached === null ) {
3242 # Trust LinkCache's state over our own, as for isRedirect()
3243 $this->mLatestID
= 0;
3244 return $this->mLatestID
;
3247 $this->mLatestID
= intval( $cached );
3249 return $this->mLatestID
;
3253 * This clears some fields in this object, and clears any associated
3254 * keys in the "bad links" section of the link cache.
3256 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3257 * loading of the new page_id. It's also called from
3258 * WikiPage::doDeleteArticleReal()
3260 * @param int $newid The new Article ID
3262 public function resetArticleID( $newid ) {
3263 $linkCache = LinkCache
::singleton();
3264 $linkCache->clearLink( $this );
3266 if ( $newid === false ) {
3267 $this->mArticleID
= -1;
3269 $this->mArticleID
= intval( $newid );
3271 $this->mRestrictionsLoaded
= false;
3272 $this->mRestrictions
= [];
3273 $this->mOldRestrictions
= false;
3274 $this->mRedirect
= null;
3275 $this->mLength
= -1;
3276 $this->mLatestID
= false;
3277 $this->mContentModel
= false;
3278 $this->mEstimateRevisions
= null;
3279 $this->mPageLanguage
= false;
3280 $this->mDbPageLanguage
= false;
3281 $this->mIsBigDeletion
= null;
3284 public static function clearCaches() {
3285 $linkCache = LinkCache
::singleton();
3286 $linkCache->clear();
3288 $titleCache = self
::getTitleCache();
3289 $titleCache->clear();
3293 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3295 * @param string $text Containing title to capitalize
3296 * @param int $ns Namespace index, defaults to NS_MAIN
3297 * @return string Containing capitalized title
3299 public static function capitalize( $text, $ns = NS_MAIN
) {
3302 if ( MWNamespace
::isCapitalized( $ns ) ) {
3303 return $wgContLang->ucfirst( $text );
3310 * Secure and split - main initialisation function for this object
3312 * Assumes that mDbkeyform has been set, and is urldecoded
3313 * and uses underscores, but not otherwise munged. This function
3314 * removes illegal characters, splits off the interwiki and
3315 * namespace prefixes, sets the other forms, and canonicalizes
3318 * @throws MalformedTitleException On invalid titles
3319 * @return bool True on success
3321 private function secureAndSplit() {
3323 $this->mInterwiki
= '';
3324 $this->mFragment
= '';
3325 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3327 $dbkey = $this->mDbkeyform
;
3329 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3330 // the parsing code with Title, while avoiding massive refactoring.
3331 // @todo: get rid of secureAndSplit, refactor parsing code.
3332 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3333 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3334 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3335 // MalformedTitleException can be thrown here
3336 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3339 $this->setFragment( '#' . $parts['fragment'] );
3340 $this->mInterwiki
= $parts['interwiki'];
3341 $this->mLocalInterwiki
= $parts['local_interwiki'];
3342 $this->mNamespace
= $parts['namespace'];
3343 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3345 $this->mDbkeyform
= $parts['dbkey'];
3346 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3347 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3349 # We already know that some pages won't be in the database!
3350 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3351 $this->mArticleID
= 0;
3358 * Get an array of Title objects linking to this Title
3359 * Also stores the IDs in the link cache.
3361 * WARNING: do not use this function on arbitrary user-supplied titles!
3362 * On heavily-used templates it will max out the memory.
3364 * @param array $options May be FOR UPDATE
3365 * @param string $table Table name
3366 * @param string $prefix Fields prefix
3367 * @return Title[] Array of Title objects linking here
3369 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3370 if ( count( $options ) > 0 ) {
3371 $db = wfGetDB( DB_MASTER
);
3373 $db = wfGetDB( DB_SLAVE
);
3378 self
::getSelectFields(),
3380 "{$prefix}_from=page_id",
3381 "{$prefix}_namespace" => $this->getNamespace(),
3382 "{$prefix}_title" => $this->getDBkey() ],
3388 if ( $res->numRows() ) {
3389 $linkCache = LinkCache
::singleton();
3390 foreach ( $res as $row ) {
3391 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3393 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3394 $retVal[] = $titleObj;
3402 * Get an array of Title objects using this Title as a template
3403 * Also stores the IDs in the link cache.
3405 * WARNING: do not use this function on arbitrary user-supplied titles!
3406 * On heavily-used templates it will max out the memory.
3408 * @param array $options Query option to Database::select()
3409 * @return Title[] Array of Title the Title objects linking here
3411 public function getTemplateLinksTo( $options = [] ) {
3412 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3416 * Get an array of Title objects linked from this Title
3417 * Also stores the IDs in the link cache.
3419 * WARNING: do not use this function on arbitrary user-supplied titles!
3420 * On heavily-used templates it will max out the memory.
3422 * @param array $options Query option to Database::select()
3423 * @param string $table Table name
3424 * @param string $prefix Fields prefix
3425 * @return array Array of Title objects linking here
3427 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3428 $id = $this->getArticleID();
3430 # If the page doesn't exist; there can't be any link from this page
3435 $db = wfGetDB( DB_SLAVE
);
3437 $blNamespace = "{$prefix}_namespace";
3438 $blTitle = "{$prefix}_title";
3443 [ $blNamespace, $blTitle ],
3444 WikiPage
::selectFields()
3446 [ "{$prefix}_from" => $id ],
3451 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3456 $linkCache = LinkCache
::singleton();
3457 foreach ( $res as $row ) {
3458 if ( $row->page_id
) {
3459 $titleObj = Title
::newFromRow( $row );
3461 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3462 $linkCache->addBadLinkObj( $titleObj );
3464 $retVal[] = $titleObj;
3471 * Get an array of Title objects used on this Title as a template
3472 * Also stores the IDs in the link cache.
3474 * WARNING: do not use this function on arbitrary user-supplied titles!
3475 * On heavily-used templates it will max out the memory.
3477 * @param array $options May be FOR UPDATE
3478 * @return Title[] Array of Title the Title objects used here
3480 public function getTemplateLinksFrom( $options = [] ) {
3481 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3485 * Get an array of Title objects referring to non-existent articles linked
3488 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3489 * should use redirect table in this case).
3490 * @return Title[] Array of Title the Title objects
3492 public function getBrokenLinksFrom() {
3493 if ( $this->getArticleID() == 0 ) {
3494 # All links from article ID 0 are false positives
3498 $dbr = wfGetDB( DB_SLAVE
);
3499 $res = $dbr->select(
3500 [ 'page', 'pagelinks' ],
3501 [ 'pl_namespace', 'pl_title' ],
3503 'pl_from' => $this->getArticleID(),
3504 'page_namespace IS NULL'
3510 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3516 foreach ( $res as $row ) {
3517 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3523 * Get a list of URLs to purge from the CDN cache when this
3526 * @return string[] Array of String the URLs
3528 public function getCdnUrls() {
3530 $this->getInternalURL(),
3531 $this->getInternalURL( 'action=history' )
3534 $pageLang = $this->getPageLanguage();
3535 if ( $pageLang->hasVariants() ) {
3536 $variants = $pageLang->getVariants();
3537 foreach ( $variants as $vCode ) {
3538 $urls[] = $this->getInternalURL( $vCode );
3542 // If we are looking at a css/js user subpage, purge the action=raw.
3543 if ( $this->isJsSubpage() ) {
3544 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3545 } elseif ( $this->isCssSubpage() ) {
3546 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3549 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3554 * @deprecated since 1.27 use getCdnUrls()
3556 public function getSquidURLs() {
3557 return $this->getCdnUrls();
3561 * Purge all applicable CDN URLs
3563 public function purgeSquid() {
3564 DeferredUpdates
::addUpdate(
3565 new CdnCacheUpdate( $this->getCdnUrls() ),
3566 DeferredUpdates
::PRESEND
3571 * Move this page without authentication
3573 * @deprecated since 1.25 use MovePage class instead
3574 * @param Title $nt The new page Title
3575 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3577 public function moveNoAuth( &$nt ) {
3578 wfDeprecated( __METHOD__
, '1.25' );
3579 return $this->moveTo( $nt, false );
3583 * Check whether a given move operation would be valid.
3584 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3586 * @deprecated since 1.25, use MovePage's methods instead
3587 * @param Title $nt The new title
3588 * @param bool $auth Whether to check user permissions (uses $wgUser)
3589 * @param string $reason Is the log summary of the move, used for spam checking
3590 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3592 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3595 if ( !( $nt instanceof Title
) ) {
3596 // Normally we'd add this to $errors, but we'll get
3597 // lots of syntax errors if $nt is not an object
3598 return [ [ 'badtitletext' ] ];
3601 $mp = new MovePage( $this, $nt );
3602 $errors = $mp->isValidMove()->getErrorsArray();
3604 $errors = wfMergeErrorArrays(
3606 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3610 return $errors ?
: true;
3614 * Check if the requested move target is a valid file move target
3615 * @todo move this to MovePage
3616 * @param Title $nt Target title
3617 * @return array List of errors
3619 protected function validateFileMoveOperation( $nt ) {
3624 $destFile = wfLocalFile( $nt );
3625 $destFile->load( File
::READ_LATEST
);
3626 if ( !$wgUser->isAllowed( 'reupload-shared' )
3627 && !$destFile->exists() && wfFindFile( $nt )
3629 $errors[] = [ 'file-exists-sharedrepo' ];
3636 * Move a title to a new location
3638 * @deprecated since 1.25, use the MovePage class instead
3639 * @param Title $nt The new title
3640 * @param bool $auth Indicates whether $wgUser's permissions
3642 * @param string $reason The reason for the move
3643 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3644 * Ignored if the user doesn't have the suppressredirect right.
3645 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3647 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3649 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3650 if ( is_array( $err ) ) {
3651 // Auto-block user's IP if the account was "hard" blocked
3652 $wgUser->spreadAnyEditBlock();
3655 // Check suppressredirect permission
3656 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3657 $createRedirect = true;
3660 $mp = new MovePage( $this, $nt );
3661 $status = $mp->move( $wgUser, $reason, $createRedirect );
3662 if ( $status->isOK() ) {
3665 return $status->getErrorsArray();
3670 * Move this page's subpages to be subpages of $nt
3672 * @param Title $nt Move target
3673 * @param bool $auth Whether $wgUser's permissions should be checked
3674 * @param string $reason The reason for the move
3675 * @param bool $createRedirect Whether to create redirects from the old subpages to
3676 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3677 * @return array Array with old page titles as keys, and strings (new page titles) or
3678 * arrays (errors) as values, or an error array with numeric indices if no pages
3681 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3682 global $wgMaximumMovedPages;
3683 // Check permissions
3684 if ( !$this->userCan( 'move-subpages' ) ) {
3685 return [ 'cant-move-subpages' ];
3687 // Do the source and target namespaces support subpages?
3688 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3689 return [ 'namespace-nosubpages',
3690 MWNamespace
::getCanonicalName( $this->getNamespace() ) ];
3692 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3693 return [ 'namespace-nosubpages',
3694 MWNamespace
::getCanonicalName( $nt->getNamespace() ) ];
3697 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3700 foreach ( $subpages as $oldSubpage ) {
3702 if ( $count > $wgMaximumMovedPages ) {
3703 $retval[$oldSubpage->getPrefixedText()] =
3704 [ 'movepage-max-pages',
3705 $wgMaximumMovedPages ];
3709 // We don't know whether this function was called before
3710 // or after moving the root page, so check both
3712 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3713 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3715 // When moving a page to a subpage of itself,
3716 // don't move it twice
3719 $newPageName = preg_replace(
3720 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3721 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3722 $oldSubpage->getDBkey() );
3723 if ( $oldSubpage->isTalkPage() ) {
3724 $newNs = $nt->getTalkPage()->getNamespace();
3726 $newNs = $nt->getSubjectPage()->getNamespace();
3728 # Bug 14385: we need makeTitleSafe because the new page names may
3729 # be longer than 255 characters.
3730 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3732 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3733 if ( $success === true ) {
3734 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3736 $retval[$oldSubpage->getPrefixedText()] = $success;
3743 * Checks if this page is just a one-rev redirect.
3744 * Adds lock, so don't use just for light purposes.
3748 public function isSingleRevRedirect() {
3749 global $wgContentHandlerUseDB;
3751 $dbw = wfGetDB( DB_MASTER
);
3754 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3755 if ( $wgContentHandlerUseDB ) {
3756 $fields[] = 'page_content_model';
3759 $row = $dbw->selectRow( 'page',
3765 # Cache some fields we may want
3766 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3767 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3768 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3769 $this->mContentModel
= $row && isset( $row->page_content_model
)
3770 ?
strval( $row->page_content_model
)
3773 if ( !$this->mRedirect
) {
3776 # Does the article have a history?
3777 $row = $dbw->selectField( [ 'page', 'revision' ],
3779 [ 'page_namespace' => $this->getNamespace(),
3780 'page_title' => $this->getDBkey(),
3782 'page_latest != rev_id'
3787 # Return true if there was no history
3788 return ( $row === false );
3792 * Checks if $this can be moved to a given Title
3793 * - Selects for update, so don't call it unless you mean business
3795 * @deprecated since 1.25, use MovePage's methods instead
3796 * @param Title $nt The new title to check
3799 public function isValidMoveTarget( $nt ) {
3800 # Is it an existing file?
3801 if ( $nt->getNamespace() == NS_FILE
) {
3802 $file = wfLocalFile( $nt );
3803 $file->load( File
::READ_LATEST
);
3804 if ( $file->exists() ) {
3805 wfDebug( __METHOD__
. ": file exists\n" );
3809 # Is it a redirect with no history?
3810 if ( !$nt->isSingleRevRedirect() ) {
3811 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3814 # Get the article text
3815 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3816 if ( !is_object( $rev ) ) {
3819 $content = $rev->getContent();
3820 # Does the redirect point to the source?
3821 # Or is it a broken self-redirect, usually caused by namespace collisions?
3822 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3824 if ( $redirTitle ) {
3825 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3826 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3827 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3833 # Fail safe (not a redirect after all. strange.)
3834 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3835 " is a redirect, but it doesn't contain a valid redirect.\n" );
3841 * Get categories to which this Title belongs and return an array of
3842 * categories' names.
3844 * @return array Array of parents in the form:
3845 * $parent => $currentarticle
3847 public function getParentCategories() {
3852 $titleKey = $this->getArticleID();
3854 if ( $titleKey === 0 ) {
3858 $dbr = wfGetDB( DB_SLAVE
);
3860 $res = $dbr->select(
3863 [ 'cl_from' => $titleKey ],
3867 if ( $res->numRows() > 0 ) {
3868 foreach ( $res as $row ) {
3869 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3870 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3877 * Get a tree of parent categories
3879 * @param array $children Array with the children in the keys, to check for circular refs
3880 * @return array Tree of parent categories
3882 public function getParentCategoryTree( $children = [] ) {
3884 $parents = $this->getParentCategories();
3887 foreach ( $parents as $parent => $current ) {
3888 if ( array_key_exists( $parent, $children ) ) {
3889 # Circular reference
3890 $stack[$parent] = [];
3892 $nt = Title
::newFromText( $parent );
3894 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3904 * Get an associative array for selecting this title from
3907 * @return array Array suitable for the $where parameter of DB::select()
3909 public function pageCond() {
3910 if ( $this->mArticleID
> 0 ) {
3911 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3912 return [ 'page_id' => $this->mArticleID
];
3914 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3919 * Get the revision ID of the previous revision
3921 * @param int $revId Revision ID. Get the revision that was before this one.
3922 * @param int $flags Title::GAID_FOR_UPDATE
3923 * @return int|bool Old revision ID, or false if none exists
3925 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3926 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3927 $revId = $db->selectField( 'revision', 'rev_id',
3929 'rev_page' => $this->getArticleID( $flags ),
3930 'rev_id < ' . intval( $revId )
3933 [ 'ORDER BY' => 'rev_id DESC' ]
3936 if ( $revId === false ) {
3939 return intval( $revId );
3944 * Get the revision ID of the next revision
3946 * @param int $revId Revision ID. Get the revision that was after this one.
3947 * @param int $flags Title::GAID_FOR_UPDATE
3948 * @return int|bool Next revision ID, or false if none exists
3950 public function getNextRevisionID( $revId, $flags = 0 ) {
3951 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3952 $revId = $db->selectField( 'revision', 'rev_id',
3954 'rev_page' => $this->getArticleID( $flags ),
3955 'rev_id > ' . intval( $revId )
3958 [ 'ORDER BY' => 'rev_id' ]
3961 if ( $revId === false ) {
3964 return intval( $revId );
3969 * Get the first revision of the page
3971 * @param int $flags Title::GAID_FOR_UPDATE
3972 * @return Revision|null If page doesn't exist
3974 public function getFirstRevision( $flags = 0 ) {
3975 $pageId = $this->getArticleID( $flags );
3977 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3978 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3979 [ 'rev_page' => $pageId ],
3981 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
3984 return new Revision( $row );
3991 * Get the oldest revision timestamp of this page
3993 * @param int $flags Title::GAID_FOR_UPDATE
3994 * @return string MW timestamp
3996 public function getEarliestRevTime( $flags = 0 ) {
3997 $rev = $this->getFirstRevision( $flags );
3998 return $rev ?
$rev->getTimestamp() : null;
4002 * Check if this is a new page
4006 public function isNewPage() {
4007 $dbr = wfGetDB( DB_SLAVE
);
4008 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4012 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4016 public function isBigDeletion() {
4017 global $wgDeleteRevisionsLimit;
4019 if ( !$wgDeleteRevisionsLimit ) {
4023 if ( $this->mIsBigDeletion
=== null ) {
4024 $dbr = wfGetDB( DB_SLAVE
);
4026 $revCount = $dbr->selectRowCount(
4029 [ 'rev_page' => $this->getArticleID() ],
4031 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4034 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4037 return $this->mIsBigDeletion
;
4041 * Get the approximate revision count of this page.
4045 public function estimateRevisionCount() {
4046 if ( !$this->exists() ) {
4050 if ( $this->mEstimateRevisions
=== null ) {
4051 $dbr = wfGetDB( DB_SLAVE
);
4052 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4053 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4056 return $this->mEstimateRevisions
;
4060 * Get the number of revisions between the given revision.
4061 * Used for diffs and other things that really need it.
4063 * @param int|Revision $old Old revision or rev ID (first before range)
4064 * @param int|Revision $new New revision or rev ID (first after range)
4065 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4066 * @return int Number of revisions between these revisions.
4068 public function countRevisionsBetween( $old, $new, $max = null ) {
4069 if ( !( $old instanceof Revision
) ) {
4070 $old = Revision
::newFromTitle( $this, (int)$old );
4072 if ( !( $new instanceof Revision
) ) {
4073 $new = Revision
::newFromTitle( $this, (int)$new );
4075 if ( !$old ||
!$new ) {
4076 return 0; // nothing to compare
4078 $dbr = wfGetDB( DB_SLAVE
);
4080 'rev_page' => $this->getArticleID(),
4081 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4082 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4084 if ( $max !== null ) {
4085 return $dbr->selectRowCount( 'revision', '1',
4088 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4091 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4096 * Get the authors between the given revisions or revision IDs.
4097 * Used for diffs and other things that really need it.
4101 * @param int|Revision $old Old revision or rev ID (first before range by default)
4102 * @param int|Revision $new New revision or rev ID (first after range by default)
4103 * @param int $limit Maximum number of authors
4104 * @param string|array $options (Optional): Single option, or an array of options:
4105 * 'include_old' Include $old in the range; $new is excluded.
4106 * 'include_new' Include $new in the range; $old is excluded.
4107 * 'include_both' Include both $old and $new in the range.
4108 * Unknown option values are ignored.
4109 * @return array|null Names of revision authors in the range; null if not both revisions exist
4111 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4112 if ( !( $old instanceof Revision
) ) {
4113 $old = Revision
::newFromTitle( $this, (int)$old );
4115 if ( !( $new instanceof Revision
) ) {
4116 $new = Revision
::newFromTitle( $this, (int)$new );
4118 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4119 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4120 // in the sanity check below?
4121 if ( !$old ||
!$new ) {
4122 return null; // nothing to compare
4127 $options = (array)$options;
4128 if ( in_array( 'include_old', $options ) ) {
4131 if ( in_array( 'include_new', $options ) ) {
4134 if ( in_array( 'include_both', $options ) ) {
4138 // No DB query needed if $old and $new are the same or successive revisions:
4139 if ( $old->getId() === $new->getId() ) {
4140 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4142 [ $old->getUserText( Revision
::RAW
) ];
4143 } elseif ( $old->getId() === $new->getParentId() ) {
4144 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4145 $authors[] = $old->getUserText( Revision
::RAW
);
4146 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4147 $authors[] = $new->getUserText( Revision
::RAW
);
4149 } elseif ( $old_cmp === '>=' ) {
4150 $authors[] = $old->getUserText( Revision
::RAW
);
4151 } elseif ( $new_cmp === '<=' ) {
4152 $authors[] = $new->getUserText( Revision
::RAW
);
4156 $dbr = wfGetDB( DB_SLAVE
);
4157 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4159 'rev_page' => $this->getArticleID(),
4160 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4161 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4163 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4165 foreach ( $res as $row ) {
4166 $authors[] = $row->rev_user_text
;
4172 * Get the number of authors between the given revisions or revision IDs.
4173 * Used for diffs and other things that really need it.
4175 * @param int|Revision $old Old revision or rev ID (first before range by default)
4176 * @param int|Revision $new New revision or rev ID (first after range by default)
4177 * @param int $limit Maximum number of authors
4178 * @param string|array $options (Optional): Single option, or an array of options:
4179 * 'include_old' Include $old in the range; $new is excluded.
4180 * 'include_new' Include $new in the range; $old is excluded.
4181 * 'include_both' Include both $old and $new in the range.
4182 * Unknown option values are ignored.
4183 * @return int Number of revision authors in the range; zero if not both revisions exist
4185 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4186 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4187 return $authors ?
count( $authors ) : 0;
4191 * Compare with another title.
4193 * @param Title $title
4196 public function equals( Title
$title ) {
4197 // Note: === is necessary for proper matching of number-like titles.
4198 return $this->getInterwiki() === $title->getInterwiki()
4199 && $this->getNamespace() == $title->getNamespace()
4200 && $this->getDBkey() === $title->getDBkey();
4204 * Check if this title is a subpage of another title
4206 * @param Title $title
4209 public function isSubpageOf( Title
$title ) {
4210 return $this->getInterwiki() === $title->getInterwiki()
4211 && $this->getNamespace() == $title->getNamespace()
4212 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4216 * Check if page exists. For historical reasons, this function simply
4217 * checks for the existence of the title in the page table, and will
4218 * thus return false for interwiki links, special pages and the like.
4219 * If you want to know if a title can be meaningfully viewed, you should
4220 * probably call the isKnown() method instead.
4222 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4223 * from master/for update
4226 public function exists( $flags = 0 ) {
4227 $exists = $this->getArticleID( $flags ) != 0;
4228 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4233 * Should links to this title be shown as potentially viewable (i.e. as
4234 * "bluelinks"), even if there's no record by this title in the page
4237 * This function is semi-deprecated for public use, as well as somewhat
4238 * misleadingly named. You probably just want to call isKnown(), which
4239 * calls this function internally.
4241 * (ISSUE: Most of these checks are cheap, but the file existence check
4242 * can potentially be quite expensive. Including it here fixes a lot of
4243 * existing code, but we might want to add an optional parameter to skip
4244 * it and any other expensive checks.)
4248 public function isAlwaysKnown() {
4252 * Allows overriding default behavior for determining if a page exists.
4253 * If $isKnown is kept as null, regular checks happen. If it's
4254 * a boolean, this value is returned by the isKnown method.
4258 * @param Title $title
4259 * @param bool|null $isKnown
4261 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4263 if ( !is_null( $isKnown ) ) {
4267 if ( $this->isExternal() ) {
4268 return true; // any interwiki link might be viewable, for all we know
4271 switch ( $this->mNamespace
) {
4274 // file exists, possibly in a foreign repo
4275 return (bool)wfFindFile( $this );
4277 // valid special page
4278 return SpecialPageFactory
::exists( $this->getDBkey() );
4280 // selflink, possibly with fragment
4281 return $this->mDbkeyform
== '';
4283 // known system message
4284 return $this->hasSourceText() !== false;
4291 * Does this title refer to a page that can (or might) be meaningfully
4292 * viewed? In particular, this function may be used to determine if
4293 * links to the title should be rendered as "bluelinks" (as opposed to
4294 * "redlinks" to non-existent pages).
4295 * Adding something else to this function will cause inconsistency
4296 * since LinkHolderArray calls isAlwaysKnown() and does its own
4297 * page existence check.
4301 public function isKnown() {
4302 return $this->isAlwaysKnown() ||
$this->exists();
4306 * Does this page have source text?
4310 public function hasSourceText() {
4311 if ( $this->exists() ) {
4315 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4316 // If the page doesn't exist but is a known system message, default
4317 // message content will be displayed, same for language subpages-
4318 // Use always content language to avoid loading hundreds of languages
4319 // to get the link color.
4321 list( $name, ) = MessageCache
::singleton()->figureMessage(
4322 $wgContLang->lcfirst( $this->getText() )
4324 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4325 return $message->exists();
4332 * Get the default message text or false if the message doesn't exist
4334 * @return string|bool
4336 public function getDefaultMessageText() {
4339 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4343 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4344 $wgContLang->lcfirst( $this->getText() )
4346 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4348 if ( $message->exists() ) {
4349 return $message->plain();
4356 * Updates page_touched for this page; called from LinksUpdate.php
4358 * @param string $purgeTime [optional] TS_MW timestamp
4359 * @return bool True if the update succeeded
4361 public function invalidateCache( $purgeTime = null ) {
4362 if ( wfReadOnly() ) {
4366 if ( $this->mArticleID
=== 0 ) {
4367 return true; // avoid gap locking if we know it's not there
4370 $conds = $this->pageCond();
4371 DeferredUpdates
::addUpdate(
4372 new AutoCommitUpdate(
4373 wfGetDB( DB_MASTER
),
4375 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4376 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4379 [ 'page_touched' => $dbTimestamp ],
4380 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4385 DeferredUpdates
::PRESEND
4392 * Update page_touched timestamps and send CDN purge messages for
4393 * pages linking to this title. May be sent to the job queue depending
4394 * on the number of links. Typically called on create and delete.
4396 public function touchLinks() {
4397 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4398 if ( $this->getNamespace() == NS_CATEGORY
) {
4399 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4404 * Get the last touched timestamp
4406 * @param IDatabase $db Optional db
4407 * @return string Last-touched timestamp
4409 public function getTouched( $db = null ) {
4410 if ( $db === null ) {
4411 $db = wfGetDB( DB_SLAVE
);
4413 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4418 * Get the timestamp when this page was updated since the user last saw it.
4421 * @return string|null
4423 public function getNotificationTimestamp( $user = null ) {
4426 // Assume current user if none given
4430 // Check cache first
4431 $uid = $user->getId();
4435 // avoid isset here, as it'll return false for null entries
4436 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4437 return $this->mNotificationTimestamp
[$uid];
4439 // Don't cache too much!
4440 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4441 $this->mNotificationTimestamp
= [];
4444 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4445 $watchedItem = $store->getWatchedItem( $user, $this );
4446 if ( $watchedItem ) {
4447 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4449 $this->mNotificationTimestamp
[$uid] = false;
4452 return $this->mNotificationTimestamp
[$uid];
4456 * Generate strings used for xml 'id' names in monobook tabs
4458 * @param string $prepend Defaults to 'nstab-'
4459 * @return string XML 'id' name
4461 public function getNamespaceKey( $prepend = 'nstab-' ) {
4463 // Gets the subject namespace if this title
4464 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4465 // Checks if canonical namespace name exists for namespace
4466 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4467 // Uses canonical namespace name
4468 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4470 // Uses text of namespace
4471 $namespaceKey = $this->getSubjectNsText();
4473 // Makes namespace key lowercase
4474 $namespaceKey = $wgContLang->lc( $namespaceKey );
4476 if ( $namespaceKey == '' ) {
4477 $namespaceKey = 'main';
4479 // Changes file to image for backwards compatibility
4480 if ( $namespaceKey == 'file' ) {
4481 $namespaceKey = 'image';
4483 return $prepend . $namespaceKey;
4487 * Get all extant redirects to this Title
4489 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4490 * @return Title[] Array of Title redirects to this title
4492 public function getRedirectsHere( $ns = null ) {
4495 $dbr = wfGetDB( DB_SLAVE
);
4497 'rd_namespace' => $this->getNamespace(),
4498 'rd_title' => $this->getDBkey(),
4501 if ( $this->isExternal() ) {
4502 $where['rd_interwiki'] = $this->getInterwiki();
4504 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4506 if ( !is_null( $ns ) ) {
4507 $where['page_namespace'] = $ns;
4510 $res = $dbr->select(
4511 [ 'redirect', 'page' ],
4512 [ 'page_namespace', 'page_title' ],
4517 foreach ( $res as $row ) {
4518 $redirs[] = self
::newFromRow( $row );
4524 * Check if this Title is a valid redirect target
4528 public function isValidRedirectTarget() {
4529 global $wgInvalidRedirectTargets;
4531 if ( $this->isSpecialPage() ) {
4532 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4533 if ( $this->isSpecial( 'Userlogout' ) ) {
4537 foreach ( $wgInvalidRedirectTargets as $target ) {
4538 if ( $this->isSpecial( $target ) ) {
4548 * Get a backlink cache object
4550 * @return BacklinkCache
4552 public function getBacklinkCache() {
4553 return BacklinkCache
::get( $this );
4557 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4561 public function canUseNoindex() {
4562 global $wgExemptFromUserRobotsControl;
4564 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4565 ? MWNamespace
::getContentNamespaces()
4566 : $wgExemptFromUserRobotsControl;
4568 return !in_array( $this->mNamespace
, $bannedNamespaces );
4573 * Returns the raw sort key to be used for categories, with the specified
4574 * prefix. This will be fed to Collation::getSortKey() to get a
4575 * binary sortkey that can be used for actual sorting.
4577 * @param string $prefix The prefix to be used, specified using
4578 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4582 public function getCategorySortkey( $prefix = '' ) {
4583 $unprefixed = $this->getText();
4585 // Anything that uses this hook should only depend
4586 // on the Title object passed in, and should probably
4587 // tell the users to run updateCollations.php --force
4588 // in order to re-sort existing category relations.
4589 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4590 if ( $prefix !== '' ) {
4591 # Separate with a line feed, so the unprefixed part is only used as
4592 # a tiebreaker when two pages have the exact same prefix.
4593 # In UCA, tab is the only character that can sort above LF
4594 # so we strip both of them from the original prefix.
4595 $prefix = strtr( $prefix, "\n\t", ' ' );
4596 return "$prefix\n$unprefixed";
4602 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4603 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4604 * the db, it will return NULL.
4606 * @return string|null|bool
4608 private function getDbPageLanguageCode() {
4609 global $wgPageLanguageUseDB;
4611 // check, if the page language could be saved in the database, and if so and
4612 // the value is not requested already, lookup the page language using LinkCache
4613 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4614 $linkCache = LinkCache
::singleton();
4615 $linkCache->addLinkObj( $this );
4616 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4619 return $this->mDbPageLanguage
;
4623 * Get the language in which the content of this page is written in
4624 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4625 * e.g. $wgLang (such as special pages, which are in the user language).
4630 public function getPageLanguage() {
4631 global $wgLang, $wgLanguageCode;
4632 if ( $this->isSpecialPage() ) {
4633 // special pages are in the user language
4637 // Checking if DB language is set
4638 $dbPageLanguage = $this->getDbPageLanguageCode();
4639 if ( $dbPageLanguage ) {
4640 return wfGetLangObj( $dbPageLanguage );
4643 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4644 // Note that this may depend on user settings, so the cache should
4645 // be only per-request.
4646 // NOTE: ContentHandler::getPageLanguage() may need to load the
4647 // content to determine the page language!
4648 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4650 $contentHandler = ContentHandler
::getForTitle( $this );
4651 $langObj = $contentHandler->getPageLanguage( $this );
4652 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4654 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4661 * Get the language in which the content of this page is written when
4662 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4663 * e.g. $wgLang (such as special pages, which are in the user language).
4668 public function getPageViewLanguage() {
4671 if ( $this->isSpecialPage() ) {
4672 // If the user chooses a variant, the content is actually
4673 // in a language whose code is the variant code.
4674 $variant = $wgLang->getPreferredVariant();
4675 if ( $wgLang->getCode() !== $variant ) {
4676 return Language
::factory( $variant );
4682 // Checking if DB language is set
4683 $dbPageLanguage = $this->getDbPageLanguageCode();
4684 if ( $dbPageLanguage ) {
4685 $pageLang = wfGetLangObj( $dbPageLanguage );
4686 $variant = $pageLang->getPreferredVariant();
4687 if ( $pageLang->getCode() !== $variant ) {
4688 $pageLang = Language
::factory( $variant );
4694 // @note Can't be cached persistently, depends on user settings.
4695 // @note ContentHandler::getPageViewLanguage() may need to load the
4696 // content to determine the page language!
4697 $contentHandler = ContentHandler
::getForTitle( $this );
4698 $pageLang = $contentHandler->getPageViewLanguage( $this );
4703 * Get a list of rendered edit notices for this page.
4705 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4706 * they will already be wrapped in paragraphs.
4709 * @param int $oldid Revision ID that's being edited
4712 public function getEditNotices( $oldid = 0 ) {
4715 // Optional notice for the entire namespace
4716 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4717 $msg = wfMessage( $editnotice_ns );
4718 if ( $msg->exists() ) {
4719 $html = $msg->parseAsBlock();
4720 // Edit notices may have complex logic, but output nothing (T91715)
4721 if ( trim( $html ) !== '' ) {
4722 $notices[$editnotice_ns] = Html
::rawElement(
4726 'mw-editnotice-namespace',
4727 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4734 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4735 // Optional notice for page itself and any parent page
4736 $parts = explode( '/', $this->getDBkey() );
4737 $editnotice_base = $editnotice_ns;
4738 while ( count( $parts ) > 0 ) {
4739 $editnotice_base .= '-' . array_shift( $parts );
4740 $msg = wfMessage( $editnotice_base );
4741 if ( $msg->exists() ) {
4742 $html = $msg->parseAsBlock();
4743 if ( trim( $html ) !== '' ) {
4744 $notices[$editnotice_base] = Html
::rawElement(
4748 'mw-editnotice-base',
4749 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4757 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4758 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4759 $msg = wfMessage( $editnoticeText );
4760 if ( $msg->exists() ) {
4761 $html = $msg->parseAsBlock();
4762 if ( trim( $html ) !== '' ) {
4763 $notices[$editnoticeText] = Html
::rawElement(
4767 'mw-editnotice-page',
4768 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4776 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4783 public function __sleep() {
4791 'mDefaultNamespace',
4795 public function __wakeup() {
4796 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4797 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4798 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );