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
;
27 * Represents a title within MediaWiki.
28 * Optionally may contain an interwiki designation or namespace.
29 * @note This class can fetch various kinds of data from the database;
30 * however, it does so inefficiently.
31 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
32 * and does not rely on global state or the database.
34 class Title
implements LinkTarget
{
35 /** @var HashBagOStuff */
36 static private $titleCache = null;
39 * Title::newFromText maintains a cache to avoid expensive re-normalization of
40 * commonly used titles. On a batch operation this can become a memory leak
41 * if not bounded. After hitting this many titles reset the cache.
43 const CACHE_MAX
= 1000;
46 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
47 * to use the master DB
49 const GAID_FOR_UPDATE
= 1;
52 * @name Private member variables
53 * Please use the accessor functions instead.
58 /** @var string Text form (spaces not underscores) of the main part */
59 public $mTextform = '';
61 /** @var string URL-encoded form of the main part */
62 public $mUrlform = '';
64 /** @var string Main part with underscores */
65 public $mDbkeyform = '';
67 /** @var string Database key with the initial letter in the case specified by the user */
68 protected $mUserCaseDBKey;
70 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
71 public $mNamespace = NS_MAIN
;
73 /** @var string Interwiki prefix */
74 public $mInterwiki = '';
76 /** @var bool Was this Title created from a string with a local interwiki prefix? */
77 private $mLocalInterwiki = false;
79 /** @var string Title fragment (i.e. the bit after the #) */
80 public $mFragment = '';
82 /** @var int Article ID, fetched from the link cache on demand */
83 public $mArticleID = -1;
85 /** @var bool|int ID of most recent revision */
86 protected $mLatestID = false;
89 * @var bool|string ID of the page's content model, i.e. one of the
90 * CONTENT_MODEL_XXX constants
92 public $mContentModel = false;
94 /** @var int Estimated number of revisions; null of not loaded */
95 private $mEstimateRevisions;
97 /** @var array Array of groups allowed to edit this article */
98 public $mRestrictions = [];
100 /** @var string|bool */
101 protected $mOldRestrictions = false;
103 /** @var bool Cascade restrictions on this page to included templates and images? */
104 public $mCascadeRestriction;
106 /** Caching the results of getCascadeProtectionSources */
107 public $mCascadingRestrictions;
109 /** @var array When do the restrictions on this page expire? */
110 protected $mRestrictionsExpiry = [];
112 /** @var bool Are cascading restrictions in effect on this page? */
113 protected $mHasCascadingRestrictions;
115 /** @var array Where are the cascading restrictions coming from on this page? */
116 public $mCascadeSources;
118 /** @var bool Boolean for initialisation on demand */
119 public $mRestrictionsLoaded = false;
121 /** @var string Text form including namespace/interwiki, initialised on demand */
122 protected $mPrefixedText = null;
124 /** @var mixed Cached value for getTitleProtection (create protection) */
125 public $mTitleProtection;
128 * @var int Namespace index when there is no namespace. Don't change the
129 * following default, NS_MAIN is hardcoded in several places. See bug 696.
130 * Zero except in {{transclusion}} tags.
132 public $mDefaultNamespace = NS_MAIN
;
134 /** @var int The page length, 0 for special pages */
135 protected $mLength = -1;
137 /** @var null Is the article at this title a redirect? */
138 public $mRedirect = null;
140 /** @var array Associative array of user ID -> timestamp/false */
141 private $mNotificationTimestamp = [];
143 /** @var bool Whether a page has any subpages */
144 private $mHasSubpages;
146 /** @var bool The (string) language code of the page's language and content code. */
147 private $mPageLanguage = false;
149 /** @var string|bool|null The page language code from the database, null if not saved in
150 * the database or false if not loaded, yet. */
151 private $mDbPageLanguage = false;
153 /** @var TitleValue A corresponding TitleValue object */
154 private $mTitleValue = null;
156 /** @var bool Would deleting this page be a big deletion? */
157 private $mIsBigDeletion = null;
161 * B/C kludge: provide a TitleParser for use by Title.
162 * Ideally, Title would have no methods that need this.
163 * Avoid usage of this singleton by using TitleValue
164 * and the associated services when possible.
166 * @return MediaWikiTitleCodec
168 private static function getMediaWikiTitleCodec() {
169 global $wgContLang, $wgLocalInterwikis;
171 static $titleCodec = null;
172 static $titleCodecFingerprint = null;
174 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
175 // make sure we are using the right one. To detect changes over the course
176 // of a request, we remember a fingerprint of the config used to create the
177 // codec singleton, and re-create it if the fingerprint doesn't match.
178 $fingerprint = spl_object_hash( $wgContLang ) . '|' . implode( '+', $wgLocalInterwikis );
180 if ( $fingerprint !== $titleCodecFingerprint ) {
184 if ( !$titleCodec ) {
185 $titleCodec = new MediaWikiTitleCodec(
187 GenderCache
::singleton(),
190 $titleCodecFingerprint = $fingerprint;
197 * B/C kludge: provide a TitleParser for use by Title.
198 * Ideally, Title would have no methods that need this.
199 * Avoid usage of this singleton by using TitleValue
200 * and the associated services when possible.
202 * @return TitleFormatter
204 private static function getTitleFormatter() {
205 // NOTE: we know that getMediaWikiTitleCodec() returns a MediaWikiTitleCodec,
206 // which implements TitleFormatter.
207 return self
::getMediaWikiTitleCodec();
210 function __construct() {
214 * Create a new Title from a prefixed DB key
216 * @param string $key The database key, which has underscores
217 * instead of spaces, possibly including namespace and
219 * @return Title|null Title, or null on an error
221 public static function newFromDBkey( $key ) {
223 $t->mDbkeyform
= $key;
226 $t->secureAndSplit();
228 } catch ( MalformedTitleException
$ex ) {
234 * Create a new Title from a TitleValue
236 * @param TitleValue $titleValue Assumed to be safe.
240 public static function newFromTitleValue( TitleValue
$titleValue ) {
241 return self
::newFromLinkTarget( $titleValue );
245 * Create a new Title from a LinkTarget
247 * @param LinkTarget $linkTarget Assumed to be safe.
251 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
252 if ( $linkTarget instanceof Title
) {
253 // Special case if it's already a Title object
256 return self
::makeTitle(
257 $linkTarget->getNamespace(),
258 $linkTarget->getText(),
259 $linkTarget->getFragment(),
260 $linkTarget->getInterwiki()
265 * Create a new Title from text, such as what one would find in a link. De-
266 * codes any HTML entities in the text.
268 * @param string|int|null $text The link text; spaces, prefixes, and an
269 * initial ':' indicating the main namespace are accepted.
270 * @param int $defaultNamespace The namespace to use if none is specified
271 * by a prefix. If you want to force a specific namespace even if
272 * $text might begin with a namespace prefix, use makeTitle() or
274 * @throws InvalidArgumentException
275 * @return Title|null Title or null on an error.
277 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
278 // DWIM: Integers can be passed in here when page titles are used as array keys.
279 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
280 throw new InvalidArgumentException( '$text must be a string.' );
282 if ( $text === null ) {
287 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
288 } catch ( MalformedTitleException
$ex ) {
294 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
295 * rather than returning null.
297 * The exception subclasses encode detailed information about why the title is invalid.
299 * @see Title::newFromText
302 * @param string $text Title text to check
303 * @param int $defaultNamespace
304 * @throws MalformedTitleException If the title is invalid
307 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
308 if ( is_object( $text ) ) {
309 throw new MWException( '$text must be a string, given an object' );
312 $titleCache = self
::getTitleCache();
314 // Wiki pages often contain multiple links to the same page.
315 // Title normalization and parsing can become expensive on pages with many
316 // links, so we can save a little time by caching them.
317 // In theory these are value objects and won't get changed...
318 if ( $defaultNamespace == NS_MAIN
) {
319 $t = $titleCache->get( $text );
325 // Convert things like é ā or 〗 into normalized (bug 14952) text
326 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
329 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
330 $t->mDefaultNamespace
= intval( $defaultNamespace );
332 $t->secureAndSplit();
333 if ( $defaultNamespace == NS_MAIN
) {
334 $titleCache->set( $text, $t );
340 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
342 * Example of wrong and broken code:
343 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
345 * Example of right code:
346 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
348 * Create a new Title from URL-encoded text. Ensures that
349 * the given title's length does not exceed the maximum.
351 * @param string $url The title, as might be taken from a URL
352 * @return Title|null The new object, or null on an error
354 public static function newFromURL( $url ) {
357 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
358 # but some URLs used it as a space replacement and they still come
359 # from some external search tools.
360 if ( strpos( self
::legalChars(), '+' ) === false ) {
361 $url = strtr( $url, '+', ' ' );
364 $t->mDbkeyform
= strtr( $url, ' ', '_' );
367 $t->secureAndSplit();
369 } catch ( MalformedTitleException
$ex ) {
375 * @return HashBagOStuff
377 private static function getTitleCache() {
378 if ( self
::$titleCache == null ) {
379 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
381 return self
::$titleCache;
385 * Returns a list of fields that are to be selected for initializing Title
386 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
387 * whether to include page_content_model.
391 protected static function getSelectFields() {
392 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
395 'page_namespace', 'page_title', 'page_id',
396 'page_len', 'page_is_redirect', 'page_latest',
399 if ( $wgContentHandlerUseDB ) {
400 $fields[] = 'page_content_model';
403 if ( $wgPageLanguageUseDB ) {
404 $fields[] = 'page_lang';
411 * Create a new Title from an article ID
413 * @param int $id The page_id corresponding to the Title to create
414 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
415 * @return Title|null The new object, or null on an error
417 public static function newFromID( $id, $flags = 0 ) {
418 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
419 $row = $db->selectRow(
421 self
::getSelectFields(),
422 [ 'page_id' => $id ],
425 if ( $row !== false ) {
426 $title = Title
::newFromRow( $row );
434 * Make an array of titles from an array of IDs
436 * @param int[] $ids Array of IDs
437 * @return Title[] Array of Titles
439 public static function newFromIDs( $ids ) {
440 if ( !count( $ids ) ) {
443 $dbr = wfGetDB( DB_SLAVE
);
447 self
::getSelectFields(),
448 [ 'page_id' => $ids ],
453 foreach ( $res as $row ) {
454 $titles[] = Title
::newFromRow( $row );
460 * Make a Title object from a DB row
462 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
463 * @return Title Corresponding Title
465 public static function newFromRow( $row ) {
466 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
467 $t->loadFromRow( $row );
472 * Load Title object fields from a DB row.
473 * If false is given, the title will be treated as non-existing.
475 * @param stdClass|bool $row Database row
477 public function loadFromRow( $row ) {
478 if ( $row ) { // page found
479 if ( isset( $row->page_id
) ) {
480 $this->mArticleID
= (int)$row->page_id
;
482 if ( isset( $row->page_len
) ) {
483 $this->mLength
= (int)$row->page_len
;
485 if ( isset( $row->page_is_redirect
) ) {
486 $this->mRedirect
= (bool)$row->page_is_redirect
;
488 if ( isset( $row->page_latest
) ) {
489 $this->mLatestID
= (int)$row->page_latest
;
491 if ( isset( $row->page_content_model
) ) {
492 $this->mContentModel
= strval( $row->page_content_model
);
494 $this->mContentModel
= false; # initialized lazily in getContentModel()
496 if ( isset( $row->page_lang
) ) {
497 $this->mDbPageLanguage
= (string)$row->page_lang
;
499 if ( isset( $row->page_restrictions
) ) {
500 $this->mOldRestrictions
= $row->page_restrictions
;
502 } else { // page not found
503 $this->mArticleID
= 0;
505 $this->mRedirect
= false;
506 $this->mLatestID
= 0;
507 $this->mContentModel
= false; # initialized lazily in getContentModel()
512 * Create a new Title from a namespace index and a DB key.
513 * It's assumed that $ns and $title are *valid*, for instance when
514 * they came directly from the database or a special page name.
515 * For convenience, spaces are converted to underscores so that
516 * eg user_text fields can be used directly.
518 * @param int $ns The namespace of the article
519 * @param string $title The unprefixed database key form
520 * @param string $fragment The link fragment (after the "#")
521 * @param string $interwiki The interwiki prefix
522 * @return Title The new object
524 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
526 $t->mInterwiki
= $interwiki;
527 $t->mFragment
= $fragment;
528 $t->mNamespace
= $ns = intval( $ns );
529 $t->mDbkeyform
= strtr( $title, ' ', '_' );
530 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
531 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
532 $t->mTextform
= strtr( $title, '_', ' ' );
533 $t->mContentModel
= false; # initialized lazily in getContentModel()
538 * Create a new Title from a namespace index and a DB key.
539 * The parameters will be checked for validity, which is a bit slower
540 * than makeTitle() but safer for user-provided data.
542 * @param int $ns The namespace of the article
543 * @param string $title Database key form
544 * @param string $fragment The link fragment (after the "#")
545 * @param string $interwiki Interwiki prefix
546 * @return Title|null The new object, or null on an error
548 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
549 if ( !MWNamespace
::exists( $ns ) ) {
554 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
557 $t->secureAndSplit();
559 } catch ( MalformedTitleException
$ex ) {
565 * Create a new Title for the Main Page
567 * @return Title The new object
569 public static function newMainPage() {
570 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
571 // Don't give fatal errors if the message is broken
573 $title = Title
::newFromText( 'Main Page' );
579 * Get the prefixed DB key associated with an ID
581 * @param int $id The page_id of the article
582 * @return Title|null An object representing the article, or null if no such article was found
584 public static function nameOf( $id ) {
585 $dbr = wfGetDB( DB_SLAVE
);
587 $s = $dbr->selectRow(
589 [ 'page_namespace', 'page_title' ],
590 [ 'page_id' => $id ],
593 if ( $s === false ) {
597 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
602 * Get a regex character class describing the legal characters in a link
604 * @return string The list of characters, not delimited
606 public static function legalChars() {
607 global $wgLegalTitleChars;
608 return $wgLegalTitleChars;
612 * Returns a simple regex that will match on characters and sequences invalid in titles.
613 * Note that this doesn't pick up many things that could be wrong with titles, but that
614 * replacing this regex with something valid will make many titles valid.
616 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
618 * @return string Regex string
620 static function getTitleInvalidRegex() {
621 wfDeprecated( __METHOD__
, '1.25' );
622 return MediaWikiTitleCodec
::getTitleInvalidRegex();
626 * Utility method for converting a character sequence from bytes to Unicode.
628 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
629 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
631 * @param string $byteClass
634 public static function convertByteClassToUnicodeClass( $byteClass ) {
635 $length = strlen( $byteClass );
637 $x0 = $x1 = $x2 = '';
639 $d0 = $d1 = $d2 = '';
640 // Decoded integer codepoints
641 $ord0 = $ord1 = $ord2 = 0;
643 $r0 = $r1 = $r2 = '';
647 $allowUnicode = false;
648 for ( $pos = 0; $pos < $length; $pos++
) {
649 // Shift the queues down
658 // Load the current input token and decoded values
659 $inChar = $byteClass[$pos];
660 if ( $inChar == '\\' ) {
661 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
662 $x0 = $inChar . $m[0];
663 $d0 = chr( hexdec( $m[1] ) );
664 $pos +
= strlen( $m[0] );
665 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
666 $x0 = $inChar . $m[0];
667 $d0 = chr( octdec( $m[0] ) );
668 $pos +
= strlen( $m[0] );
669 } elseif ( $pos +
1 >= $length ) {
672 $d0 = $byteClass[$pos +
1];
680 // Load the current re-encoded value
681 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
682 $r0 = sprintf( '\x%02x', $ord0 );
683 } elseif ( $ord0 >= 0x80 ) {
684 // Allow unicode if a single high-bit character appears
685 $r0 = sprintf( '\x%02x', $ord0 );
686 $allowUnicode = true;
687 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
693 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
695 if ( $ord2 > $ord0 ) {
697 } elseif ( $ord0 >= 0x80 ) {
699 $allowUnicode = true;
700 if ( $ord2 < 0x80 ) {
701 // Keep the non-unicode section of the range
708 // Reset state to the initial value
709 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
710 } elseif ( $ord2 < 0x80 ) {
715 if ( $ord1 < 0x80 ) {
718 if ( $ord0 < 0x80 ) {
721 if ( $allowUnicode ) {
722 $out .= '\u0080-\uFFFF';
728 * Make a prefixed DB key from a DB key and a namespace index
730 * @param int $ns Numerical representation of the namespace
731 * @param string $title The DB key form the title
732 * @param string $fragment The link fragment (after the "#")
733 * @param string $interwiki The interwiki prefix
734 * @param bool $canonicalNamespace If true, use the canonical name for
735 * $ns instead of the localized version.
736 * @return string The prefixed form of the title
738 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
739 $canonicalNamespace = false
743 if ( $canonicalNamespace ) {
744 $namespace = MWNamespace
::getCanonicalName( $ns );
746 $namespace = $wgContLang->getNsText( $ns );
748 $name = $namespace == '' ?
$title : "$namespace:$title";
749 if ( strval( $interwiki ) != '' ) {
750 $name = "$interwiki:$name";
752 if ( strval( $fragment ) != '' ) {
753 $name .= '#' . $fragment;
759 * Escape a text fragment, say from a link, for a URL
761 * @param string $fragment Containing a URL or link fragment (after the "#")
762 * @return string Escaped string
764 static function escapeFragmentForURL( $fragment ) {
765 # Note that we don't urlencode the fragment. urlencoded Unicode
766 # fragments appear not to work in IE (at least up to 7) or in at least
767 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
768 # to care if they aren't encoded.
769 return Sanitizer
::escapeId( $fragment, 'noninitial' );
773 * Callback for usort() to do title sorts by (namespace, title)
778 * @return int Result of string comparison, or namespace comparison
780 public static function compare( $a, $b ) {
781 if ( $a->getNamespace() == $b->getNamespace() ) {
782 return strcmp( $a->getText(), $b->getText() );
784 return $a->getNamespace() - $b->getNamespace();
789 * Determine whether the object refers to a page within
790 * this project (either this wiki or a wiki with a local
791 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
793 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
795 public function isLocal() {
796 if ( $this->isExternal() ) {
797 $iw = Interwiki
::fetch( $this->mInterwiki
);
799 return $iw->isLocal();
806 * Is this Title interwiki?
810 public function isExternal() {
811 return $this->mInterwiki
!== '';
815 * Get the interwiki prefix
817 * Use Title::isExternal to check if a interwiki is set
819 * @return string Interwiki prefix
821 public function getInterwiki() {
822 return $this->mInterwiki
;
826 * Was this a local interwiki link?
830 public function wasLocalInterwiki() {
831 return $this->mLocalInterwiki
;
835 * Determine whether the object refers to a page within
836 * this project and is transcludable.
838 * @return bool True if this is transcludable
840 public function isTrans() {
841 if ( !$this->isExternal() ) {
845 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
849 * Returns the DB name of the distant wiki which owns the object.
851 * @return string The DB name
853 public function getTransWikiID() {
854 if ( !$this->isExternal() ) {
858 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
862 * Get a TitleValue object representing this Title.
864 * @note Not all valid Titles have a corresponding valid TitleValue
865 * (e.g. TitleValues cannot represent page-local links that have a
866 * fragment but no title text).
868 * @return TitleValue|null
870 public function getTitleValue() {
871 if ( $this->mTitleValue
=== null ) {
873 $this->mTitleValue
= new TitleValue(
874 $this->getNamespace(),
876 $this->getFragment(),
877 $this->getInterwiki()
879 } catch ( InvalidArgumentException
$ex ) {
880 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
881 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
885 return $this->mTitleValue
;
889 * Get the text form (spaces not underscores) of the main part
891 * @return string Main part of the title
893 public function getText() {
894 return $this->mTextform
;
898 * Get the URL-encoded form of the main part
900 * @return string Main part of the title, URL-encoded
902 public function getPartialURL() {
903 return $this->mUrlform
;
907 * Get the main part with underscores
909 * @return string Main part of the title, with underscores
911 public function getDBkey() {
912 return $this->mDbkeyform
;
916 * Get the DB key with the initial letter case as specified by the user
918 * @return string DB key
920 function getUserCaseDBKey() {
921 if ( !is_null( $this->mUserCaseDBKey
) ) {
922 return $this->mUserCaseDBKey
;
924 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
925 return $this->mDbkeyform
;
930 * Get the namespace index, i.e. one of the NS_xxxx constants.
932 * @return int Namespace index
934 public function getNamespace() {
935 return $this->mNamespace
;
939 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
941 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
942 * @return string Content model id
944 public function getContentModel( $flags = 0 ) {
945 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
946 $linkCache = LinkCache
::singleton();
947 $linkCache->addLinkObj( $this ); # in case we already had an article ID
948 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
951 if ( !$this->mContentModel
) {
952 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
955 return $this->mContentModel
;
959 * Convenience method for checking a title's content model name
961 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
962 * @return bool True if $this->getContentModel() == $id
964 public function hasContentModel( $id ) {
965 return $this->getContentModel() == $id;
969 * Get the namespace text
971 * @return string Namespace text
973 public function getNsText() {
974 if ( $this->isExternal() ) {
975 // This probably shouldn't even happen,
976 // but for interwiki transclusion it sometimes does.
977 // Use the canonical namespaces if possible to try to
978 // resolve a foreign namespace.
979 if ( MWNamespace
::exists( $this->mNamespace
) ) {
980 return MWNamespace
::getCanonicalName( $this->mNamespace
);
985 $formatter = self
::getTitleFormatter();
986 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
987 } catch ( InvalidArgumentException
$ex ) {
988 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
994 * Get the namespace text of the subject (rather than talk) page
996 * @return string Namespace text
998 public function getSubjectNsText() {
1000 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1004 * Get the namespace text of the talk page
1006 * @return string Namespace text
1008 public function getTalkNsText() {
1010 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1014 * Could this title have a corresponding talk page?
1018 public function canTalk() {
1019 return MWNamespace
::canTalk( $this->mNamespace
);
1023 * Is this in a namespace that allows actual pages?
1027 public function canExist() {
1028 return $this->mNamespace
>= NS_MAIN
;
1032 * Can this title be added to a user's watchlist?
1036 public function isWatchable() {
1037 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1041 * Returns true if this is a special page.
1045 public function isSpecialPage() {
1046 return $this->getNamespace() == NS_SPECIAL
;
1050 * Returns true if this title resolves to the named special page
1052 * @param string $name The special page name
1055 public function isSpecial( $name ) {
1056 if ( $this->isSpecialPage() ) {
1057 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1058 if ( $name == $thisName ) {
1066 * If the Title refers to a special page alias which is not the local default, resolve
1067 * the alias, and localise the name as necessary. Otherwise, return $this
1071 public function fixSpecialName() {
1072 if ( $this->isSpecialPage() ) {
1073 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1074 if ( $canonicalName ) {
1075 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1076 if ( $localName != $this->mDbkeyform
) {
1077 return Title
::makeTitle( NS_SPECIAL
, $localName );
1085 * Returns true if the title is inside the specified namespace.
1087 * Please make use of this instead of comparing to getNamespace()
1088 * This function is much more resistant to changes we may make
1089 * to namespaces than code that makes direct comparisons.
1090 * @param int $ns The namespace
1094 public function inNamespace( $ns ) {
1095 return MWNamespace
::equals( $this->getNamespace(), $ns );
1099 * Returns true if the title is inside one of the specified namespaces.
1101 * @param int $namespaces,... The namespaces to check for
1105 public function inNamespaces( /* ... */ ) {
1106 $namespaces = func_get_args();
1107 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1108 $namespaces = $namespaces[0];
1111 foreach ( $namespaces as $ns ) {
1112 if ( $this->inNamespace( $ns ) ) {
1121 * Returns true if the title has the same subject namespace as the
1122 * namespace specified.
1123 * For example this method will take NS_USER and return true if namespace
1124 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1125 * as their subject namespace.
1127 * This is MUCH simpler than individually testing for equivalence
1128 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1133 public function hasSubjectNamespace( $ns ) {
1134 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1138 * Is this Title in a namespace which contains content?
1139 * In other words, is this a content page, for the purposes of calculating
1144 public function isContentPage() {
1145 return MWNamespace
::isContent( $this->getNamespace() );
1149 * Would anybody with sufficient privileges be able to move this page?
1150 * Some pages just aren't movable.
1154 public function isMovable() {
1155 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1156 // Interwiki title or immovable namespace. Hooks don't get to override here
1161 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1166 * Is this the mainpage?
1167 * @note Title::newFromText seems to be sufficiently optimized by the title
1168 * cache that we don't need to over-optimize by doing direct comparisons and
1169 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1170 * ends up reporting something differently than $title->isMainPage();
1175 public function isMainPage() {
1176 return $this->equals( Title
::newMainPage() );
1180 * Is this a subpage?
1184 public function isSubpage() {
1185 return MWNamespace
::hasSubpages( $this->mNamespace
)
1186 ?
strpos( $this->getText(), '/' ) !== false
1191 * Is this a conversion table for the LanguageConverter?
1195 public function isConversionTable() {
1196 // @todo ConversionTable should become a separate content model.
1198 return $this->getNamespace() == NS_MEDIAWIKI
&&
1199 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1203 * Does that page contain wikitext, or it is JS, CSS or whatever?
1207 public function isWikitextPage() {
1208 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1212 * Could this page contain custom CSS or JavaScript for the global UI.
1213 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1214 * or CONTENT_MODEL_JAVASCRIPT.
1216 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1219 * Note that this method should not return true for pages that contain and
1220 * show "inactive" CSS or JS.
1223 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1225 public function isCssOrJsPage() {
1226 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1227 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1228 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1230 # @note This hook is also called in ContentHandler::getDefaultModel.
1231 # It's called here again to make sure hook functions can force this
1232 # method to return true even outside the MediaWiki namespace.
1234 Hooks
::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1236 return $isCssOrJsPage;
1240 * Is this a .css or .js subpage of a user page?
1242 * @todo FIXME: Rename to isUserConfigPage()
1244 public function isCssJsSubpage() {
1245 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1246 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1247 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1251 * Trim down a .css or .js subpage title to get the corresponding skin name
1253 * @return string Containing skin name from .css or .js subpage title
1255 public function getSkinFromCssJsSubpage() {
1256 $subpage = explode( '/', $this->mTextform
);
1257 $subpage = $subpage[count( $subpage ) - 1];
1258 $lastdot = strrpos( $subpage, '.' );
1259 if ( $lastdot === false ) {
1260 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1262 return substr( $subpage, 0, $lastdot );
1266 * Is this a .css subpage of a user page?
1270 public function isCssSubpage() {
1271 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1272 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1276 * Is this a .js subpage of a user page?
1280 public function isJsSubpage() {
1281 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1282 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1286 * Is this a talk page of some sort?
1290 public function isTalkPage() {
1291 return MWNamespace
::isTalk( $this->getNamespace() );
1295 * Get a Title object associated with the talk page of this article
1297 * @return Title The object for the talk page
1299 public function getTalkPage() {
1300 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1304 * Get a title object associated with the subject page of this
1307 * @return Title The object for the subject page
1309 public function getSubjectPage() {
1310 // Is this the same title?
1311 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1312 if ( $this->getNamespace() == $subjectNS ) {
1315 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1319 * Get the other title for this page, if this is a subject page
1320 * get the talk page, if it is a subject page get the talk page
1323 * @throws MWException
1326 public function getOtherPage() {
1327 if ( $this->isSpecialPage() ) {
1328 throw new MWException( 'Special pages cannot have other pages' );
1330 if ( $this->isTalkPage() ) {
1331 return $this->getSubjectPage();
1333 return $this->getTalkPage();
1338 * Get the default namespace index, for when there is no namespace
1340 * @return int Default namespace index
1342 public function getDefaultNamespace() {
1343 return $this->mDefaultNamespace
;
1347 * Get the Title fragment (i.e.\ the bit after the #) in text form
1349 * Use Title::hasFragment to check for a fragment
1351 * @return string Title fragment
1353 public function getFragment() {
1354 return $this->mFragment
;
1358 * Check if a Title fragment is set
1363 public function hasFragment() {
1364 return $this->mFragment
!== '';
1368 * Get the fragment in URL form, including the "#" character if there is one
1369 * @return string Fragment in URL form
1371 public function getFragmentForURL() {
1372 if ( !$this->hasFragment() ) {
1375 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1380 * Set the fragment for this title. Removes the first character from the
1381 * specified fragment before setting, so it assumes you're passing it with
1384 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1385 * or Title::createFragmentTarget().
1386 * Still in active use privately.
1389 * @param string $fragment Text
1391 public function setFragment( $fragment ) {
1392 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1396 * Creates a new Title for a different fragment of the same page.
1399 * @param string $fragment
1402 public function createFragmentTarget( $fragment ) {
1403 return self
::makeTitle(
1404 $this->getNamespace(),
1407 $this->getInterwiki()
1413 * Prefix some arbitrary text with the namespace or interwiki prefix
1416 * @param string $name The text
1417 * @return string The prefixed text
1419 private function prefix( $name ) {
1421 if ( $this->isExternal() ) {
1422 $p = $this->mInterwiki
. ':';
1425 if ( 0 != $this->mNamespace
) {
1426 $p .= $this->getNsText() . ':';
1432 * Get the prefixed database key form
1434 * @return string The prefixed title, with underscores and
1435 * any interwiki and namespace prefixes
1437 public function getPrefixedDBkey() {
1438 $s = $this->prefix( $this->mDbkeyform
);
1439 $s = strtr( $s, ' ', '_' );
1444 * Get the prefixed title with spaces.
1445 * This is the form usually used for display
1447 * @return string The prefixed title, with spaces
1449 public function getPrefixedText() {
1450 if ( $this->mPrefixedText
=== null ) {
1451 $s = $this->prefix( $this->mTextform
);
1452 $s = strtr( $s, '_', ' ' );
1453 $this->mPrefixedText
= $s;
1455 return $this->mPrefixedText
;
1459 * Return a string representation of this title
1461 * @return string Representation of this title
1463 public function __toString() {
1464 return $this->getPrefixedText();
1468 * Get the prefixed title with spaces, plus any fragment
1469 * (part beginning with '#')
1471 * @return string The prefixed title, with spaces and the fragment, including '#'
1473 public function getFullText() {
1474 $text = $this->getPrefixedText();
1475 if ( $this->hasFragment() ) {
1476 $text .= '#' . $this->getFragment();
1482 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1486 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1490 * @return string Root name
1493 public function getRootText() {
1494 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1495 return $this->getText();
1498 return strtok( $this->getText(), '/' );
1502 * Get the root page name title, i.e. the leftmost part before any slashes
1506 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1507 * # returns: Title{User:Foo}
1510 * @return Title Root title
1513 public function getRootTitle() {
1514 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1518 * Get the base page name without a namespace, i.e. the part before the subpage name
1522 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1523 * # returns: 'Foo/Bar'
1526 * @return string Base name
1528 public function getBaseText() {
1529 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1530 return $this->getText();
1533 $parts = explode( '/', $this->getText() );
1534 # Don't discard the real title if there's no subpage involved
1535 if ( count( $parts ) > 1 ) {
1536 unset( $parts[count( $parts ) - 1] );
1538 return implode( '/', $parts );
1542 * Get the base page name title, i.e. the part before the subpage name
1546 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1547 * # returns: Title{User:Foo/Bar}
1550 * @return Title Base title
1553 public function getBaseTitle() {
1554 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1558 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1562 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1566 * @return string Subpage name
1568 public function getSubpageText() {
1569 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1570 return $this->mTextform
;
1572 $parts = explode( '/', $this->mTextform
);
1573 return $parts[count( $parts ) - 1];
1577 * Get the title for a subpage of the current page
1581 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1582 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1585 * @param string $text The subpage name to add to the title
1586 * @return Title Subpage title
1589 public function getSubpage( $text ) {
1590 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1594 * Get a URL-encoded form of the subpage text
1596 * @return string URL-encoded subpage name
1598 public function getSubpageUrlForm() {
1599 $text = $this->getSubpageText();
1600 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1605 * Get a URL-encoded title (not an actual URL) including interwiki
1607 * @return string The URL-encoded form
1609 public function getPrefixedURL() {
1610 $s = $this->prefix( $this->mDbkeyform
);
1611 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1616 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1617 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1618 * second argument named variant. This was deprecated in favor
1619 * of passing an array of option with a "variant" key
1620 * Once $query2 is removed for good, this helper can be dropped
1621 * and the wfArrayToCgi moved to getLocalURL();
1623 * @since 1.19 (r105919)
1624 * @param array|string $query
1625 * @param bool $query2
1628 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1629 if ( $query2 !== false ) {
1630 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1631 "method called with a second parameter is deprecated. Add your " .
1632 "parameter to an array passed as the first parameter.", "1.19" );
1634 if ( is_array( $query ) ) {
1635 $query = wfArrayToCgi( $query );
1638 if ( is_string( $query2 ) ) {
1639 // $query2 is a string, we will consider this to be
1640 // a deprecated $variant argument and add it to the query
1641 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1643 $query2 = wfArrayToCgi( $query2 );
1645 // If we have $query content add a & to it first
1649 // Now append the queries together
1656 * Get a real URL referring to this title, with interwiki link and
1659 * @see self::getLocalURL for the arguments.
1661 * @param array|string $query
1662 * @param bool $query2
1663 * @param string $proto Protocol type to use in URL
1664 * @return string The URL
1666 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1667 $query = self
::fixUrlQueryArgs( $query, $query2 );
1669 # Hand off all the decisions on urls to getLocalURL
1670 $url = $this->getLocalURL( $query );
1672 # Expand the url to make it a full url. Note that getLocalURL has the
1673 # potential to output full urls for a variety of reasons, so we use
1674 # wfExpandUrl instead of simply prepending $wgServer
1675 $url = wfExpandUrl( $url, $proto );
1677 # Finally, add the fragment.
1678 $url .= $this->getFragmentForURL();
1680 Hooks
::run( 'GetFullURL', [ &$this, &$url, $query ] );
1685 * Get a URL with no fragment or server name (relative URL) from a Title object.
1686 * If this page is generated with action=render, however,
1687 * $wgServer is prepended to make an absolute URL.
1689 * @see self::getFullURL to always get an absolute URL.
1690 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1691 * valid to link, locally, to the current Title.
1692 * @see self::newFromText to produce a Title object.
1694 * @param string|array $query An optional query string,
1695 * not used for interwiki links. Can be specified as an associative array as well,
1696 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1697 * Some query patterns will trigger various shorturl path replacements.
1698 * @param array $query2 An optional secondary query array. This one MUST
1699 * be an array. If a string is passed it will be interpreted as a deprecated
1700 * variant argument and urlencoded into a variant= argument.
1701 * This second query argument will be added to the $query
1702 * The second parameter is deprecated since 1.19. Pass it as a key,value
1703 * pair in the first parameter array instead.
1705 * @return string String of the URL.
1707 public function getLocalURL( $query = '', $query2 = false ) {
1708 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1710 $query = self
::fixUrlQueryArgs( $query, $query2 );
1712 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1714 $namespace = $this->getNsText();
1715 if ( $namespace != '' ) {
1716 # Can this actually happen? Interwikis shouldn't be parsed.
1717 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1720 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1721 $url = wfAppendQuery( $url, $query );
1723 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1724 if ( $query == '' ) {
1725 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1726 Hooks
::run( 'GetLocalURL::Article', [ &$this, &$url ] );
1728 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1732 if ( !empty( $wgActionPaths )
1733 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1735 $action = urldecode( $matches[2] );
1736 if ( isset( $wgActionPaths[$action] ) ) {
1737 $query = $matches[1];
1738 if ( isset( $matches[4] ) ) {
1739 $query .= $matches[4];
1741 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1742 if ( $query != '' ) {
1743 $url = wfAppendQuery( $url, $query );
1749 && $wgVariantArticlePath
1750 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1751 && $this->getPageLanguage()->hasVariants()
1752 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1754 $variant = urldecode( $matches[1] );
1755 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1756 // Only do the variant replacement if the given variant is a valid
1757 // variant for the page's language.
1758 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1759 $url = str_replace( '$1', $dbkey, $url );
1763 if ( $url === false ) {
1764 if ( $query == '-' ) {
1767 $url = "{$wgScript}?title={$dbkey}&{$query}";
1771 Hooks
::run( 'GetLocalURL::Internal', [ &$this, &$url, $query ] );
1773 // @todo FIXME: This causes breakage in various places when we
1774 // actually expected a local URL and end up with dupe prefixes.
1775 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1776 $url = $wgServer . $url;
1779 Hooks
::run( 'GetLocalURL', [ &$this, &$url, $query ] );
1784 * Get a URL that's the simplest URL that will be valid to link, locally,
1785 * to the current Title. It includes the fragment, but does not include
1786 * the server unless action=render is used (or the link is external). If
1787 * there's a fragment but the prefixed text is empty, we just return a link
1790 * The result obviously should not be URL-escaped, but does need to be
1791 * HTML-escaped if it's being output in HTML.
1793 * @param array $query
1794 * @param bool $query2
1795 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1796 * @see self::getLocalURL for the arguments.
1797 * @return string The URL
1799 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1800 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1801 $ret = $this->getFullURL( $query, $query2, $proto );
1802 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1803 $ret = $this->getFragmentForURL();
1805 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1811 * Get the URL form for an internal link.
1812 * - Used in various CDN-related code, in case we have a different
1813 * internal hostname for the server from the exposed one.
1815 * This uses $wgInternalServer to qualify the path, or $wgServer
1816 * if $wgInternalServer is not set. If the server variable used is
1817 * protocol-relative, the URL will be expanded to http://
1819 * @see self::getLocalURL for the arguments.
1820 * @return string The URL
1822 public function getInternalURL( $query = '', $query2 = false ) {
1823 global $wgInternalServer, $wgServer;
1824 $query = self
::fixUrlQueryArgs( $query, $query2 );
1825 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1826 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1827 Hooks
::run( 'GetInternalURL', [ &$this, &$url, $query ] );
1832 * Get the URL for a canonical link, for use in things like IRC and
1833 * e-mail notifications. Uses $wgCanonicalServer and the
1834 * GetCanonicalURL hook.
1836 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1838 * @see self::getLocalURL for the arguments.
1839 * @return string The URL
1842 public function getCanonicalURL( $query = '', $query2 = false ) {
1843 $query = self
::fixUrlQueryArgs( $query, $query2 );
1844 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1845 Hooks
::run( 'GetCanonicalURL', [ &$this, &$url, $query ] );
1850 * Get the edit URL for this Title
1852 * @return string The URL, or a null string if this is an interwiki link
1854 public function getEditURL() {
1855 if ( $this->isExternal() ) {
1858 $s = $this->getLocalURL( 'action=edit' );
1864 * Can $user perform $action on this page?
1865 * This skips potentially expensive cascading permission checks
1866 * as well as avoids expensive error formatting
1868 * Suitable for use for nonessential UI controls in common cases, but
1869 * _not_ for functional access control.
1871 * May provide false positives, but should never provide a false negative.
1873 * @param string $action Action that permission needs to be checked for
1874 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1877 public function quickUserCan( $action, $user = null ) {
1878 return $this->userCan( $action, $user, false );
1882 * Can $user perform $action on this page?
1884 * @param string $action Action that permission needs to be checked for
1885 * @param User $user User to check (since 1.19); $wgUser will be used if not
1887 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1890 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1891 if ( !$user instanceof User
) {
1896 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1900 * Can $user perform $action on this page?
1902 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1904 * @param string $action Action that permission needs to be checked for
1905 * @param User $user User to check
1906 * @param string $rigor One of (quick,full,secure)
1907 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1908 * - full : does cheap and expensive checks possibly from a slave
1909 * - secure : does cheap and expensive checks, using the master as needed
1910 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1911 * whose corresponding errors may be ignored.
1912 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1914 public function getUserPermissionsErrors(
1915 $action, $user, $rigor = 'secure', $ignoreErrors = []
1917 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1919 // Remove the errors being ignored.
1920 foreach ( $errors as $index => $error ) {
1921 $errKey = is_array( $error ) ?
$error[0] : $error;
1923 if ( in_array( $errKey, $ignoreErrors ) ) {
1924 unset( $errors[$index] );
1926 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1927 unset( $errors[$index] );
1935 * Permissions checks that fail most often, and which are easiest to test.
1937 * @param string $action The action to check
1938 * @param User $user User to check
1939 * @param array $errors List of current errors
1940 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1941 * @param bool $short Short circuit on first error
1943 * @return array List of errors
1945 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1946 if ( !Hooks
::run( 'TitleQuickPermissions',
1947 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1952 if ( $action == 'create' ) {
1954 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1955 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1957 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1959 } elseif ( $action == 'move' ) {
1960 if ( !$user->isAllowed( 'move-rootuserpages' )
1961 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1962 // Show user page-specific message only if the user can move other pages
1963 $errors[] = [ 'cant-move-user-page' ];
1966 // Check if user is allowed to move files if it's a file
1967 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1968 $errors[] = [ 'movenotallowedfile' ];
1971 // Check if user is allowed to move category pages if it's a category page
1972 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1973 $errors[] = [ 'cant-move-category-page' ];
1976 if ( !$user->isAllowed( 'move' ) ) {
1977 // User can't move anything
1978 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1979 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1980 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1981 // custom message if logged-in users without any special rights can move
1982 $errors[] = [ 'movenologintext' ];
1984 $errors[] = [ 'movenotallowed' ];
1987 } elseif ( $action == 'move-target' ) {
1988 if ( !$user->isAllowed( 'move' ) ) {
1989 // User can't move anything
1990 $errors[] = [ 'movenotallowed' ];
1991 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1992 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1993 // Show user page-specific message only if the user can move other pages
1994 $errors[] = [ 'cant-move-to-user-page' ];
1995 } elseif ( !$user->isAllowed( 'move-categorypages' )
1996 && $this->mNamespace
== NS_CATEGORY
) {
1997 // Show category page-specific message only if the user can move other pages
1998 $errors[] = [ 'cant-move-to-category-page' ];
2000 } elseif ( !$user->isAllowed( $action ) ) {
2001 $errors[] = $this->missingPermissionError( $action, $short );
2008 * Add the resulting error code to the errors array
2010 * @param array $errors List of current errors
2011 * @param array $result Result of errors
2013 * @return array List of errors
2015 private function resultToError( $errors, $result ) {
2016 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2017 // A single array representing an error
2018 $errors[] = $result;
2019 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2020 // A nested array representing multiple errors
2021 $errors = array_merge( $errors, $result );
2022 } elseif ( $result !== '' && is_string( $result ) ) {
2023 // A string representing a message-id
2024 $errors[] = [ $result ];
2025 } elseif ( $result instanceof MessageSpecifier
) {
2026 // A message specifier representing an error
2027 $errors[] = [ $result ];
2028 } elseif ( $result === false ) {
2029 // a generic "We don't want them to do that"
2030 $errors[] = [ 'badaccess-group0' ];
2036 * Check various permission hooks
2038 * @param string $action The action to check
2039 * @param User $user User to check
2040 * @param array $errors List of current errors
2041 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2042 * @param bool $short Short circuit on first error
2044 * @return array List of errors
2046 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2047 // Use getUserPermissionsErrors instead
2049 if ( !Hooks
::run( 'userCan', [ &$this, &$user, $action, &$result ] ) ) {
2050 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2052 // Check getUserPermissionsErrors hook
2053 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$this, &$user, $action, &$result ] ) ) {
2054 $errors = $this->resultToError( $errors, $result );
2056 // Check getUserPermissionsErrorsExpensive hook
2059 && !( $short && count( $errors ) > 0 )
2060 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$this, &$user, $action, &$result ] )
2062 $errors = $this->resultToError( $errors, $result );
2069 * Check permissions on special pages & namespaces
2071 * @param string $action The action to check
2072 * @param User $user User to check
2073 * @param array $errors List of current errors
2074 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2075 * @param bool $short Short circuit on first error
2077 * @return array List of errors
2079 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2080 # Only 'createaccount' can be performed on special pages,
2081 # which don't actually exist in the DB.
2082 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2083 $errors[] = [ 'ns-specialprotected' ];
2086 # Check $wgNamespaceProtection for restricted namespaces
2087 if ( $this->isNamespaceProtected( $user ) ) {
2088 $ns = $this->mNamespace
== NS_MAIN ?
2089 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2090 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2091 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2098 * Check CSS/JS sub-page permissions
2100 * @param string $action The action to check
2101 * @param User $user User to check
2102 * @param array $errors List of current errors
2103 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2104 * @param bool $short Short circuit on first error
2106 * @return array List of errors
2108 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2109 # Protect css/js subpages of user pages
2110 # XXX: this might be better using restrictions
2111 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2112 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2113 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2114 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2115 $errors[] = [ 'mycustomcssprotected', $action ];
2116 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2117 $errors[] = [ 'mycustomjsprotected', $action ];
2120 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2121 $errors[] = [ 'customcssprotected', $action ];
2122 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2123 $errors[] = [ 'customjsprotected', $action ];
2132 * Check against page_restrictions table requirements on this
2133 * page. The user must possess all required rights for this
2136 * @param string $action The action to check
2137 * @param User $user User to check
2138 * @param array $errors List of current errors
2139 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2140 * @param bool $short Short circuit on first error
2142 * @return array List of errors
2144 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2145 foreach ( $this->getRestrictions( $action ) as $right ) {
2146 // Backwards compatibility, rewrite sysop -> editprotected
2147 if ( $right == 'sysop' ) {
2148 $right = 'editprotected';
2150 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2151 if ( $right == 'autoconfirmed' ) {
2152 $right = 'editsemiprotected';
2154 if ( $right == '' ) {
2157 if ( !$user->isAllowed( $right ) ) {
2158 $errors[] = [ 'protectedpagetext', $right, $action ];
2159 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2160 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2168 * Check restrictions on cascading pages.
2170 * @param string $action The action to check
2171 * @param User $user User to check
2172 * @param array $errors List of current errors
2173 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2174 * @param bool $short Short circuit on first error
2176 * @return array List of errors
2178 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2179 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2180 # We /could/ use the protection level on the source page, but it's
2181 # fairly ugly as we have to establish a precedence hierarchy for pages
2182 # included by multiple cascade-protected pages. So just restrict
2183 # it to people with 'protect' permission, as they could remove the
2184 # protection anyway.
2185 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2186 # Cascading protection depends on more than this page...
2187 # Several cascading protected pages may include this page...
2188 # Check each cascading level
2189 # This is only for protection restrictions, not for all actions
2190 if ( isset( $restrictions[$action] ) ) {
2191 foreach ( $restrictions[$action] as $right ) {
2192 // Backwards compatibility, rewrite sysop -> editprotected
2193 if ( $right == 'sysop' ) {
2194 $right = 'editprotected';
2196 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2197 if ( $right == 'autoconfirmed' ) {
2198 $right = 'editsemiprotected';
2200 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2202 foreach ( $cascadingSources as $page ) {
2203 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2205 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2215 * Check action permissions not already checked in checkQuickPermissions
2217 * @param string $action The action to check
2218 * @param User $user User to check
2219 * @param array $errors List of current errors
2220 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2221 * @param bool $short Short circuit on first error
2223 * @return array List of errors
2225 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2226 global $wgDeleteRevisionsLimit, $wgLang;
2228 if ( $action == 'protect' ) {
2229 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2230 // If they can't edit, they shouldn't protect.
2231 $errors[] = [ 'protect-cantedit' ];
2233 } elseif ( $action == 'create' ) {
2234 $title_protection = $this->getTitleProtection();
2235 if ( $title_protection ) {
2236 if ( $title_protection['permission'] == ''
2237 ||
!$user->isAllowed( $title_protection['permission'] )
2241 User
::whoIs( $title_protection['user'] ),
2242 $title_protection['reason']
2246 } elseif ( $action == 'move' ) {
2247 // Check for immobile pages
2248 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2249 // Specific message for this case
2250 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2251 } elseif ( !$this->isMovable() ) {
2252 // Less specific message for rarer cases
2253 $errors[] = [ 'immobile-source-page' ];
2255 } elseif ( $action == 'move-target' ) {
2256 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2257 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2258 } elseif ( !$this->isMovable() ) {
2259 $errors[] = [ 'immobile-target-page' ];
2261 } elseif ( $action == 'delete' ) {
2262 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2263 if ( !$tempErrors ) {
2264 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2265 $user, $tempErrors, $rigor, true );
2267 if ( $tempErrors ) {
2268 // If protection keeps them from editing, they shouldn't be able to delete.
2269 $errors[] = [ 'deleteprotected' ];
2271 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2272 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2274 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2281 * Check that the user isn't blocked from editing.
2283 * @param string $action The action to check
2284 * @param User $user User to check
2285 * @param array $errors List of current errors
2286 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2287 * @param bool $short Short circuit on first error
2289 * @return array List of errors
2291 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2292 // Account creation blocks handled at userlogin.
2293 // Unblocking handled in SpecialUnblock
2294 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2298 global $wgEmailConfirmToEdit;
2300 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2301 $errors[] = [ 'confirmedittext' ];
2304 $useSlave = ( $rigor !== 'secure' );
2305 if ( ( $action == 'edit' ||
$action == 'create' )
2306 && !$user->isBlockedFrom( $this, $useSlave )
2308 // Don't block the user from editing their own talk page unless they've been
2309 // explicitly blocked from that too.
2310 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2311 // @todo FIXME: Pass the relevant context into this function.
2312 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2319 * Check that the user is allowed to read this page.
2321 * @param string $action The action to check
2322 * @param User $user User to check
2323 * @param array $errors List of current errors
2324 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2325 * @param bool $short Short circuit on first error
2327 * @return array List of errors
2329 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2330 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2332 $whitelisted = false;
2333 if ( User
::isEveryoneAllowed( 'read' ) ) {
2334 # Shortcut for public wikis, allows skipping quite a bit of code
2335 $whitelisted = true;
2336 } elseif ( $user->isAllowed( 'read' ) ) {
2337 # If the user is allowed to read pages, he is allowed to read all pages
2338 $whitelisted = true;
2339 } elseif ( $this->isSpecial( 'Userlogin' )
2340 ||
$this->isSpecial( 'ChangePassword' )
2341 ||
$this->isSpecial( 'PasswordReset' )
2343 # Always grant access to the login page.
2344 # Even anons need to be able to log in.
2345 $whitelisted = true;
2346 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2347 # Time to check the whitelist
2348 # Only do these checks is there's something to check against
2349 $name = $this->getPrefixedText();
2350 $dbName = $this->getPrefixedDBkey();
2352 // Check for explicit whitelisting with and without underscores
2353 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2354 $whitelisted = true;
2355 } elseif ( $this->getNamespace() == NS_MAIN
) {
2356 # Old settings might have the title prefixed with
2357 # a colon for main-namespace pages
2358 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2359 $whitelisted = true;
2361 } elseif ( $this->isSpecialPage() ) {
2362 # If it's a special page, ditch the subpage bit and check again
2363 $name = $this->getDBkey();
2364 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2366 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2367 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2368 $whitelisted = true;
2374 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2375 $name = $this->getPrefixedText();
2376 // Check for regex whitelisting
2377 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2378 if ( preg_match( $listItem, $name ) ) {
2379 $whitelisted = true;
2385 if ( !$whitelisted ) {
2386 # If the title is not whitelisted, give extensions a chance to do so...
2387 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2388 if ( !$whitelisted ) {
2389 $errors[] = $this->missingPermissionError( $action, $short );
2397 * Get a description array when the user doesn't have the right to perform
2398 * $action (i.e. when User::isAllowed() returns false)
2400 * @param string $action The action to check
2401 * @param bool $short Short circuit on first error
2402 * @return array List of errors
2404 private function missingPermissionError( $action, $short ) {
2405 // We avoid expensive display logic for quickUserCan's and such
2407 return [ 'badaccess-group0' ];
2410 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2411 User
::getGroupsWithPermission( $action ) );
2413 if ( count( $groups ) ) {
2417 $wgLang->commaList( $groups ),
2421 return [ 'badaccess-group0' ];
2426 * Can $user perform $action on this page? This is an internal function,
2427 * with multiple levels of checks depending on performance needs; see $rigor below.
2428 * It does not check wfReadOnly().
2430 * @param string $action Action that permission needs to be checked for
2431 * @param User $user User to check
2432 * @param string $rigor One of (quick,full,secure)
2433 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2434 * - full : does cheap and expensive checks possibly from a slave
2435 * - secure : does cheap and expensive checks, using the master as needed
2436 * @param bool $short Set this to true to stop after the first permission error.
2437 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2439 protected function getUserPermissionsErrorsInternal(
2440 $action, $user, $rigor = 'secure', $short = false
2442 if ( $rigor === true ) {
2443 $rigor = 'secure'; // b/c
2444 } elseif ( $rigor === false ) {
2445 $rigor = 'quick'; // b/c
2446 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2447 throw new Exception( "Invalid rigor parameter '$rigor'." );
2450 # Read has special handling
2451 if ( $action == 'read' ) {
2453 'checkPermissionHooks',
2454 'checkReadPermissions',
2456 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2457 # here as it will lead to duplicate error messages. This is okay to do
2458 # since anywhere that checks for create will also check for edit, and
2459 # those checks are called for edit.
2460 } elseif ( $action == 'create' ) {
2462 'checkQuickPermissions',
2463 'checkPermissionHooks',
2464 'checkPageRestrictions',
2465 'checkCascadingSourcesRestrictions',
2466 'checkActionPermissions',
2471 'checkQuickPermissions',
2472 'checkPermissionHooks',
2473 'checkSpecialsAndNSPermissions',
2474 'checkCSSandJSPermissions',
2475 'checkPageRestrictions',
2476 'checkCascadingSourcesRestrictions',
2477 'checkActionPermissions',
2483 while ( count( $checks ) > 0 &&
2484 !( $short && count( $errors ) > 0 ) ) {
2485 $method = array_shift( $checks );
2486 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2493 * Get a filtered list of all restriction types supported by this wiki.
2494 * @param bool $exists True to get all restriction types that apply to
2495 * titles that do exist, False for all restriction types that apply to
2496 * titles that do not exist
2499 public static function getFilteredRestrictionTypes( $exists = true ) {
2500 global $wgRestrictionTypes;
2501 $types = $wgRestrictionTypes;
2503 # Remove the create restriction for existing titles
2504 $types = array_diff( $types, [ 'create' ] );
2506 # Only the create and upload restrictions apply to non-existing titles
2507 $types = array_intersect( $types, [ 'create', 'upload' ] );
2513 * Returns restriction types for the current Title
2515 * @return array Applicable restriction types
2517 public function getRestrictionTypes() {
2518 if ( $this->isSpecialPage() ) {
2522 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2524 if ( $this->getNamespace() != NS_FILE
) {
2525 # Remove the upload restriction for non-file titles
2526 $types = array_diff( $types, [ 'upload' ] );
2529 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2531 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2532 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2538 * Is this title subject to title protection?
2539 * Title protection is the one applied against creation of such title.
2541 * @return array|bool An associative array representing any existent title
2542 * protection, or false if there's none.
2544 public function getTitleProtection() {
2545 // Can't protect pages in special namespaces
2546 if ( $this->getNamespace() < 0 ) {
2550 // Can't protect pages that exist.
2551 if ( $this->exists() ) {
2555 if ( $this->mTitleProtection
=== null ) {
2556 $dbr = wfGetDB( DB_SLAVE
);
2557 $res = $dbr->select(
2560 'user' => 'pt_user',
2561 'reason' => 'pt_reason',
2562 'expiry' => 'pt_expiry',
2563 'permission' => 'pt_create_perm'
2565 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2569 // fetchRow returns false if there are no rows.
2570 $row = $dbr->fetchRow( $res );
2572 if ( $row['permission'] == 'sysop' ) {
2573 $row['permission'] = 'editprotected'; // B/C
2575 if ( $row['permission'] == 'autoconfirmed' ) {
2576 $row['permission'] = 'editsemiprotected'; // B/C
2578 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2580 $this->mTitleProtection
= $row;
2582 return $this->mTitleProtection
;
2586 * Remove any title protection due to page existing
2588 public function deleteTitleProtection() {
2589 $dbw = wfGetDB( DB_MASTER
);
2593 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2596 $this->mTitleProtection
= false;
2600 * Is this page "semi-protected" - the *only* protection levels are listed
2601 * in $wgSemiprotectedRestrictionLevels?
2603 * @param string $action Action to check (default: edit)
2606 public function isSemiProtected( $action = 'edit' ) {
2607 global $wgSemiprotectedRestrictionLevels;
2609 $restrictions = $this->getRestrictions( $action );
2610 $semi = $wgSemiprotectedRestrictionLevels;
2611 if ( !$restrictions ||
!$semi ) {
2612 // Not protected, or all protection is full protection
2616 // Remap autoconfirmed to editsemiprotected for BC
2617 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2618 $semi[$key] = 'editsemiprotected';
2620 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2621 $restrictions[$key] = 'editsemiprotected';
2624 return !array_diff( $restrictions, $semi );
2628 * Does the title correspond to a protected article?
2630 * @param string $action The action the page is protected from,
2631 * by default checks all actions.
2634 public function isProtected( $action = '' ) {
2635 global $wgRestrictionLevels;
2637 $restrictionTypes = $this->getRestrictionTypes();
2639 # Special pages have inherent protection
2640 if ( $this->isSpecialPage() ) {
2644 # Check regular protection levels
2645 foreach ( $restrictionTypes as $type ) {
2646 if ( $action == $type ||
$action == '' ) {
2647 $r = $this->getRestrictions( $type );
2648 foreach ( $wgRestrictionLevels as $level ) {
2649 if ( in_array( $level, $r ) && $level != '' ) {
2660 * Determines if $user is unable to edit this page because it has been protected
2661 * by $wgNamespaceProtection.
2663 * @param User $user User object to check permissions
2666 public function isNamespaceProtected( User
$user ) {
2667 global $wgNamespaceProtection;
2669 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2670 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2671 if ( $right != '' && !$user->isAllowed( $right ) ) {
2680 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2682 * @return bool If the page is subject to cascading restrictions.
2684 public function isCascadeProtected() {
2685 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2686 return ( $sources > 0 );
2690 * Determines whether cascading protection sources have already been loaded from
2693 * @param bool $getPages True to check if the pages are loaded, or false to check
2694 * if the status is loaded.
2695 * @return bool Whether or not the specified information has been loaded
2698 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2699 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2703 * Cascading protection: Get the source of any cascading restrictions on this page.
2705 * @param bool $getPages Whether or not to retrieve the actual pages
2706 * that the restrictions have come from and the actual restrictions
2708 * @return array Two elements: First is an array of Title objects of the
2709 * pages from which cascading restrictions have come, false for
2710 * none, or true if such restrictions exist but $getPages was not
2711 * set. Second is an array like that returned by
2712 * Title::getAllRestrictions(), or an empty array if $getPages is
2715 public function getCascadeProtectionSources( $getPages = true ) {
2716 $pagerestrictions = [];
2718 if ( $this->mCascadeSources
!== null && $getPages ) {
2719 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2720 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2721 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2724 $dbr = wfGetDB( DB_SLAVE
);
2726 if ( $this->getNamespace() == NS_FILE
) {
2727 $tables = [ 'imagelinks', 'page_restrictions' ];
2729 'il_to' => $this->getDBkey(),
2734 $tables = [ 'templatelinks', 'page_restrictions' ];
2736 'tl_namespace' => $this->getNamespace(),
2737 'tl_title' => $this->getDBkey(),
2744 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2745 'pr_expiry', 'pr_type', 'pr_level' ];
2746 $where_clauses[] = 'page_id=pr_page';
2749 $cols = [ 'pr_expiry' ];
2752 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2754 $sources = $getPages ?
[] : false;
2755 $now = wfTimestampNow();
2757 foreach ( $res as $row ) {
2758 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2759 if ( $expiry > $now ) {
2761 $page_id = $row->pr_page
;
2762 $page_ns = $row->page_namespace
;
2763 $page_title = $row->page_title
;
2764 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2765 # Add groups needed for each restriction type if its not already there
2766 # Make sure this restriction type still exists
2768 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2769 $pagerestrictions[$row->pr_type
] = [];
2773 isset( $pagerestrictions[$row->pr_type
] )
2774 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2776 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2785 $this->mCascadeSources
= $sources;
2786 $this->mCascadingRestrictions
= $pagerestrictions;
2788 $this->mHasCascadingRestrictions
= $sources;
2791 return [ $sources, $pagerestrictions ];
2795 * Accessor for mRestrictionsLoaded
2797 * @return bool Whether or not the page's restrictions have already been
2798 * loaded from the database
2801 public function areRestrictionsLoaded() {
2802 return $this->mRestrictionsLoaded
;
2806 * Accessor/initialisation for mRestrictions
2808 * @param string $action Action that permission needs to be checked for
2809 * @return array Restriction levels needed to take the action. All levels are
2810 * required. Note that restriction levels are normally user rights, but 'sysop'
2811 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2812 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2814 public function getRestrictions( $action ) {
2815 if ( !$this->mRestrictionsLoaded
) {
2816 $this->loadRestrictions();
2818 return isset( $this->mRestrictions
[$action] )
2819 ?
$this->mRestrictions
[$action]
2824 * Accessor/initialisation for mRestrictions
2826 * @return array Keys are actions, values are arrays as returned by
2827 * Title::getRestrictions()
2830 public function getAllRestrictions() {
2831 if ( !$this->mRestrictionsLoaded
) {
2832 $this->loadRestrictions();
2834 return $this->mRestrictions
;
2838 * Get the expiry time for the restriction against a given action
2840 * @param string $action
2841 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2842 * or not protected at all, or false if the action is not recognised.
2844 public function getRestrictionExpiry( $action ) {
2845 if ( !$this->mRestrictionsLoaded
) {
2846 $this->loadRestrictions();
2848 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2852 * Returns cascading restrictions for the current article
2856 function areRestrictionsCascading() {
2857 if ( !$this->mRestrictionsLoaded
) {
2858 $this->loadRestrictions();
2861 return $this->mCascadeRestriction
;
2865 * Loads a string into mRestrictions array
2867 * @param ResultWrapper $res Resource restrictions as an SQL result.
2868 * @param string $oldFashionedRestrictions Comma-separated list of page
2869 * restrictions from page table (pre 1.10)
2871 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2874 foreach ( $res as $row ) {
2878 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2882 * Compiles list of active page restrictions from both page table (pre 1.10)
2883 * and page_restrictions table for this existing page.
2884 * Public for usage by LiquidThreads.
2886 * @param array $rows Array of db result objects
2887 * @param string $oldFashionedRestrictions Comma-separated list of page
2888 * restrictions from page table (pre 1.10)
2890 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2891 $dbr = wfGetDB( DB_SLAVE
);
2893 $restrictionTypes = $this->getRestrictionTypes();
2895 foreach ( $restrictionTypes as $type ) {
2896 $this->mRestrictions
[$type] = [];
2897 $this->mRestrictionsExpiry
[$type] = 'infinity';
2900 $this->mCascadeRestriction
= false;
2902 # Backwards-compatibility: also load the restrictions from the page record (old format).
2903 if ( $oldFashionedRestrictions !== null ) {
2904 $this->mOldRestrictions
= $oldFashionedRestrictions;
2907 if ( $this->mOldRestrictions
=== false ) {
2908 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2909 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2912 if ( $this->mOldRestrictions
!= '' ) {
2913 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2914 $temp = explode( '=', trim( $restrict ) );
2915 if ( count( $temp ) == 1 ) {
2916 // old old format should be treated as edit/move restriction
2917 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2918 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2920 $restriction = trim( $temp[1] );
2921 if ( $restriction != '' ) { // some old entries are empty
2922 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2928 if ( count( $rows ) ) {
2929 # Current system - load second to make them override.
2930 $now = wfTimestampNow();
2932 # Cycle through all the restrictions.
2933 foreach ( $rows as $row ) {
2935 // Don't take care of restrictions types that aren't allowed
2936 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2940 // This code should be refactored, now that it's being used more generally,
2941 // But I don't really see any harm in leaving it in Block for now -werdna
2942 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2944 // Only apply the restrictions if they haven't expired!
2945 if ( !$expiry ||
$expiry > $now ) {
2946 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2947 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2949 $this->mCascadeRestriction |
= $row->pr_cascade
;
2954 $this->mRestrictionsLoaded
= true;
2958 * Load restrictions from the page_restrictions table
2960 * @param string $oldFashionedRestrictions Comma-separated list of page
2961 * restrictions from page table (pre 1.10)
2963 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2964 if ( !$this->mRestrictionsLoaded
) {
2965 $dbr = wfGetDB( DB_SLAVE
);
2966 if ( $this->exists() ) {
2967 $res = $dbr->select(
2968 'page_restrictions',
2969 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2970 [ 'pr_page' => $this->getArticleID() ],
2974 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2976 $title_protection = $this->getTitleProtection();
2978 if ( $title_protection ) {
2979 $now = wfTimestampNow();
2980 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2982 if ( !$expiry ||
$expiry > $now ) {
2983 // Apply the restrictions
2984 $this->mRestrictionsExpiry
['create'] = $expiry;
2985 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
2986 } else { // Get rid of the old restrictions
2987 $this->mTitleProtection
= false;
2990 $this->mRestrictionsExpiry
['create'] = 'infinity';
2992 $this->mRestrictionsLoaded
= true;
2998 * Flush the protection cache in this object and force reload from the database.
2999 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3001 public function flushRestrictions() {
3002 $this->mRestrictionsLoaded
= false;
3003 $this->mTitleProtection
= null;
3007 * Purge expired restrictions from the page_restrictions table
3009 static function purgeExpiredRestrictions() {
3010 if ( wfReadOnly() ) {
3014 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3015 wfGetDB( DB_MASTER
),
3017 function ( IDatabase
$dbw, $fname ) {
3019 'page_restrictions',
3020 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3025 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3033 * Does this have subpages? (Warning, usually requires an extra DB query.)
3037 public function hasSubpages() {
3038 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3043 # We dynamically add a member variable for the purpose of this method
3044 # alone to cache the result. There's no point in having it hanging
3045 # around uninitialized in every Title object; therefore we only add it
3046 # if needed and don't declare it statically.
3047 if ( $this->mHasSubpages
=== null ) {
3048 $this->mHasSubpages
= false;
3049 $subpages = $this->getSubpages( 1 );
3050 if ( $subpages instanceof TitleArray
) {
3051 $this->mHasSubpages
= (bool)$subpages->count();
3055 return $this->mHasSubpages
;
3059 * Get all subpages of this page.
3061 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3062 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3063 * doesn't allow subpages
3065 public function getSubpages( $limit = -1 ) {
3066 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3070 $dbr = wfGetDB( DB_SLAVE
);
3071 $conds['page_namespace'] = $this->getNamespace();
3072 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3074 if ( $limit > -1 ) {
3075 $options['LIMIT'] = $limit;
3077 $this->mSubpages
= TitleArray
::newFromResult(
3078 $dbr->select( 'page',
3079 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3085 return $this->mSubpages
;
3089 * Is there a version of this page in the deletion archive?
3091 * @return int The number of archived revisions
3093 public function isDeleted() {
3094 if ( $this->getNamespace() < 0 ) {
3097 $dbr = wfGetDB( DB_SLAVE
);
3099 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3100 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3103 if ( $this->getNamespace() == NS_FILE
) {
3104 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3105 [ 'fa_name' => $this->getDBkey() ],
3114 * Is there a version of this page in the deletion archive?
3118 public function isDeletedQuick() {
3119 if ( $this->getNamespace() < 0 ) {
3122 $dbr = wfGetDB( DB_SLAVE
);
3123 $deleted = (bool)$dbr->selectField( 'archive', '1',
3124 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3127 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3128 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3129 [ 'fa_name' => $this->getDBkey() ],
3137 * Get the article ID for this Title from the link cache,
3138 * adding it if necessary
3140 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3142 * @return int The ID
3144 public function getArticleID( $flags = 0 ) {
3145 if ( $this->getNamespace() < 0 ) {
3146 $this->mArticleID
= 0;
3147 return $this->mArticleID
;
3149 $linkCache = LinkCache
::singleton();
3150 if ( $flags & self
::GAID_FOR_UPDATE
) {
3151 $oldUpdate = $linkCache->forUpdate( true );
3152 $linkCache->clearLink( $this );
3153 $this->mArticleID
= $linkCache->addLinkObj( $this );
3154 $linkCache->forUpdate( $oldUpdate );
3156 if ( -1 == $this->mArticleID
) {
3157 $this->mArticleID
= $linkCache->addLinkObj( $this );
3160 return $this->mArticleID
;
3164 * Is this an article that is a redirect page?
3165 * Uses link cache, adding it if necessary
3167 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3170 public function isRedirect( $flags = 0 ) {
3171 if ( !is_null( $this->mRedirect
) ) {
3172 return $this->mRedirect
;
3174 if ( !$this->getArticleID( $flags ) ) {
3175 $this->mRedirect
= false;
3176 return $this->mRedirect
;
3179 $linkCache = LinkCache
::singleton();
3180 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3181 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3182 if ( $cached === null ) {
3183 # Trust LinkCache's state over our own
3184 # LinkCache is telling us that the page doesn't exist, despite there being cached
3185 # data relating to an existing page in $this->mArticleID. Updaters should clear
3186 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3187 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3188 # LinkCache to refresh its data from the master.
3189 $this->mRedirect
= false;
3190 return $this->mRedirect
;
3193 $this->mRedirect
= (bool)$cached;
3195 return $this->mRedirect
;
3199 * What is the length of this page?
3200 * Uses link cache, adding it if necessary
3202 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3205 public function getLength( $flags = 0 ) {
3206 if ( $this->mLength
!= -1 ) {
3207 return $this->mLength
;
3209 if ( !$this->getArticleID( $flags ) ) {
3211 return $this->mLength
;
3213 $linkCache = LinkCache
::singleton();
3214 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3215 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3216 if ( $cached === null ) {
3217 # Trust LinkCache's state over our own, as for isRedirect()
3219 return $this->mLength
;
3222 $this->mLength
= intval( $cached );
3224 return $this->mLength
;
3228 * What is the page_latest field for this page?
3230 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3231 * @return int Int or 0 if the page doesn't exist
3233 public function getLatestRevID( $flags = 0 ) {
3234 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3235 return intval( $this->mLatestID
);
3237 if ( !$this->getArticleID( $flags ) ) {
3238 $this->mLatestID
= 0;
3239 return $this->mLatestID
;
3241 $linkCache = LinkCache
::singleton();
3242 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3243 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3244 if ( $cached === null ) {
3245 # Trust LinkCache's state over our own, as for isRedirect()
3246 $this->mLatestID
= 0;
3247 return $this->mLatestID
;
3250 $this->mLatestID
= intval( $cached );
3252 return $this->mLatestID
;
3256 * This clears some fields in this object, and clears any associated
3257 * keys in the "bad links" section of the link cache.
3259 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3260 * loading of the new page_id. It's also called from
3261 * WikiPage::doDeleteArticleReal()
3263 * @param int $newid The new Article ID
3265 public function resetArticleID( $newid ) {
3266 $linkCache = LinkCache
::singleton();
3267 $linkCache->clearLink( $this );
3269 if ( $newid === false ) {
3270 $this->mArticleID
= -1;
3272 $this->mArticleID
= intval( $newid );
3274 $this->mRestrictionsLoaded
= false;
3275 $this->mRestrictions
= [];
3276 $this->mOldRestrictions
= false;
3277 $this->mRedirect
= null;
3278 $this->mLength
= -1;
3279 $this->mLatestID
= false;
3280 $this->mContentModel
= false;
3281 $this->mEstimateRevisions
= null;
3282 $this->mPageLanguage
= false;
3283 $this->mDbPageLanguage
= false;
3284 $this->mIsBigDeletion
= null;
3287 public static function clearCaches() {
3288 $linkCache = LinkCache
::singleton();
3289 $linkCache->clear();
3291 $titleCache = self
::getTitleCache();
3292 $titleCache->clear();
3296 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3298 * @param string $text Containing title to capitalize
3299 * @param int $ns Namespace index, defaults to NS_MAIN
3300 * @return string Containing capitalized title
3302 public static function capitalize( $text, $ns = NS_MAIN
) {
3305 if ( MWNamespace
::isCapitalized( $ns ) ) {
3306 return $wgContLang->ucfirst( $text );
3313 * Secure and split - main initialisation function for this object
3315 * Assumes that mDbkeyform has been set, and is urldecoded
3316 * and uses underscores, but not otherwise munged. This function
3317 * removes illegal characters, splits off the interwiki and
3318 * namespace prefixes, sets the other forms, and canonicalizes
3321 * @throws MalformedTitleException On invalid titles
3322 * @return bool True on success
3324 private function secureAndSplit() {
3326 $this->mInterwiki
= '';
3327 $this->mFragment
= '';
3328 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3330 $dbkey = $this->mDbkeyform
;
3332 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3333 // the parsing code with Title, while avoiding massive refactoring.
3334 // @todo: get rid of secureAndSplit, refactor parsing code.
3335 $titleParser = self
::getMediaWikiTitleCodec();
3336 // MalformedTitleException can be thrown here
3337 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3340 $this->setFragment( '#' . $parts['fragment'] );
3341 $this->mInterwiki
= $parts['interwiki'];
3342 $this->mLocalInterwiki
= $parts['local_interwiki'];
3343 $this->mNamespace
= $parts['namespace'];
3344 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3346 $this->mDbkeyform
= $parts['dbkey'];
3347 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3348 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3350 # We already know that some pages won't be in the database!
3351 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3352 $this->mArticleID
= 0;
3359 * Get an array of Title objects linking to this Title
3360 * Also stores the IDs in the link cache.
3362 * WARNING: do not use this function on arbitrary user-supplied titles!
3363 * On heavily-used templates it will max out the memory.
3365 * @param array $options May be FOR UPDATE
3366 * @param string $table Table name
3367 * @param string $prefix Fields prefix
3368 * @return Title[] Array of Title objects linking here
3370 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3371 if ( count( $options ) > 0 ) {
3372 $db = wfGetDB( DB_MASTER
);
3374 $db = wfGetDB( DB_SLAVE
);
3379 self
::getSelectFields(),
3381 "{$prefix}_from=page_id",
3382 "{$prefix}_namespace" => $this->getNamespace(),
3383 "{$prefix}_title" => $this->getDBkey() ],
3389 if ( $res->numRows() ) {
3390 $linkCache = LinkCache
::singleton();
3391 foreach ( $res as $row ) {
3392 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3394 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3395 $retVal[] = $titleObj;
3403 * Get an array of Title objects using this Title as a template
3404 * Also stores the IDs in the link cache.
3406 * WARNING: do not use this function on arbitrary user-supplied titles!
3407 * On heavily-used templates it will max out the memory.
3409 * @param array $options Query option to Database::select()
3410 * @return Title[] Array of Title the Title objects linking here
3412 public function getTemplateLinksTo( $options = [] ) {
3413 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3417 * Get an array of Title objects linked from this Title
3418 * Also stores the IDs in the link cache.
3420 * WARNING: do not use this function on arbitrary user-supplied titles!
3421 * On heavily-used templates it will max out the memory.
3423 * @param array $options Query option to Database::select()
3424 * @param string $table Table name
3425 * @param string $prefix Fields prefix
3426 * @return array Array of Title objects linking here
3428 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3429 $id = $this->getArticleID();
3431 # If the page doesn't exist; there can't be any link from this page
3436 $db = wfGetDB( DB_SLAVE
);
3438 $blNamespace = "{$prefix}_namespace";
3439 $blTitle = "{$prefix}_title";
3444 [ $blNamespace, $blTitle ],
3445 WikiPage
::selectFields()
3447 [ "{$prefix}_from" => $id ],
3452 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3457 $linkCache = LinkCache
::singleton();
3458 foreach ( $res as $row ) {
3459 if ( $row->page_id
) {
3460 $titleObj = Title
::newFromRow( $row );
3462 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3463 $linkCache->addBadLinkObj( $titleObj );
3465 $retVal[] = $titleObj;
3472 * Get an array of Title objects used on this Title as a template
3473 * Also stores the IDs in the link cache.
3475 * WARNING: do not use this function on arbitrary user-supplied titles!
3476 * On heavily-used templates it will max out the memory.
3478 * @param array $options May be FOR UPDATE
3479 * @return Title[] Array of Title the Title objects used here
3481 public function getTemplateLinksFrom( $options = [] ) {
3482 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3486 * Get an array of Title objects referring to non-existent articles linked
3489 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3490 * should use redirect table in this case).
3491 * @return Title[] Array of Title the Title objects
3493 public function getBrokenLinksFrom() {
3494 if ( $this->getArticleID() == 0 ) {
3495 # All links from article ID 0 are false positives
3499 $dbr = wfGetDB( DB_SLAVE
);
3500 $res = $dbr->select(
3501 [ 'page', 'pagelinks' ],
3502 [ 'pl_namespace', 'pl_title' ],
3504 'pl_from' => $this->getArticleID(),
3505 'page_namespace IS NULL'
3511 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3517 foreach ( $res as $row ) {
3518 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3524 * Get a list of URLs to purge from the CDN cache when this
3527 * @return string[] Array of String the URLs
3529 public function getCdnUrls() {
3531 $this->getInternalURL(),
3532 $this->getInternalURL( 'action=history' )
3535 $pageLang = $this->getPageLanguage();
3536 if ( $pageLang->hasVariants() ) {
3537 $variants = $pageLang->getVariants();
3538 foreach ( $variants as $vCode ) {
3539 $urls[] = $this->getInternalURL( $vCode );
3543 // If we are looking at a css/js user subpage, purge the action=raw.
3544 if ( $this->isJsSubpage() ) {
3545 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3546 } elseif ( $this->isCssSubpage() ) {
3547 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3550 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3555 * @deprecated since 1.27 use getCdnUrls()
3557 public function getSquidURLs() {
3558 return $this->getCdnUrls();
3562 * Purge all applicable CDN URLs
3564 public function purgeSquid() {
3565 DeferredUpdates
::addUpdate(
3566 new CdnCacheUpdate( $this->getCdnUrls() ),
3567 DeferredUpdates
::PRESEND
3572 * Move this page without authentication
3574 * @deprecated since 1.25 use MovePage class instead
3575 * @param Title $nt The new page Title
3576 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3578 public function moveNoAuth( &$nt ) {
3579 wfDeprecated( __METHOD__
, '1.25' );
3580 return $this->moveTo( $nt, false );
3584 * Check whether a given move operation would be valid.
3585 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3587 * @deprecated since 1.25, use MovePage's methods instead
3588 * @param Title $nt The new title
3589 * @param bool $auth Whether to check user permissions (uses $wgUser)
3590 * @param string $reason Is the log summary of the move, used for spam checking
3591 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3593 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3596 if ( !( $nt instanceof Title
) ) {
3597 // Normally we'd add this to $errors, but we'll get
3598 // lots of syntax errors if $nt is not an object
3599 return [ [ 'badtitletext' ] ];
3602 $mp = new MovePage( $this, $nt );
3603 $errors = $mp->isValidMove()->getErrorsArray();
3605 $errors = wfMergeErrorArrays(
3607 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3611 return $errors ?
: true;
3615 * Check if the requested move target is a valid file move target
3616 * @todo move this to MovePage
3617 * @param Title $nt Target title
3618 * @return array List of errors
3620 protected function validateFileMoveOperation( $nt ) {
3625 $destFile = wfLocalFile( $nt );
3626 $destFile->load( File
::READ_LATEST
);
3627 if ( !$wgUser->isAllowed( 'reupload-shared' )
3628 && !$destFile->exists() && wfFindFile( $nt )
3630 $errors[] = [ 'file-exists-sharedrepo' ];
3637 * Move a title to a new location
3639 * @deprecated since 1.25, use the MovePage class instead
3640 * @param Title $nt The new title
3641 * @param bool $auth Indicates whether $wgUser's permissions
3643 * @param string $reason The reason for the move
3644 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3645 * Ignored if the user doesn't have the suppressredirect right.
3646 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3648 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3650 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3651 if ( is_array( $err ) ) {
3652 // Auto-block user's IP if the account was "hard" blocked
3653 $wgUser->spreadAnyEditBlock();
3656 // Check suppressredirect permission
3657 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3658 $createRedirect = true;
3661 $mp = new MovePage( $this, $nt );
3662 $status = $mp->move( $wgUser, $reason, $createRedirect );
3663 if ( $status->isOK() ) {
3666 return $status->getErrorsArray();
3671 * Move this page's subpages to be subpages of $nt
3673 * @param Title $nt Move target
3674 * @param bool $auth Whether $wgUser's permissions should be checked
3675 * @param string $reason The reason for the move
3676 * @param bool $createRedirect Whether to create redirects from the old subpages to
3677 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3678 * @return array Array with old page titles as keys, and strings (new page titles) or
3679 * arrays (errors) as values, or an error array with numeric indices if no pages
3682 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3683 global $wgMaximumMovedPages;
3684 // Check permissions
3685 if ( !$this->userCan( 'move-subpages' ) ) {
3686 return [ 'cant-move-subpages' ];
3688 // Do the source and target namespaces support subpages?
3689 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3690 return [ 'namespace-nosubpages',
3691 MWNamespace
::getCanonicalName( $this->getNamespace() ) ];
3693 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3694 return [ 'namespace-nosubpages',
3695 MWNamespace
::getCanonicalName( $nt->getNamespace() ) ];
3698 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3701 foreach ( $subpages as $oldSubpage ) {
3703 if ( $count > $wgMaximumMovedPages ) {
3704 $retval[$oldSubpage->getPrefixedText()] =
3705 [ 'movepage-max-pages',
3706 $wgMaximumMovedPages ];
3710 // We don't know whether this function was called before
3711 // or after moving the root page, so check both
3713 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3714 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3716 // When moving a page to a subpage of itself,
3717 // don't move it twice
3720 $newPageName = preg_replace(
3721 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3722 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3723 $oldSubpage->getDBkey() );
3724 if ( $oldSubpage->isTalkPage() ) {
3725 $newNs = $nt->getTalkPage()->getNamespace();
3727 $newNs = $nt->getSubjectPage()->getNamespace();
3729 # Bug 14385: we need makeTitleSafe because the new page names may
3730 # be longer than 255 characters.
3731 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3733 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3734 if ( $success === true ) {
3735 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3737 $retval[$oldSubpage->getPrefixedText()] = $success;
3744 * Checks if this page is just a one-rev redirect.
3745 * Adds lock, so don't use just for light purposes.
3749 public function isSingleRevRedirect() {
3750 global $wgContentHandlerUseDB;
3752 $dbw = wfGetDB( DB_MASTER
);
3755 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3756 if ( $wgContentHandlerUseDB ) {
3757 $fields[] = 'page_content_model';
3760 $row = $dbw->selectRow( 'page',
3766 # Cache some fields we may want
3767 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3768 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3769 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3770 $this->mContentModel
= $row && isset( $row->page_content_model
)
3771 ?
strval( $row->page_content_model
)
3774 if ( !$this->mRedirect
) {
3777 # Does the article have a history?
3778 $row = $dbw->selectField( [ 'page', 'revision' ],
3780 [ 'page_namespace' => $this->getNamespace(),
3781 'page_title' => $this->getDBkey(),
3783 'page_latest != rev_id'
3788 # Return true if there was no history
3789 return ( $row === false );
3793 * Checks if $this can be moved to a given Title
3794 * - Selects for update, so don't call it unless you mean business
3796 * @deprecated since 1.25, use MovePage's methods instead
3797 * @param Title $nt The new title to check
3800 public function isValidMoveTarget( $nt ) {
3801 # Is it an existing file?
3802 if ( $nt->getNamespace() == NS_FILE
) {
3803 $file = wfLocalFile( $nt );
3804 $file->load( File
::READ_LATEST
);
3805 if ( $file->exists() ) {
3806 wfDebug( __METHOD__
. ": file exists\n" );
3810 # Is it a redirect with no history?
3811 if ( !$nt->isSingleRevRedirect() ) {
3812 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3815 # Get the article text
3816 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3817 if ( !is_object( $rev ) ) {
3820 $content = $rev->getContent();
3821 # Does the redirect point to the source?
3822 # Or is it a broken self-redirect, usually caused by namespace collisions?
3823 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3825 if ( $redirTitle ) {
3826 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3827 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3828 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3834 # Fail safe (not a redirect after all. strange.)
3835 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3836 " is a redirect, but it doesn't contain a valid redirect.\n" );
3842 * Get categories to which this Title belongs and return an array of
3843 * categories' names.
3845 * @return array Array of parents in the form:
3846 * $parent => $currentarticle
3848 public function getParentCategories() {
3853 $titleKey = $this->getArticleID();
3855 if ( $titleKey === 0 ) {
3859 $dbr = wfGetDB( DB_SLAVE
);
3861 $res = $dbr->select(
3864 [ 'cl_from' => $titleKey ],
3868 if ( $res->numRows() > 0 ) {
3869 foreach ( $res as $row ) {
3870 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3871 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3878 * Get a tree of parent categories
3880 * @param array $children Array with the children in the keys, to check for circular refs
3881 * @return array Tree of parent categories
3883 public function getParentCategoryTree( $children = [] ) {
3885 $parents = $this->getParentCategories();
3888 foreach ( $parents as $parent => $current ) {
3889 if ( array_key_exists( $parent, $children ) ) {
3890 # Circular reference
3891 $stack[$parent] = [];
3893 $nt = Title
::newFromText( $parent );
3895 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3905 * Get an associative array for selecting this title from
3908 * @return array Array suitable for the $where parameter of DB::select()
3910 public function pageCond() {
3911 if ( $this->mArticleID
> 0 ) {
3912 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3913 return [ 'page_id' => $this->mArticleID
];
3915 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3920 * Get the revision ID of the previous revision
3922 * @param int $revId Revision ID. Get the revision that was before this one.
3923 * @param int $flags Title::GAID_FOR_UPDATE
3924 * @return int|bool Old revision ID, or false if none exists
3926 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3927 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3928 $revId = $db->selectField( 'revision', 'rev_id',
3930 'rev_page' => $this->getArticleID( $flags ),
3931 'rev_id < ' . intval( $revId )
3934 [ 'ORDER BY' => 'rev_id DESC' ]
3937 if ( $revId === false ) {
3940 return intval( $revId );
3945 * Get the revision ID of the next revision
3947 * @param int $revId Revision ID. Get the revision that was after this one.
3948 * @param int $flags Title::GAID_FOR_UPDATE
3949 * @return int|bool Next revision ID, or false if none exists
3951 public function getNextRevisionID( $revId, $flags = 0 ) {
3952 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3953 $revId = $db->selectField( 'revision', 'rev_id',
3955 'rev_page' => $this->getArticleID( $flags ),
3956 'rev_id > ' . intval( $revId )
3959 [ 'ORDER BY' => 'rev_id' ]
3962 if ( $revId === false ) {
3965 return intval( $revId );
3970 * Get the first revision of the page
3972 * @param int $flags Title::GAID_FOR_UPDATE
3973 * @return Revision|null If page doesn't exist
3975 public function getFirstRevision( $flags = 0 ) {
3976 $pageId = $this->getArticleID( $flags );
3978 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3979 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3980 [ 'rev_page' => $pageId ],
3982 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
3985 return new Revision( $row );
3992 * Get the oldest revision timestamp of this page
3994 * @param int $flags Title::GAID_FOR_UPDATE
3995 * @return string MW timestamp
3997 public function getEarliestRevTime( $flags = 0 ) {
3998 $rev = $this->getFirstRevision( $flags );
3999 return $rev ?
$rev->getTimestamp() : null;
4003 * Check if this is a new page
4007 public function isNewPage() {
4008 $dbr = wfGetDB( DB_SLAVE
);
4009 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4013 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4017 public function isBigDeletion() {
4018 global $wgDeleteRevisionsLimit;
4020 if ( !$wgDeleteRevisionsLimit ) {
4024 if ( $this->mIsBigDeletion
=== null ) {
4025 $dbr = wfGetDB( DB_SLAVE
);
4027 $revCount = $dbr->selectRowCount(
4030 [ 'rev_page' => $this->getArticleID() ],
4032 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4035 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4038 return $this->mIsBigDeletion
;
4042 * Get the approximate revision count of this page.
4046 public function estimateRevisionCount() {
4047 if ( !$this->exists() ) {
4051 if ( $this->mEstimateRevisions
=== null ) {
4052 $dbr = wfGetDB( DB_SLAVE
);
4053 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4054 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4057 return $this->mEstimateRevisions
;
4061 * Get the number of revisions between the given revision.
4062 * Used for diffs and other things that really need it.
4064 * @param int|Revision $old Old revision or rev ID (first before range)
4065 * @param int|Revision $new New revision or rev ID (first after range)
4066 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4067 * @return int Number of revisions between these revisions.
4069 public function countRevisionsBetween( $old, $new, $max = null ) {
4070 if ( !( $old instanceof Revision
) ) {
4071 $old = Revision
::newFromTitle( $this, (int)$old );
4073 if ( !( $new instanceof Revision
) ) {
4074 $new = Revision
::newFromTitle( $this, (int)$new );
4076 if ( !$old ||
!$new ) {
4077 return 0; // nothing to compare
4079 $dbr = wfGetDB( DB_SLAVE
);
4081 'rev_page' => $this->getArticleID(),
4082 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4083 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4085 if ( $max !== null ) {
4086 return $dbr->selectRowCount( 'revision', '1',
4089 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4092 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4097 * Get the authors between the given revisions or revision IDs.
4098 * Used for diffs and other things that really need it.
4102 * @param int|Revision $old Old revision or rev ID (first before range by default)
4103 * @param int|Revision $new New revision or rev ID (first after range by default)
4104 * @param int $limit Maximum number of authors
4105 * @param string|array $options (Optional): Single option, or an array of options:
4106 * 'include_old' Include $old in the range; $new is excluded.
4107 * 'include_new' Include $new in the range; $old is excluded.
4108 * 'include_both' Include both $old and $new in the range.
4109 * Unknown option values are ignored.
4110 * @return array|null Names of revision authors in the range; null if not both revisions exist
4112 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4113 if ( !( $old instanceof Revision
) ) {
4114 $old = Revision
::newFromTitle( $this, (int)$old );
4116 if ( !( $new instanceof Revision
) ) {
4117 $new = Revision
::newFromTitle( $this, (int)$new );
4119 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4120 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4121 // in the sanity check below?
4122 if ( !$old ||
!$new ) {
4123 return null; // nothing to compare
4128 $options = (array)$options;
4129 if ( in_array( 'include_old', $options ) ) {
4132 if ( in_array( 'include_new', $options ) ) {
4135 if ( in_array( 'include_both', $options ) ) {
4139 // No DB query needed if $old and $new are the same or successive revisions:
4140 if ( $old->getId() === $new->getId() ) {
4141 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4143 [ $old->getUserText( Revision
::RAW
) ];
4144 } elseif ( $old->getId() === $new->getParentId() ) {
4145 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4146 $authors[] = $old->getUserText( Revision
::RAW
);
4147 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4148 $authors[] = $new->getUserText( Revision
::RAW
);
4150 } elseif ( $old_cmp === '>=' ) {
4151 $authors[] = $old->getUserText( Revision
::RAW
);
4152 } elseif ( $new_cmp === '<=' ) {
4153 $authors[] = $new->getUserText( Revision
::RAW
);
4157 $dbr = wfGetDB( DB_SLAVE
);
4158 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4160 'rev_page' => $this->getArticleID(),
4161 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4162 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4164 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4166 foreach ( $res as $row ) {
4167 $authors[] = $row->rev_user_text
;
4173 * Get the number of authors between the given revisions or revision IDs.
4174 * Used for diffs and other things that really need it.
4176 * @param int|Revision $old Old revision or rev ID (first before range by default)
4177 * @param int|Revision $new New revision or rev ID (first after range by default)
4178 * @param int $limit Maximum number of authors
4179 * @param string|array $options (Optional): Single option, or an array of options:
4180 * 'include_old' Include $old in the range; $new is excluded.
4181 * 'include_new' Include $new in the range; $old is excluded.
4182 * 'include_both' Include both $old and $new in the range.
4183 * Unknown option values are ignored.
4184 * @return int Number of revision authors in the range; zero if not both revisions exist
4186 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4187 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4188 return $authors ?
count( $authors ) : 0;
4192 * Compare with another title.
4194 * @param Title $title
4197 public function equals( Title
$title ) {
4198 // Note: === is necessary for proper matching of number-like titles.
4199 return $this->getInterwiki() === $title->getInterwiki()
4200 && $this->getNamespace() == $title->getNamespace()
4201 && $this->getDBkey() === $title->getDBkey();
4205 * Check if this title is a subpage of another title
4207 * @param Title $title
4210 public function isSubpageOf( Title
$title ) {
4211 return $this->getInterwiki() === $title->getInterwiki()
4212 && $this->getNamespace() == $title->getNamespace()
4213 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4217 * Check if page exists. For historical reasons, this function simply
4218 * checks for the existence of the title in the page table, and will
4219 * thus return false for interwiki links, special pages and the like.
4220 * If you want to know if a title can be meaningfully viewed, you should
4221 * probably call the isKnown() method instead.
4223 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4224 * from master/for update
4227 public function exists( $flags = 0 ) {
4228 $exists = $this->getArticleID( $flags ) != 0;
4229 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4234 * Should links to this title be shown as potentially viewable (i.e. as
4235 * "bluelinks"), even if there's no record by this title in the page
4238 * This function is semi-deprecated for public use, as well as somewhat
4239 * misleadingly named. You probably just want to call isKnown(), which
4240 * calls this function internally.
4242 * (ISSUE: Most of these checks are cheap, but the file existence check
4243 * can potentially be quite expensive. Including it here fixes a lot of
4244 * existing code, but we might want to add an optional parameter to skip
4245 * it and any other expensive checks.)
4249 public function isAlwaysKnown() {
4253 * Allows overriding default behavior for determining if a page exists.
4254 * If $isKnown is kept as null, regular checks happen. If it's
4255 * a boolean, this value is returned by the isKnown method.
4259 * @param Title $title
4260 * @param bool|null $isKnown
4262 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4264 if ( !is_null( $isKnown ) ) {
4268 if ( $this->isExternal() ) {
4269 return true; // any interwiki link might be viewable, for all we know
4272 switch ( $this->mNamespace
) {
4275 // file exists, possibly in a foreign repo
4276 return (bool)wfFindFile( $this );
4278 // valid special page
4279 return SpecialPageFactory
::exists( $this->getDBkey() );
4281 // selflink, possibly with fragment
4282 return $this->mDbkeyform
== '';
4284 // known system message
4285 return $this->hasSourceText() !== false;
4292 * Does this title refer to a page that can (or might) be meaningfully
4293 * viewed? In particular, this function may be used to determine if
4294 * links to the title should be rendered as "bluelinks" (as opposed to
4295 * "redlinks" to non-existent pages).
4296 * Adding something else to this function will cause inconsistency
4297 * since LinkHolderArray calls isAlwaysKnown() and does its own
4298 * page existence check.
4302 public function isKnown() {
4303 return $this->isAlwaysKnown() ||
$this->exists();
4307 * Does this page have source text?
4311 public function hasSourceText() {
4312 if ( $this->exists() ) {
4316 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4317 // If the page doesn't exist but is a known system message, default
4318 // message content will be displayed, same for language subpages-
4319 // Use always content language to avoid loading hundreds of languages
4320 // to get the link color.
4322 list( $name, ) = MessageCache
::singleton()->figureMessage(
4323 $wgContLang->lcfirst( $this->getText() )
4325 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4326 return $message->exists();
4333 * Get the default message text or false if the message doesn't exist
4335 * @return string|bool
4337 public function getDefaultMessageText() {
4340 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4344 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4345 $wgContLang->lcfirst( $this->getText() )
4347 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4349 if ( $message->exists() ) {
4350 return $message->plain();
4357 * Updates page_touched for this page; called from LinksUpdate.php
4359 * @param string $purgeTime [optional] TS_MW timestamp
4360 * @return bool True if the update succeeded
4362 public function invalidateCache( $purgeTime = null ) {
4363 if ( wfReadOnly() ) {
4367 if ( $this->mArticleID
=== 0 ) {
4368 return true; // avoid gap locking if we know it's not there
4371 $method = __METHOD__
;
4372 $dbw = wfGetDB( DB_MASTER
);
4373 $conds = $this->pageCond();
4374 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4375 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4379 [ 'page_touched' => $dbTimestamp ],
4380 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4389 * Update page_touched timestamps and send CDN purge messages for
4390 * pages linking to this title. May be sent to the job queue depending
4391 * on the number of links. Typically called on create and delete.
4393 public function touchLinks() {
4394 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4395 if ( $this->getNamespace() == NS_CATEGORY
) {
4396 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4401 * Get the last touched timestamp
4403 * @param IDatabase $db Optional db
4404 * @return string Last-touched timestamp
4406 public function getTouched( $db = null ) {
4407 if ( $db === null ) {
4408 $db = wfGetDB( DB_SLAVE
);
4410 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4415 * Get the timestamp when this page was updated since the user last saw it.
4418 * @return string|null
4420 public function getNotificationTimestamp( $user = null ) {
4423 // Assume current user if none given
4427 // Check cache first
4428 $uid = $user->getId();
4432 // avoid isset here, as it'll return false for null entries
4433 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4434 return $this->mNotificationTimestamp
[$uid];
4436 // Don't cache too much!
4437 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4438 $this->mNotificationTimestamp
= [];
4441 $watchedItem = WatchedItemStore
::getDefaultInstance()->getWatchedItem( $user, $this );
4442 if ( $watchedItem ) {
4443 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4445 $this->mNotificationTimestamp
[$uid] = false;
4448 return $this->mNotificationTimestamp
[$uid];
4452 * Generate strings used for xml 'id' names in monobook tabs
4454 * @param string $prepend Defaults to 'nstab-'
4455 * @return string XML 'id' name
4457 public function getNamespaceKey( $prepend = 'nstab-' ) {
4459 // Gets the subject namespace if this title
4460 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4461 // Checks if canonical namespace name exists for namespace
4462 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4463 // Uses canonical namespace name
4464 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4466 // Uses text of namespace
4467 $namespaceKey = $this->getSubjectNsText();
4469 // Makes namespace key lowercase
4470 $namespaceKey = $wgContLang->lc( $namespaceKey );
4472 if ( $namespaceKey == '' ) {
4473 $namespaceKey = 'main';
4475 // Changes file to image for backwards compatibility
4476 if ( $namespaceKey == 'file' ) {
4477 $namespaceKey = 'image';
4479 return $prepend . $namespaceKey;
4483 * Get all extant redirects to this Title
4485 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4486 * @return Title[] Array of Title redirects to this title
4488 public function getRedirectsHere( $ns = null ) {
4491 $dbr = wfGetDB( DB_SLAVE
);
4493 'rd_namespace' => $this->getNamespace(),
4494 'rd_title' => $this->getDBkey(),
4497 if ( $this->isExternal() ) {
4498 $where['rd_interwiki'] = $this->getInterwiki();
4500 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4502 if ( !is_null( $ns ) ) {
4503 $where['page_namespace'] = $ns;
4506 $res = $dbr->select(
4507 [ 'redirect', 'page' ],
4508 [ 'page_namespace', 'page_title' ],
4513 foreach ( $res as $row ) {
4514 $redirs[] = self
::newFromRow( $row );
4520 * Check if this Title is a valid redirect target
4524 public function isValidRedirectTarget() {
4525 global $wgInvalidRedirectTargets;
4527 if ( $this->isSpecialPage() ) {
4528 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4529 if ( $this->isSpecial( 'Userlogout' ) ) {
4533 foreach ( $wgInvalidRedirectTargets as $target ) {
4534 if ( $this->isSpecial( $target ) ) {
4544 * Get a backlink cache object
4546 * @return BacklinkCache
4548 public function getBacklinkCache() {
4549 return BacklinkCache
::get( $this );
4553 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4557 public function canUseNoindex() {
4558 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4560 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4561 ?
$wgContentNamespaces
4562 : $wgExemptFromUserRobotsControl;
4564 return !in_array( $this->mNamespace
, $bannedNamespaces );
4569 * Returns the raw sort key to be used for categories, with the specified
4570 * prefix. This will be fed to Collation::getSortKey() to get a
4571 * binary sortkey that can be used for actual sorting.
4573 * @param string $prefix The prefix to be used, specified using
4574 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4578 public function getCategorySortkey( $prefix = '' ) {
4579 $unprefixed = $this->getText();
4581 // Anything that uses this hook should only depend
4582 // on the Title object passed in, and should probably
4583 // tell the users to run updateCollations.php --force
4584 // in order to re-sort existing category relations.
4585 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4586 if ( $prefix !== '' ) {
4587 # Separate with a line feed, so the unprefixed part is only used as
4588 # a tiebreaker when two pages have the exact same prefix.
4589 # In UCA, tab is the only character that can sort above LF
4590 # so we strip both of them from the original prefix.
4591 $prefix = strtr( $prefix, "\n\t", ' ' );
4592 return "$prefix\n$unprefixed";
4598 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4599 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4600 * the db, it will return NULL.
4602 * @return string|null|bool
4604 private function getDbPageLanguageCode() {
4605 global $wgPageLanguageUseDB;
4607 // check, if the page language could be saved in the database, and if so and
4608 // the value is not requested already, lookup the page language using LinkCache
4609 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4610 $linkCache = LinkCache
::singleton();
4611 $linkCache->addLinkObj( $this );
4612 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4615 return $this->mDbPageLanguage
;
4619 * Get the language in which the content of this page is written in
4620 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4621 * e.g. $wgLang (such as special pages, which are in the user language).
4626 public function getPageLanguage() {
4627 global $wgLang, $wgLanguageCode;
4628 if ( $this->isSpecialPage() ) {
4629 // special pages are in the user language
4633 // Checking if DB language is set
4634 $dbPageLanguage = $this->getDbPageLanguageCode();
4635 if ( $dbPageLanguage ) {
4636 return wfGetLangObj( $dbPageLanguage );
4639 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4640 // Note that this may depend on user settings, so the cache should
4641 // be only per-request.
4642 // NOTE: ContentHandler::getPageLanguage() may need to load the
4643 // content to determine the page language!
4644 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4646 $contentHandler = ContentHandler
::getForTitle( $this );
4647 $langObj = $contentHandler->getPageLanguage( $this );
4648 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4650 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4657 * Get the language in which the content of this page is written when
4658 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4659 * e.g. $wgLang (such as special pages, which are in the user language).
4664 public function getPageViewLanguage() {
4667 if ( $this->isSpecialPage() ) {
4668 // If the user chooses a variant, the content is actually
4669 // in a language whose code is the variant code.
4670 $variant = $wgLang->getPreferredVariant();
4671 if ( $wgLang->getCode() !== $variant ) {
4672 return Language
::factory( $variant );
4678 // Checking if DB language is set
4679 $dbPageLanguage = $this->getDbPageLanguageCode();
4680 if ( $dbPageLanguage ) {
4681 $pageLang = wfGetLangObj( $dbPageLanguage );
4682 $variant = $pageLang->getPreferredVariant();
4683 if ( $pageLang->getCode() !== $variant ) {
4684 $pageLang = Language
::factory( $variant );
4690 // @note Can't be cached persistently, depends on user settings.
4691 // @note ContentHandler::getPageViewLanguage() may need to load the
4692 // content to determine the page language!
4693 $contentHandler = ContentHandler
::getForTitle( $this );
4694 $pageLang = $contentHandler->getPageViewLanguage( $this );
4699 * Get a list of rendered edit notices for this page.
4701 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4702 * they will already be wrapped in paragraphs.
4705 * @param int $oldid Revision ID that's being edited
4708 public function getEditNotices( $oldid = 0 ) {
4711 // Optional notice for the entire namespace
4712 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4713 $msg = wfMessage( $editnotice_ns );
4714 if ( $msg->exists() ) {
4715 $html = $msg->parseAsBlock();
4716 // Edit notices may have complex logic, but output nothing (T91715)
4717 if ( trim( $html ) !== '' ) {
4718 $notices[$editnotice_ns] = Html
::rawElement(
4722 'mw-editnotice-namespace',
4723 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4730 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4731 // Optional notice for page itself and any parent page
4732 $parts = explode( '/', $this->getDBkey() );
4733 $editnotice_base = $editnotice_ns;
4734 while ( count( $parts ) > 0 ) {
4735 $editnotice_base .= '-' . array_shift( $parts );
4736 $msg = wfMessage( $editnotice_base );
4737 if ( $msg->exists() ) {
4738 $html = $msg->parseAsBlock();
4739 if ( trim( $html ) !== '' ) {
4740 $notices[$editnotice_base] = Html
::rawElement(
4744 'mw-editnotice-base',
4745 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4753 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4754 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4755 $msg = wfMessage( $editnoticeText );
4756 if ( $msg->exists() ) {
4757 $html = $msg->parseAsBlock();
4758 if ( trim( $html ) !== '' ) {
4759 $notices[$editnoticeText] = Html
::rawElement(
4763 'mw-editnotice-page',
4764 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4772 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4779 public function __sleep() {
4787 'mDefaultNamespace',
4791 public function __wakeup() {
4792 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4793 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4794 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );