3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
24 use MediaWiki\Linker\LinkTarget
;
25 use MediaWiki\MediaWikiServices
;
28 * Represents a title within MediaWiki.
29 * Optionally may contain an interwiki designation or namespace.
30 * @note This class can fetch various kinds of data from the database;
31 * however, it does so inefficiently.
32 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
33 * and does not rely on global state or the database.
35 class Title
implements LinkTarget
{
36 /** @var HashBagOStuff */
37 static private $titleCache = null;
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 /** @var string Text form (spaces not underscores) of the main part */
60 public $mTextform = '';
62 /** @var string URL-encoded form of the main part */
63 public $mUrlform = '';
65 /** @var string Main part with underscores */
66 public $mDbkeyform = '';
68 /** @var string Database key with the initial letter in the case specified by the user */
69 protected $mUserCaseDBKey;
71 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
72 public $mNamespace = NS_MAIN
;
74 /** @var string Interwiki prefix */
75 public $mInterwiki = '';
77 /** @var bool Was this Title created from a string with a local interwiki prefix? */
78 private $mLocalInterwiki = false;
80 /** @var string Title fragment (i.e. the bit after the #) */
81 public $mFragment = '';
83 /** @var int Article ID, fetched from the link cache on demand */
84 public $mArticleID = -1;
86 /** @var bool|int ID of most recent revision */
87 protected $mLatestID = false;
90 * @var bool|string ID of the page's content model, i.e. one of the
91 * CONTENT_MODEL_XXX constants
93 public $mContentModel = false;
95 /** @var int Estimated number of revisions; null of not loaded */
96 private $mEstimateRevisions;
98 /** @var array Array of groups allowed to edit this article */
99 public $mRestrictions = [];
101 /** @var string|bool */
102 protected $mOldRestrictions = false;
104 /** @var bool Cascade restrictions on this page to included templates and images? */
105 public $mCascadeRestriction;
107 /** Caching the results of getCascadeProtectionSources */
108 public $mCascadingRestrictions;
110 /** @var array When do the restrictions on this page expire? */
111 protected $mRestrictionsExpiry = [];
113 /** @var bool Are cascading restrictions in effect on this page? */
114 protected $mHasCascadingRestrictions;
116 /** @var array Where are the cascading restrictions coming from on this page? */
117 public $mCascadeSources;
119 /** @var bool Boolean for initialisation on demand */
120 public $mRestrictionsLoaded = false;
122 /** @var string Text form including namespace/interwiki, initialised on demand */
123 protected $mPrefixedText = null;
125 /** @var mixed Cached value for getTitleProtection (create protection) */
126 public $mTitleProtection;
129 * @var int Namespace index when there is no namespace. Don't change the
130 * following default, NS_MAIN is hardcoded in several places. See bug 696.
131 * Zero except in {{transclusion}} tags.
133 public $mDefaultNamespace = NS_MAIN
;
135 /** @var int The page length, 0 for special pages */
136 protected $mLength = -1;
138 /** @var null Is the article at this title a redirect? */
139 public $mRedirect = null;
141 /** @var array Associative array of user ID -> timestamp/false */
142 private $mNotificationTimestamp = [];
144 /** @var bool Whether a page has any subpages */
145 private $mHasSubpages;
147 /** @var bool The (string) language code of the page's language and content code. */
148 private $mPageLanguage = false;
150 /** @var string|bool|null The page language code from the database, null if not saved in
151 * the database or false if not loaded, yet. */
152 private $mDbPageLanguage = false;
154 /** @var TitleValue A corresponding TitleValue object */
155 private $mTitleValue = null;
157 /** @var bool Would deleting this page be a big deletion? */
158 private $mIsBigDeletion = null;
162 * B/C kludge: provide a TitleParser for use by Title.
163 * Ideally, Title would have no methods that need this.
164 * Avoid usage of this singleton by using TitleValue
165 * and the associated services when possible.
167 * @return TitleFormatter
169 private static function getTitleFormatter() {
170 return MediaWikiServices
::getInstance()->getTitleFormatter();
176 function __construct() {
180 * Create a new Title from a prefixed DB key
182 * @param string $key The database key, which has underscores
183 * instead of spaces, possibly including namespace and
185 * @return Title|null Title, or null on an error
187 public static function newFromDBkey( $key ) {
189 $t->mDbkeyform
= $key;
192 $t->secureAndSplit();
194 } catch ( MalformedTitleException
$ex ) {
200 * Create a new Title from a TitleValue
202 * @param TitleValue $titleValue Assumed to be safe.
206 public static function newFromTitleValue( TitleValue
$titleValue ) {
207 return self
::newFromLinkTarget( $titleValue );
211 * Create a new Title from a LinkTarget
213 * @param LinkTarget $linkTarget Assumed to be safe.
217 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
218 if ( $linkTarget instanceof Title
) {
219 // Special case if it's already a Title object
222 return self
::makeTitle(
223 $linkTarget->getNamespace(),
224 $linkTarget->getText(),
225 $linkTarget->getFragment(),
226 $linkTarget->getInterwiki()
231 * Create a new Title from text, such as what one would find in a link. De-
232 * codes any HTML entities in the text.
234 * @param string|int|null $text The link text; spaces, prefixes, and an
235 * initial ':' indicating the main namespace are accepted.
236 * @param int $defaultNamespace The namespace to use if none is specified
237 * by a prefix. If you want to force a specific namespace even if
238 * $text might begin with a namespace prefix, use makeTitle() or
240 * @throws InvalidArgumentException
241 * @return Title|null Title or null on an error.
243 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
244 // DWIM: Integers can be passed in here when page titles are used as array keys.
245 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
246 throw new InvalidArgumentException( '$text must be a string.' );
248 if ( $text === null ) {
253 return Title
::newFromTextThrow( strval( $text ), $defaultNamespace );
254 } catch ( MalformedTitleException
$ex ) {
260 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
261 * rather than returning null.
263 * The exception subclasses encode detailed information about why the title is invalid.
265 * @see Title::newFromText
268 * @param string $text Title text to check
269 * @param int $defaultNamespace
270 * @throws MalformedTitleException If the title is invalid
273 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
274 if ( is_object( $text ) ) {
275 throw new MWException( '$text must be a string, given an object' );
278 $titleCache = self
::getTitleCache();
280 // Wiki pages often contain multiple links to the same page.
281 // Title normalization and parsing can become expensive on pages with many
282 // links, so we can save a little time by caching them.
283 // In theory these are value objects and won't get changed...
284 if ( $defaultNamespace == NS_MAIN
) {
285 $t = $titleCache->get( $text );
291 // Convert things like é ā or 〗 into normalized (bug 14952) text
292 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
295 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
296 $t->mDefaultNamespace
= intval( $defaultNamespace );
298 $t->secureAndSplit();
299 if ( $defaultNamespace == NS_MAIN
) {
300 $titleCache->set( $text, $t );
306 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
308 * Example of wrong and broken code:
309 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
311 * Example of right code:
312 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
314 * Create a new Title from URL-encoded text. Ensures that
315 * the given title's length does not exceed the maximum.
317 * @param string $url The title, as might be taken from a URL
318 * @return Title|null The new object, or null on an error
320 public static function newFromURL( $url ) {
323 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
324 # but some URLs used it as a space replacement and they still come
325 # from some external search tools.
326 if ( strpos( self
::legalChars(), '+' ) === false ) {
327 $url = strtr( $url, '+', ' ' );
330 $t->mDbkeyform
= strtr( $url, ' ', '_' );
333 $t->secureAndSplit();
335 } catch ( MalformedTitleException
$ex ) {
341 * @return HashBagOStuff
343 private static function getTitleCache() {
344 if ( self
::$titleCache == null ) {
345 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
347 return self
::$titleCache;
351 * Returns a list of fields that are to be selected for initializing Title
352 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
353 * whether to include page_content_model.
357 protected static function getSelectFields() {
358 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
361 'page_namespace', 'page_title', 'page_id',
362 'page_len', 'page_is_redirect', 'page_latest',
365 if ( $wgContentHandlerUseDB ) {
366 $fields[] = 'page_content_model';
369 if ( $wgPageLanguageUseDB ) {
370 $fields[] = 'page_lang';
377 * Create a new Title from an article ID
379 * @param int $id The page_id corresponding to the Title to create
380 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
381 * @return Title|null The new object, or null on an error
383 public static function newFromID( $id, $flags = 0 ) {
384 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
385 $row = $db->selectRow(
387 self
::getSelectFields(),
388 [ 'page_id' => $id ],
391 if ( $row !== false ) {
392 $title = Title
::newFromRow( $row );
400 * Make an array of titles from an array of IDs
402 * @param int[] $ids Array of IDs
403 * @return Title[] Array of Titles
405 public static function newFromIDs( $ids ) {
406 if ( !count( $ids ) ) {
409 $dbr = wfGetDB( DB_SLAVE
);
413 self
::getSelectFields(),
414 [ 'page_id' => $ids ],
419 foreach ( $res as $row ) {
420 $titles[] = Title
::newFromRow( $row );
426 * Make a Title object from a DB row
428 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
429 * @return Title Corresponding Title
431 public static function newFromRow( $row ) {
432 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
433 $t->loadFromRow( $row );
438 * Load Title object fields from a DB row.
439 * If false is given, the title will be treated as non-existing.
441 * @param stdClass|bool $row Database row
443 public function loadFromRow( $row ) {
444 if ( $row ) { // page found
445 if ( isset( $row->page_id
) ) {
446 $this->mArticleID
= (int)$row->page_id
;
448 if ( isset( $row->page_len
) ) {
449 $this->mLength
= (int)$row->page_len
;
451 if ( isset( $row->page_is_redirect
) ) {
452 $this->mRedirect
= (bool)$row->page_is_redirect
;
454 if ( isset( $row->page_latest
) ) {
455 $this->mLatestID
= (int)$row->page_latest
;
457 if ( isset( $row->page_content_model
) ) {
458 $this->mContentModel
= strval( $row->page_content_model
);
460 $this->mContentModel
= false; # initialized lazily in getContentModel()
462 if ( isset( $row->page_lang
) ) {
463 $this->mDbPageLanguage
= (string)$row->page_lang
;
465 if ( isset( $row->page_restrictions
) ) {
466 $this->mOldRestrictions
= $row->page_restrictions
;
468 } else { // page not found
469 $this->mArticleID
= 0;
471 $this->mRedirect
= false;
472 $this->mLatestID
= 0;
473 $this->mContentModel
= false; # initialized lazily in getContentModel()
478 * Create a new Title from a namespace index and a DB key.
479 * It's assumed that $ns and $title are *valid*, for instance when
480 * they came directly from the database or a special page name.
481 * For convenience, spaces are converted to underscores so that
482 * eg user_text fields can be used directly.
484 * @param int $ns The namespace of the article
485 * @param string $title The unprefixed database key form
486 * @param string $fragment The link fragment (after the "#")
487 * @param string $interwiki The interwiki prefix
488 * @return Title The new object
490 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
492 $t->mInterwiki
= $interwiki;
493 $t->mFragment
= $fragment;
494 $t->mNamespace
= $ns = intval( $ns );
495 $t->mDbkeyform
= strtr( $title, ' ', '_' );
496 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
497 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
498 $t->mTextform
= strtr( $title, '_', ' ' );
499 $t->mContentModel
= false; # initialized lazily in getContentModel()
504 * Create a new Title from a namespace index and a DB key.
505 * The parameters will be checked for validity, which is a bit slower
506 * than makeTitle() but safer for user-provided data.
508 * @param int $ns The namespace of the article
509 * @param string $title Database key form
510 * @param string $fragment The link fragment (after the "#")
511 * @param string $interwiki Interwiki prefix
512 * @return Title|null The new object, or null on an error
514 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
515 if ( !MWNamespace
::exists( $ns ) ) {
520 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
523 $t->secureAndSplit();
525 } catch ( MalformedTitleException
$ex ) {
531 * Create a new Title for the Main Page
533 * @return Title The new object
535 public static function newMainPage() {
536 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
537 // Don't give fatal errors if the message is broken
539 $title = Title
::newFromText( 'Main Page' );
545 * Get the prefixed DB key associated with an ID
547 * @param int $id The page_id of the article
548 * @return Title|null An object representing the article, or null if no such article was found
550 public static function nameOf( $id ) {
551 $dbr = wfGetDB( DB_SLAVE
);
553 $s = $dbr->selectRow(
555 [ 'page_namespace', 'page_title' ],
556 [ 'page_id' => $id ],
559 if ( $s === false ) {
563 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
568 * Get a regex character class describing the legal characters in a link
570 * @return string The list of characters, not delimited
572 public static function legalChars() {
573 global $wgLegalTitleChars;
574 return $wgLegalTitleChars;
578 * Returns a simple regex that will match on characters and sequences invalid in titles.
579 * Note that this doesn't pick up many things that could be wrong with titles, but that
580 * replacing this regex with something valid will make many titles valid.
582 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
584 * @return string Regex string
586 static function getTitleInvalidRegex() {
587 wfDeprecated( __METHOD__
, '1.25' );
588 return MediaWikiTitleCodec
::getTitleInvalidRegex();
592 * Utility method for converting a character sequence from bytes to Unicode.
594 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
595 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
597 * @param string $byteClass
600 public static function convertByteClassToUnicodeClass( $byteClass ) {
601 $length = strlen( $byteClass );
603 $x0 = $x1 = $x2 = '';
605 $d0 = $d1 = $d2 = '';
606 // Decoded integer codepoints
607 $ord0 = $ord1 = $ord2 = 0;
609 $r0 = $r1 = $r2 = '';
613 $allowUnicode = false;
614 for ( $pos = 0; $pos < $length; $pos++
) {
615 // Shift the queues down
624 // Load the current input token and decoded values
625 $inChar = $byteClass[$pos];
626 if ( $inChar == '\\' ) {
627 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
628 $x0 = $inChar . $m[0];
629 $d0 = chr( hexdec( $m[1] ) );
630 $pos +
= strlen( $m[0] );
631 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
632 $x0 = $inChar . $m[0];
633 $d0 = chr( octdec( $m[0] ) );
634 $pos +
= strlen( $m[0] );
635 } elseif ( $pos +
1 >= $length ) {
638 $d0 = $byteClass[$pos +
1];
646 // Load the current re-encoded value
647 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
648 $r0 = sprintf( '\x%02x', $ord0 );
649 } elseif ( $ord0 >= 0x80 ) {
650 // Allow unicode if a single high-bit character appears
651 $r0 = sprintf( '\x%02x', $ord0 );
652 $allowUnicode = true;
653 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
659 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
661 if ( $ord2 > $ord0 ) {
663 } elseif ( $ord0 >= 0x80 ) {
665 $allowUnicode = true;
666 if ( $ord2 < 0x80 ) {
667 // Keep the non-unicode section of the range
674 // Reset state to the initial value
675 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
676 } elseif ( $ord2 < 0x80 ) {
681 if ( $ord1 < 0x80 ) {
684 if ( $ord0 < 0x80 ) {
687 if ( $allowUnicode ) {
688 $out .= '\u0080-\uFFFF';
694 * Make a prefixed DB key from a DB key and a namespace index
696 * @param int $ns Numerical representation of the namespace
697 * @param string $title The DB key form the title
698 * @param string $fragment The link fragment (after the "#")
699 * @param string $interwiki The interwiki prefix
700 * @param bool $canonicalNamespace If true, use the canonical name for
701 * $ns instead of the localized version.
702 * @return string The prefixed form of the title
704 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
705 $canonicalNamespace = false
709 if ( $canonicalNamespace ) {
710 $namespace = MWNamespace
::getCanonicalName( $ns );
712 $namespace = $wgContLang->getNsText( $ns );
714 $name = $namespace == '' ?
$title : "$namespace:$title";
715 if ( strval( $interwiki ) != '' ) {
716 $name = "$interwiki:$name";
718 if ( strval( $fragment ) != '' ) {
719 $name .= '#' . $fragment;
725 * Escape a text fragment, say from a link, for a URL
727 * @param string $fragment Containing a URL or link fragment (after the "#")
728 * @return string Escaped string
730 static function escapeFragmentForURL( $fragment ) {
731 # Note that we don't urlencode the fragment. urlencoded Unicode
732 # fragments appear not to work in IE (at least up to 7) or in at least
733 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
734 # to care if they aren't encoded.
735 return Sanitizer
::escapeId( $fragment, 'noninitial' );
739 * Callback for usort() to do title sorts by (namespace, title)
744 * @return int Result of string comparison, or namespace comparison
746 public static function compare( $a, $b ) {
747 if ( $a->getNamespace() == $b->getNamespace() ) {
748 return strcmp( $a->getText(), $b->getText() );
750 return $a->getNamespace() - $b->getNamespace();
755 * Determine whether the object refers to a page within
756 * this project (either this wiki or a wiki with a local
757 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
759 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
761 public function isLocal() {
762 if ( $this->isExternal() ) {
763 $iw = Interwiki
::fetch( $this->mInterwiki
);
765 return $iw->isLocal();
772 * Is this Title interwiki?
776 public function isExternal() {
777 return $this->mInterwiki
!== '';
781 * Get the interwiki prefix
783 * Use Title::isExternal to check if a interwiki is set
785 * @return string Interwiki prefix
787 public function getInterwiki() {
788 return $this->mInterwiki
;
792 * Was this a local interwiki link?
796 public function wasLocalInterwiki() {
797 return $this->mLocalInterwiki
;
801 * Determine whether the object refers to a page within
802 * this project and is transcludable.
804 * @return bool True if this is transcludable
806 public function isTrans() {
807 if ( !$this->isExternal() ) {
811 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
815 * Returns the DB name of the distant wiki which owns the object.
817 * @return string The DB name
819 public function getTransWikiID() {
820 if ( !$this->isExternal() ) {
824 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
828 * Get a TitleValue object representing this Title.
830 * @note Not all valid Titles have a corresponding valid TitleValue
831 * (e.g. TitleValues cannot represent page-local links that have a
832 * fragment but no title text).
834 * @return TitleValue|null
836 public function getTitleValue() {
837 if ( $this->mTitleValue
=== null ) {
839 $this->mTitleValue
= new TitleValue(
840 $this->getNamespace(),
842 $this->getFragment(),
843 $this->getInterwiki()
845 } catch ( InvalidArgumentException
$ex ) {
846 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
847 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
851 return $this->mTitleValue
;
855 * Get the text form (spaces not underscores) of the main part
857 * @return string Main part of the title
859 public function getText() {
860 return $this->mTextform
;
864 * Get the URL-encoded form of the main part
866 * @return string Main part of the title, URL-encoded
868 public function getPartialURL() {
869 return $this->mUrlform
;
873 * Get the main part with underscores
875 * @return string Main part of the title, with underscores
877 public function getDBkey() {
878 return $this->mDbkeyform
;
882 * Get the DB key with the initial letter case as specified by the user
884 * @return string DB key
886 function getUserCaseDBKey() {
887 if ( !is_null( $this->mUserCaseDBKey
) ) {
888 return $this->mUserCaseDBKey
;
890 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
891 return $this->mDbkeyform
;
896 * Get the namespace index, i.e. one of the NS_xxxx constants.
898 * @return int Namespace index
900 public function getNamespace() {
901 return $this->mNamespace
;
905 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
907 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
908 * @return string Content model id
910 public function getContentModel( $flags = 0 ) {
911 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
912 $linkCache = LinkCache
::singleton();
913 $linkCache->addLinkObj( $this ); # in case we already had an article ID
914 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
917 if ( !$this->mContentModel
) {
918 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
921 return $this->mContentModel
;
925 * Convenience method for checking a title's content model name
927 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
928 * @return bool True if $this->getContentModel() == $id
930 public function hasContentModel( $id ) {
931 return $this->getContentModel() == $id;
935 * Get the namespace text
937 * @return string Namespace text
939 public function getNsText() {
940 if ( $this->isExternal() ) {
941 // This probably shouldn't even happen,
942 // but for interwiki transclusion it sometimes does.
943 // Use the canonical namespaces if possible to try to
944 // resolve a foreign namespace.
945 if ( MWNamespace
::exists( $this->mNamespace
) ) {
946 return MWNamespace
::getCanonicalName( $this->mNamespace
);
951 $formatter = self
::getTitleFormatter();
952 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
953 } catch ( InvalidArgumentException
$ex ) {
954 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
960 * Get the namespace text of the subject (rather than talk) page
962 * @return string Namespace text
964 public function getSubjectNsText() {
966 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
970 * Get the namespace text of the talk page
972 * @return string Namespace text
974 public function getTalkNsText() {
976 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
980 * Could this title have a corresponding talk page?
984 public function canTalk() {
985 return MWNamespace
::canTalk( $this->mNamespace
);
989 * Is this in a namespace that allows actual pages?
993 public function canExist() {
994 return $this->mNamespace
>= NS_MAIN
;
998 * Can this title be added to a user's watchlist?
1002 public function isWatchable() {
1003 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1007 * Returns true if this is a special page.
1011 public function isSpecialPage() {
1012 return $this->getNamespace() == NS_SPECIAL
;
1016 * Returns true if this title resolves to the named special page
1018 * @param string $name The special page name
1021 public function isSpecial( $name ) {
1022 if ( $this->isSpecialPage() ) {
1023 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1024 if ( $name == $thisName ) {
1032 * If the Title refers to a special page alias which is not the local default, resolve
1033 * the alias, and localise the name as necessary. Otherwise, return $this
1037 public function fixSpecialName() {
1038 if ( $this->isSpecialPage() ) {
1039 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1040 if ( $canonicalName ) {
1041 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1042 if ( $localName != $this->mDbkeyform
) {
1043 return Title
::makeTitle( NS_SPECIAL
, $localName );
1051 * Returns true if the title is inside the specified namespace.
1053 * Please make use of this instead of comparing to getNamespace()
1054 * This function is much more resistant to changes we may make
1055 * to namespaces than code that makes direct comparisons.
1056 * @param int $ns The namespace
1060 public function inNamespace( $ns ) {
1061 return MWNamespace
::equals( $this->getNamespace(), $ns );
1065 * Returns true if the title is inside one of the specified namespaces.
1067 * @param int $namespaces,... The namespaces to check for
1071 public function inNamespaces( /* ... */ ) {
1072 $namespaces = func_get_args();
1073 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1074 $namespaces = $namespaces[0];
1077 foreach ( $namespaces as $ns ) {
1078 if ( $this->inNamespace( $ns ) ) {
1087 * Returns true if the title has the same subject namespace as the
1088 * namespace specified.
1089 * For example this method will take NS_USER and return true if namespace
1090 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1091 * as their subject namespace.
1093 * This is MUCH simpler than individually testing for equivalence
1094 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1099 public function hasSubjectNamespace( $ns ) {
1100 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1104 * Is this Title in a namespace which contains content?
1105 * In other words, is this a content page, for the purposes of calculating
1110 public function isContentPage() {
1111 return MWNamespace
::isContent( $this->getNamespace() );
1115 * Would anybody with sufficient privileges be able to move this page?
1116 * Some pages just aren't movable.
1120 public function isMovable() {
1121 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1122 // Interwiki title or immovable namespace. Hooks don't get to override here
1127 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1132 * Is this the mainpage?
1133 * @note Title::newFromText seems to be sufficiently optimized by the title
1134 * cache that we don't need to over-optimize by doing direct comparisons and
1135 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1136 * ends up reporting something differently than $title->isMainPage();
1141 public function isMainPage() {
1142 return $this->equals( Title
::newMainPage() );
1146 * Is this a subpage?
1150 public function isSubpage() {
1151 return MWNamespace
::hasSubpages( $this->mNamespace
)
1152 ?
strpos( $this->getText(), '/' ) !== false
1157 * Is this a conversion table for the LanguageConverter?
1161 public function isConversionTable() {
1162 // @todo ConversionTable should become a separate content model.
1164 return $this->getNamespace() == NS_MEDIAWIKI
&&
1165 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1169 * Does that page contain wikitext, or it is JS, CSS or whatever?
1173 public function isWikitextPage() {
1174 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1178 * Could this page contain custom CSS or JavaScript for the global UI.
1179 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1180 * or CONTENT_MODEL_JAVASCRIPT.
1182 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1185 * Note that this method should not return true for pages that contain and
1186 * show "inactive" CSS or JS.
1189 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1191 public function isCssOrJsPage() {
1192 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1193 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1194 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1196 # @note This hook is also called in ContentHandler::getDefaultModel.
1197 # It's called here again to make sure hook functions can force this
1198 # method to return true even outside the MediaWiki namespace.
1200 Hooks
::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1202 return $isCssOrJsPage;
1206 * Is this a .css or .js subpage of a user page?
1208 * @todo FIXME: Rename to isUserConfigPage()
1210 public function isCssJsSubpage() {
1211 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1212 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1213 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1217 * Trim down a .css or .js subpage title to get the corresponding skin name
1219 * @return string Containing skin name from .css or .js subpage title
1221 public function getSkinFromCssJsSubpage() {
1222 $subpage = explode( '/', $this->mTextform
);
1223 $subpage = $subpage[count( $subpage ) - 1];
1224 $lastdot = strrpos( $subpage, '.' );
1225 if ( $lastdot === false ) {
1226 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1228 return substr( $subpage, 0, $lastdot );
1232 * Is this a .css subpage of a user page?
1236 public function isCssSubpage() {
1237 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1238 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1242 * Is this a .js subpage of a user page?
1246 public function isJsSubpage() {
1247 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1248 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1252 * Is this a talk page of some sort?
1256 public function isTalkPage() {
1257 return MWNamespace
::isTalk( $this->getNamespace() );
1261 * Get a Title object associated with the talk page of this article
1263 * @return Title The object for the talk page
1265 public function getTalkPage() {
1266 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1270 * Get a title object associated with the subject page of this
1273 * @return Title The object for the subject page
1275 public function getSubjectPage() {
1276 // Is this the same title?
1277 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1278 if ( $this->getNamespace() == $subjectNS ) {
1281 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1285 * Get the other title for this page, if this is a subject page
1286 * get the talk page, if it is a subject page get the talk page
1289 * @throws MWException
1292 public function getOtherPage() {
1293 if ( $this->isSpecialPage() ) {
1294 throw new MWException( 'Special pages cannot have other pages' );
1296 if ( $this->isTalkPage() ) {
1297 return $this->getSubjectPage();
1299 return $this->getTalkPage();
1304 * Get the default namespace index, for when there is no namespace
1306 * @return int Default namespace index
1308 public function getDefaultNamespace() {
1309 return $this->mDefaultNamespace
;
1313 * Get the Title fragment (i.e.\ the bit after the #) in text form
1315 * Use Title::hasFragment to check for a fragment
1317 * @return string Title fragment
1319 public function getFragment() {
1320 return $this->mFragment
;
1324 * Check if a Title fragment is set
1329 public function hasFragment() {
1330 return $this->mFragment
!== '';
1334 * Get the fragment in URL form, including the "#" character if there is one
1335 * @return string Fragment in URL form
1337 public function getFragmentForURL() {
1338 if ( !$this->hasFragment() ) {
1341 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1346 * Set the fragment for this title. Removes the first character from the
1347 * specified fragment before setting, so it assumes you're passing it with
1350 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1351 * or Title::createFragmentTarget().
1352 * Still in active use privately.
1355 * @param string $fragment Text
1357 public function setFragment( $fragment ) {
1358 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1362 * Creates a new Title for a different fragment of the same page.
1365 * @param string $fragment
1368 public function createFragmentTarget( $fragment ) {
1369 return self
::makeTitle(
1370 $this->getNamespace(),
1373 $this->getInterwiki()
1379 * Prefix some arbitrary text with the namespace or interwiki prefix
1382 * @param string $name The text
1383 * @return string The prefixed text
1385 private function prefix( $name ) {
1387 if ( $this->isExternal() ) {
1388 $p = $this->mInterwiki
. ':';
1391 if ( 0 != $this->mNamespace
) {
1392 $p .= $this->getNsText() . ':';
1398 * Get the prefixed database key form
1400 * @return string The prefixed title, with underscores and
1401 * any interwiki and namespace prefixes
1403 public function getPrefixedDBkey() {
1404 $s = $this->prefix( $this->mDbkeyform
);
1405 $s = strtr( $s, ' ', '_' );
1410 * Get the prefixed title with spaces.
1411 * This is the form usually used for display
1413 * @return string The prefixed title, with spaces
1415 public function getPrefixedText() {
1416 if ( $this->mPrefixedText
=== null ) {
1417 $s = $this->prefix( $this->mTextform
);
1418 $s = strtr( $s, '_', ' ' );
1419 $this->mPrefixedText
= $s;
1421 return $this->mPrefixedText
;
1425 * Return a string representation of this title
1427 * @return string Representation of this title
1429 public function __toString() {
1430 return $this->getPrefixedText();
1434 * Get the prefixed title with spaces, plus any fragment
1435 * (part beginning with '#')
1437 * @return string The prefixed title, with spaces and the fragment, including '#'
1439 public function getFullText() {
1440 $text = $this->getPrefixedText();
1441 if ( $this->hasFragment() ) {
1442 $text .= '#' . $this->getFragment();
1448 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1452 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1456 * @return string Root name
1459 public function getRootText() {
1460 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1461 return $this->getText();
1464 return strtok( $this->getText(), '/' );
1468 * Get the root page name title, i.e. the leftmost part before any slashes
1472 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1473 * # returns: Title{User:Foo}
1476 * @return Title Root title
1479 public function getRootTitle() {
1480 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1484 * Get the base page name without a namespace, i.e. the part before the subpage name
1488 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1489 * # returns: 'Foo/Bar'
1492 * @return string Base name
1494 public function getBaseText() {
1495 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1496 return $this->getText();
1499 $parts = explode( '/', $this->getText() );
1500 # Don't discard the real title if there's no subpage involved
1501 if ( count( $parts ) > 1 ) {
1502 unset( $parts[count( $parts ) - 1] );
1504 return implode( '/', $parts );
1508 * Get the base page name title, i.e. the part before the subpage name
1512 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1513 * # returns: Title{User:Foo/Bar}
1516 * @return Title Base title
1519 public function getBaseTitle() {
1520 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1524 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1528 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1532 * @return string Subpage name
1534 public function getSubpageText() {
1535 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1536 return $this->mTextform
;
1538 $parts = explode( '/', $this->mTextform
);
1539 return $parts[count( $parts ) - 1];
1543 * Get the title for a subpage of the current page
1547 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1548 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1551 * @param string $text The subpage name to add to the title
1552 * @return Title Subpage title
1555 public function getSubpage( $text ) {
1556 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1560 * Get a URL-encoded form of the subpage text
1562 * @return string URL-encoded subpage name
1564 public function getSubpageUrlForm() {
1565 $text = $this->getSubpageText();
1566 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1571 * Get a URL-encoded title (not an actual URL) including interwiki
1573 * @return string The URL-encoded form
1575 public function getPrefixedURL() {
1576 $s = $this->prefix( $this->mDbkeyform
);
1577 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1582 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1583 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1584 * second argument named variant. This was deprecated in favor
1585 * of passing an array of option with a "variant" key
1586 * Once $query2 is removed for good, this helper can be dropped
1587 * and the wfArrayToCgi moved to getLocalURL();
1589 * @since 1.19 (r105919)
1590 * @param array|string $query
1591 * @param bool $query2
1594 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1595 if ( $query2 !== false ) {
1596 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1597 "method called with a second parameter is deprecated. Add your " .
1598 "parameter to an array passed as the first parameter.", "1.19" );
1600 if ( is_array( $query ) ) {
1601 $query = wfArrayToCgi( $query );
1604 if ( is_string( $query2 ) ) {
1605 // $query2 is a string, we will consider this to be
1606 // a deprecated $variant argument and add it to the query
1607 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1609 $query2 = wfArrayToCgi( $query2 );
1611 // If we have $query content add a & to it first
1615 // Now append the queries together
1622 * Get a real URL referring to this title, with interwiki link and
1625 * @see self::getLocalURL for the arguments.
1627 * @param array|string $query
1628 * @param bool $query2
1629 * @param string $proto Protocol type to use in URL
1630 * @return string The URL
1632 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1633 $query = self
::fixUrlQueryArgs( $query, $query2 );
1635 # Hand off all the decisions on urls to getLocalURL
1636 $url = $this->getLocalURL( $query );
1638 # Expand the url to make it a full url. Note that getLocalURL has the
1639 # potential to output full urls for a variety of reasons, so we use
1640 # wfExpandUrl instead of simply prepending $wgServer
1641 $url = wfExpandUrl( $url, $proto );
1643 # Finally, add the fragment.
1644 $url .= $this->getFragmentForURL();
1646 Hooks
::run( 'GetFullURL', [ &$this, &$url, $query ] );
1651 * Get a URL with no fragment or server name (relative URL) from a Title object.
1652 * If this page is generated with action=render, however,
1653 * $wgServer is prepended to make an absolute URL.
1655 * @see self::getFullURL to always get an absolute URL.
1656 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1657 * valid to link, locally, to the current Title.
1658 * @see self::newFromText to produce a Title object.
1660 * @param string|array $query An optional query string,
1661 * not used for interwiki links. Can be specified as an associative array as well,
1662 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1663 * Some query patterns will trigger various shorturl path replacements.
1664 * @param array $query2 An optional secondary query array. This one MUST
1665 * be an array. If a string is passed it will be interpreted as a deprecated
1666 * variant argument and urlencoded into a variant= argument.
1667 * This second query argument will be added to the $query
1668 * The second parameter is deprecated since 1.19. Pass it as a key,value
1669 * pair in the first parameter array instead.
1671 * @return string String of the URL.
1673 public function getLocalURL( $query = '', $query2 = false ) {
1674 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1676 $query = self
::fixUrlQueryArgs( $query, $query2 );
1678 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1680 $namespace = $this->getNsText();
1681 if ( $namespace != '' ) {
1682 # Can this actually happen? Interwikis shouldn't be parsed.
1683 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1686 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1687 $url = wfAppendQuery( $url, $query );
1689 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1690 if ( $query == '' ) {
1691 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1692 Hooks
::run( 'GetLocalURL::Article', [ &$this, &$url ] );
1694 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1698 if ( !empty( $wgActionPaths )
1699 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1701 $action = urldecode( $matches[2] );
1702 if ( isset( $wgActionPaths[$action] ) ) {
1703 $query = $matches[1];
1704 if ( isset( $matches[4] ) ) {
1705 $query .= $matches[4];
1707 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1708 if ( $query != '' ) {
1709 $url = wfAppendQuery( $url, $query );
1715 && $wgVariantArticlePath
1716 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1717 && $this->getPageLanguage()->hasVariants()
1718 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1720 $variant = urldecode( $matches[1] );
1721 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1722 // Only do the variant replacement if the given variant is a valid
1723 // variant for the page's language.
1724 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1725 $url = str_replace( '$1', $dbkey, $url );
1729 if ( $url === false ) {
1730 if ( $query == '-' ) {
1733 $url = "{$wgScript}?title={$dbkey}&{$query}";
1737 Hooks
::run( 'GetLocalURL::Internal', [ &$this, &$url, $query ] );
1739 // @todo FIXME: This causes breakage in various places when we
1740 // actually expected a local URL and end up with dupe prefixes.
1741 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1742 $url = $wgServer . $url;
1745 Hooks
::run( 'GetLocalURL', [ &$this, &$url, $query ] );
1750 * Get a URL that's the simplest URL that will be valid to link, locally,
1751 * to the current Title. It includes the fragment, but does not include
1752 * the server unless action=render is used (or the link is external). If
1753 * there's a fragment but the prefixed text is empty, we just return a link
1756 * The result obviously should not be URL-escaped, but does need to be
1757 * HTML-escaped if it's being output in HTML.
1759 * @param array $query
1760 * @param bool $query2
1761 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1762 * @see self::getLocalURL for the arguments.
1763 * @return string The URL
1765 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1766 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1767 $ret = $this->getFullURL( $query, $query2, $proto );
1768 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1769 $ret = $this->getFragmentForURL();
1771 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1777 * Get the URL form for an internal link.
1778 * - Used in various CDN-related code, in case we have a different
1779 * internal hostname for the server from the exposed one.
1781 * This uses $wgInternalServer to qualify the path, or $wgServer
1782 * if $wgInternalServer is not set. If the server variable used is
1783 * protocol-relative, the URL will be expanded to http://
1785 * @see self::getLocalURL for the arguments.
1786 * @return string The URL
1788 public function getInternalURL( $query = '', $query2 = false ) {
1789 global $wgInternalServer, $wgServer;
1790 $query = self
::fixUrlQueryArgs( $query, $query2 );
1791 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1792 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1793 Hooks
::run( 'GetInternalURL', [ &$this, &$url, $query ] );
1798 * Get the URL for a canonical link, for use in things like IRC and
1799 * e-mail notifications. Uses $wgCanonicalServer and the
1800 * GetCanonicalURL hook.
1802 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1804 * @see self::getLocalURL for the arguments.
1805 * @return string The URL
1808 public function getCanonicalURL( $query = '', $query2 = false ) {
1809 $query = self
::fixUrlQueryArgs( $query, $query2 );
1810 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1811 Hooks
::run( 'GetCanonicalURL', [ &$this, &$url, $query ] );
1816 * Get the edit URL for this Title
1818 * @return string The URL, or a null string if this is an interwiki link
1820 public function getEditURL() {
1821 if ( $this->isExternal() ) {
1824 $s = $this->getLocalURL( 'action=edit' );
1830 * Can $user perform $action on this page?
1831 * This skips potentially expensive cascading permission checks
1832 * as well as avoids expensive error formatting
1834 * Suitable for use for nonessential UI controls in common cases, but
1835 * _not_ for functional access control.
1837 * May provide false positives, but should never provide a false negative.
1839 * @param string $action Action that permission needs to be checked for
1840 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1843 public function quickUserCan( $action, $user = null ) {
1844 return $this->userCan( $action, $user, false );
1848 * Can $user perform $action on this page?
1850 * @param string $action Action that permission needs to be checked for
1851 * @param User $user User to check (since 1.19); $wgUser will be used if not
1853 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1856 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1857 if ( !$user instanceof User
) {
1862 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1866 * Can $user perform $action on this page?
1868 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1870 * @param string $action Action that permission needs to be checked for
1871 * @param User $user User to check
1872 * @param string $rigor One of (quick,full,secure)
1873 * - quick : does cheap permission checks from slaves (usable for GUI creation)
1874 * - full : does cheap and expensive checks possibly from a slave
1875 * - secure : does cheap and expensive checks, using the master as needed
1876 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1877 * whose corresponding errors may be ignored.
1878 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1880 public function getUserPermissionsErrors(
1881 $action, $user, $rigor = 'secure', $ignoreErrors = []
1883 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1885 // Remove the errors being ignored.
1886 foreach ( $errors as $index => $error ) {
1887 $errKey = is_array( $error ) ?
$error[0] : $error;
1889 if ( in_array( $errKey, $ignoreErrors ) ) {
1890 unset( $errors[$index] );
1892 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
1893 unset( $errors[$index] );
1901 * Permissions checks that fail most often, and which are easiest to test.
1903 * @param string $action The action to check
1904 * @param User $user User to check
1905 * @param array $errors List of current errors
1906 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1907 * @param bool $short Short circuit on first error
1909 * @return array List of errors
1911 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1912 if ( !Hooks
::run( 'TitleQuickPermissions',
1913 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1918 if ( $action == 'create' ) {
1920 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1921 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1923 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1925 } elseif ( $action == 'move' ) {
1926 if ( !$user->isAllowed( 'move-rootuserpages' )
1927 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1928 // Show user page-specific message only if the user can move other pages
1929 $errors[] = [ 'cant-move-user-page' ];
1932 // Check if user is allowed to move files if it's a file
1933 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1934 $errors[] = [ 'movenotallowedfile' ];
1937 // Check if user is allowed to move category pages if it's a category page
1938 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1939 $errors[] = [ 'cant-move-category-page' ];
1942 if ( !$user->isAllowed( 'move' ) ) {
1943 // User can't move anything
1944 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1945 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1946 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1947 // custom message if logged-in users without any special rights can move
1948 $errors[] = [ 'movenologintext' ];
1950 $errors[] = [ 'movenotallowed' ];
1953 } elseif ( $action == 'move-target' ) {
1954 if ( !$user->isAllowed( 'move' ) ) {
1955 // User can't move anything
1956 $errors[] = [ 'movenotallowed' ];
1957 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1958 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1959 // Show user page-specific message only if the user can move other pages
1960 $errors[] = [ 'cant-move-to-user-page' ];
1961 } elseif ( !$user->isAllowed( 'move-categorypages' )
1962 && $this->mNamespace
== NS_CATEGORY
) {
1963 // Show category page-specific message only if the user can move other pages
1964 $errors[] = [ 'cant-move-to-category-page' ];
1966 } elseif ( !$user->isAllowed( $action ) ) {
1967 $errors[] = $this->missingPermissionError( $action, $short );
1974 * Add the resulting error code to the errors array
1976 * @param array $errors List of current errors
1977 * @param array $result Result of errors
1979 * @return array List of errors
1981 private function resultToError( $errors, $result ) {
1982 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1983 // A single array representing an error
1984 $errors[] = $result;
1985 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1986 // A nested array representing multiple errors
1987 $errors = array_merge( $errors, $result );
1988 } elseif ( $result !== '' && is_string( $result ) ) {
1989 // A string representing a message-id
1990 $errors[] = [ $result ];
1991 } elseif ( $result instanceof MessageSpecifier
) {
1992 // A message specifier representing an error
1993 $errors[] = [ $result ];
1994 } elseif ( $result === false ) {
1995 // a generic "We don't want them to do that"
1996 $errors[] = [ 'badaccess-group0' ];
2002 * Check various permission hooks
2004 * @param string $action The action to check
2005 * @param User $user User to check
2006 * @param array $errors List of current errors
2007 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2008 * @param bool $short Short circuit on first error
2010 * @return array List of errors
2012 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2013 // Use getUserPermissionsErrors instead
2015 if ( !Hooks
::run( 'userCan', [ &$this, &$user, $action, &$result ] ) ) {
2016 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2018 // Check getUserPermissionsErrors hook
2019 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$this, &$user, $action, &$result ] ) ) {
2020 $errors = $this->resultToError( $errors, $result );
2022 // Check getUserPermissionsErrorsExpensive hook
2025 && !( $short && count( $errors ) > 0 )
2026 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$this, &$user, $action, &$result ] )
2028 $errors = $this->resultToError( $errors, $result );
2035 * Check permissions on special pages & namespaces
2037 * @param string $action The action to check
2038 * @param User $user User to check
2039 * @param array $errors List of current errors
2040 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2041 * @param bool $short Short circuit on first error
2043 * @return array List of errors
2045 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2046 # Only 'createaccount' can be performed on special pages,
2047 # which don't actually exist in the DB.
2048 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2049 $errors[] = [ 'ns-specialprotected' ];
2052 # Check $wgNamespaceProtection for restricted namespaces
2053 if ( $this->isNamespaceProtected( $user ) ) {
2054 $ns = $this->mNamespace
== NS_MAIN ?
2055 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2056 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2057 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2064 * Check CSS/JS sub-page permissions
2066 * @param string $action The action to check
2067 * @param User $user User to check
2068 * @param array $errors List of current errors
2069 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2070 * @param bool $short Short circuit on first error
2072 * @return array List of errors
2074 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2075 # Protect css/js subpages of user pages
2076 # XXX: this might be better using restrictions
2077 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2078 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2079 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2080 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2081 $errors[] = [ 'mycustomcssprotected', $action ];
2082 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2083 $errors[] = [ 'mycustomjsprotected', $action ];
2086 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2087 $errors[] = [ 'customcssprotected', $action ];
2088 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2089 $errors[] = [ 'customjsprotected', $action ];
2098 * Check against page_restrictions table requirements on this
2099 * page. The user must possess all required rights for this
2102 * @param string $action The action to check
2103 * @param User $user User to check
2104 * @param array $errors List of current errors
2105 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2106 * @param bool $short Short circuit on first error
2108 * @return array List of errors
2110 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2111 foreach ( $this->getRestrictions( $action ) as $right ) {
2112 // Backwards compatibility, rewrite sysop -> editprotected
2113 if ( $right == 'sysop' ) {
2114 $right = 'editprotected';
2116 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2117 if ( $right == 'autoconfirmed' ) {
2118 $right = 'editsemiprotected';
2120 if ( $right == '' ) {
2123 if ( !$user->isAllowed( $right ) ) {
2124 $errors[] = [ 'protectedpagetext', $right, $action ];
2125 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2126 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2134 * Check restrictions on cascading pages.
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 checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2145 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2146 # We /could/ use the protection level on the source page, but it's
2147 # fairly ugly as we have to establish a precedence hierarchy for pages
2148 # included by multiple cascade-protected pages. So just restrict
2149 # it to people with 'protect' permission, as they could remove the
2150 # protection anyway.
2151 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2152 # Cascading protection depends on more than this page...
2153 # Several cascading protected pages may include this page...
2154 # Check each cascading level
2155 # This is only for protection restrictions, not for all actions
2156 if ( isset( $restrictions[$action] ) ) {
2157 foreach ( $restrictions[$action] as $right ) {
2158 // Backwards compatibility, rewrite sysop -> editprotected
2159 if ( $right == 'sysop' ) {
2160 $right = 'editprotected';
2162 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2163 if ( $right == 'autoconfirmed' ) {
2164 $right = 'editsemiprotected';
2166 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2168 foreach ( $cascadingSources as $page ) {
2169 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2171 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2181 * Check action permissions not already checked in checkQuickPermissions
2183 * @param string $action The action to check
2184 * @param User $user User to check
2185 * @param array $errors List of current errors
2186 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2187 * @param bool $short Short circuit on first error
2189 * @return array List of errors
2191 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2192 global $wgDeleteRevisionsLimit, $wgLang;
2194 if ( $action == 'protect' ) {
2195 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2196 // If they can't edit, they shouldn't protect.
2197 $errors[] = [ 'protect-cantedit' ];
2199 } elseif ( $action == 'create' ) {
2200 $title_protection = $this->getTitleProtection();
2201 if ( $title_protection ) {
2202 if ( $title_protection['permission'] == ''
2203 ||
!$user->isAllowed( $title_protection['permission'] )
2207 User
::whoIs( $title_protection['user'] ),
2208 $title_protection['reason']
2212 } elseif ( $action == 'move' ) {
2213 // Check for immobile pages
2214 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2215 // Specific message for this case
2216 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2217 } elseif ( !$this->isMovable() ) {
2218 // Less specific message for rarer cases
2219 $errors[] = [ 'immobile-source-page' ];
2221 } elseif ( $action == 'move-target' ) {
2222 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2223 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2224 } elseif ( !$this->isMovable() ) {
2225 $errors[] = [ 'immobile-target-page' ];
2227 } elseif ( $action == 'delete' ) {
2228 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2229 if ( !$tempErrors ) {
2230 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2231 $user, $tempErrors, $rigor, true );
2233 if ( $tempErrors ) {
2234 // If protection keeps them from editing, they shouldn't be able to delete.
2235 $errors[] = [ 'deleteprotected' ];
2237 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2238 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2240 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2247 * Check that the user isn't blocked from editing.
2249 * @param string $action The action to check
2250 * @param User $user User to check
2251 * @param array $errors List of current errors
2252 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2253 * @param bool $short Short circuit on first error
2255 * @return array List of errors
2257 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2258 // Account creation blocks handled at userlogin.
2259 // Unblocking handled in SpecialUnblock
2260 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2264 global $wgEmailConfirmToEdit;
2266 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2267 $errors[] = [ 'confirmedittext' ];
2270 $useSlave = ( $rigor !== 'secure' );
2271 if ( ( $action == 'edit' ||
$action == 'create' )
2272 && !$user->isBlockedFrom( $this, $useSlave )
2274 // Don't block the user from editing their own talk page unless they've been
2275 // explicitly blocked from that too.
2276 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2277 // @todo FIXME: Pass the relevant context into this function.
2278 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2285 * Check that the user is allowed to read this page.
2287 * @param string $action The action to check
2288 * @param User $user User to check
2289 * @param array $errors List of current errors
2290 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2291 * @param bool $short Short circuit on first error
2293 * @return array List of errors
2295 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2296 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2298 $whitelisted = false;
2299 if ( User
::isEveryoneAllowed( 'read' ) ) {
2300 # Shortcut for public wikis, allows skipping quite a bit of code
2301 $whitelisted = true;
2302 } elseif ( $user->isAllowed( 'read' ) ) {
2303 # If the user is allowed to read pages, he is allowed to read all pages
2304 $whitelisted = true;
2305 } elseif ( $this->isSpecial( 'Userlogin' )
2306 ||
$this->isSpecial( 'ChangePassword' )
2307 ||
$this->isSpecial( 'PasswordReset' )
2309 # Always grant access to the login page.
2310 # Even anons need to be able to log in.
2311 $whitelisted = true;
2312 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2313 # Time to check the whitelist
2314 # Only do these checks is there's something to check against
2315 $name = $this->getPrefixedText();
2316 $dbName = $this->getPrefixedDBkey();
2318 // Check for explicit whitelisting with and without underscores
2319 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2320 $whitelisted = true;
2321 } elseif ( $this->getNamespace() == NS_MAIN
) {
2322 # Old settings might have the title prefixed with
2323 # a colon for main-namespace pages
2324 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2325 $whitelisted = true;
2327 } elseif ( $this->isSpecialPage() ) {
2328 # If it's a special page, ditch the subpage bit and check again
2329 $name = $this->getDBkey();
2330 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2332 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2333 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2334 $whitelisted = true;
2340 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2341 $name = $this->getPrefixedText();
2342 // Check for regex whitelisting
2343 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2344 if ( preg_match( $listItem, $name ) ) {
2345 $whitelisted = true;
2351 if ( !$whitelisted ) {
2352 # If the title is not whitelisted, give extensions a chance to do so...
2353 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2354 if ( !$whitelisted ) {
2355 $errors[] = $this->missingPermissionError( $action, $short );
2363 * Get a description array when the user doesn't have the right to perform
2364 * $action (i.e. when User::isAllowed() returns false)
2366 * @param string $action The action to check
2367 * @param bool $short Short circuit on first error
2368 * @return array List of errors
2370 private function missingPermissionError( $action, $short ) {
2371 // We avoid expensive display logic for quickUserCan's and such
2373 return [ 'badaccess-group0' ];
2376 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2377 User
::getGroupsWithPermission( $action ) );
2379 if ( count( $groups ) ) {
2383 $wgLang->commaList( $groups ),
2387 return [ 'badaccess-group0' ];
2392 * Can $user perform $action on this page? This is an internal function,
2393 * with multiple levels of checks depending on performance needs; see $rigor below.
2394 * It does not check wfReadOnly().
2396 * @param string $action Action that permission needs to be checked for
2397 * @param User $user User to check
2398 * @param string $rigor One of (quick,full,secure)
2399 * - quick : does cheap permission checks from slaves (usable for GUI creation)
2400 * - full : does cheap and expensive checks possibly from a slave
2401 * - secure : does cheap and expensive checks, using the master as needed
2402 * @param bool $short Set this to true to stop after the first permission error.
2403 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2405 protected function getUserPermissionsErrorsInternal(
2406 $action, $user, $rigor = 'secure', $short = false
2408 if ( $rigor === true ) {
2409 $rigor = 'secure'; // b/c
2410 } elseif ( $rigor === false ) {
2411 $rigor = 'quick'; // b/c
2412 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2413 throw new Exception( "Invalid rigor parameter '$rigor'." );
2416 # Read has special handling
2417 if ( $action == 'read' ) {
2419 'checkPermissionHooks',
2420 'checkReadPermissions',
2422 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2423 # here as it will lead to duplicate error messages. This is okay to do
2424 # since anywhere that checks for create will also check for edit, and
2425 # those checks are called for edit.
2426 } elseif ( $action == 'create' ) {
2428 'checkQuickPermissions',
2429 'checkPermissionHooks',
2430 'checkPageRestrictions',
2431 'checkCascadingSourcesRestrictions',
2432 'checkActionPermissions',
2437 'checkQuickPermissions',
2438 'checkPermissionHooks',
2439 'checkSpecialsAndNSPermissions',
2440 'checkCSSandJSPermissions',
2441 'checkPageRestrictions',
2442 'checkCascadingSourcesRestrictions',
2443 'checkActionPermissions',
2449 while ( count( $checks ) > 0 &&
2450 !( $short && count( $errors ) > 0 ) ) {
2451 $method = array_shift( $checks );
2452 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2459 * Get a filtered list of all restriction types supported by this wiki.
2460 * @param bool $exists True to get all restriction types that apply to
2461 * titles that do exist, False for all restriction types that apply to
2462 * titles that do not exist
2465 public static function getFilteredRestrictionTypes( $exists = true ) {
2466 global $wgRestrictionTypes;
2467 $types = $wgRestrictionTypes;
2469 # Remove the create restriction for existing titles
2470 $types = array_diff( $types, [ 'create' ] );
2472 # Only the create and upload restrictions apply to non-existing titles
2473 $types = array_intersect( $types, [ 'create', 'upload' ] );
2479 * Returns restriction types for the current Title
2481 * @return array Applicable restriction types
2483 public function getRestrictionTypes() {
2484 if ( $this->isSpecialPage() ) {
2488 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2490 if ( $this->getNamespace() != NS_FILE
) {
2491 # Remove the upload restriction for non-file titles
2492 $types = array_diff( $types, [ 'upload' ] );
2495 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2497 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2498 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2504 * Is this title subject to title protection?
2505 * Title protection is the one applied against creation of such title.
2507 * @return array|bool An associative array representing any existent title
2508 * protection, or false if there's none.
2510 public function getTitleProtection() {
2511 // Can't protect pages in special namespaces
2512 if ( $this->getNamespace() < 0 ) {
2516 // Can't protect pages that exist.
2517 if ( $this->exists() ) {
2521 if ( $this->mTitleProtection
=== null ) {
2522 $dbr = wfGetDB( DB_SLAVE
);
2523 $res = $dbr->select(
2526 'user' => 'pt_user',
2527 'reason' => 'pt_reason',
2528 'expiry' => 'pt_expiry',
2529 'permission' => 'pt_create_perm'
2531 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2535 // fetchRow returns false if there are no rows.
2536 $row = $dbr->fetchRow( $res );
2538 if ( $row['permission'] == 'sysop' ) {
2539 $row['permission'] = 'editprotected'; // B/C
2541 if ( $row['permission'] == 'autoconfirmed' ) {
2542 $row['permission'] = 'editsemiprotected'; // B/C
2544 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2546 $this->mTitleProtection
= $row;
2548 return $this->mTitleProtection
;
2552 * Remove any title protection due to page existing
2554 public function deleteTitleProtection() {
2555 $dbw = wfGetDB( DB_MASTER
);
2559 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2562 $this->mTitleProtection
= false;
2566 * Is this page "semi-protected" - the *only* protection levels are listed
2567 * in $wgSemiprotectedRestrictionLevels?
2569 * @param string $action Action to check (default: edit)
2572 public function isSemiProtected( $action = 'edit' ) {
2573 global $wgSemiprotectedRestrictionLevels;
2575 $restrictions = $this->getRestrictions( $action );
2576 $semi = $wgSemiprotectedRestrictionLevels;
2577 if ( !$restrictions ||
!$semi ) {
2578 // Not protected, or all protection is full protection
2582 // Remap autoconfirmed to editsemiprotected for BC
2583 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2584 $semi[$key] = 'editsemiprotected';
2586 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2587 $restrictions[$key] = 'editsemiprotected';
2590 return !array_diff( $restrictions, $semi );
2594 * Does the title correspond to a protected article?
2596 * @param string $action The action the page is protected from,
2597 * by default checks all actions.
2600 public function isProtected( $action = '' ) {
2601 global $wgRestrictionLevels;
2603 $restrictionTypes = $this->getRestrictionTypes();
2605 # Special pages have inherent protection
2606 if ( $this->isSpecialPage() ) {
2610 # Check regular protection levels
2611 foreach ( $restrictionTypes as $type ) {
2612 if ( $action == $type ||
$action == '' ) {
2613 $r = $this->getRestrictions( $type );
2614 foreach ( $wgRestrictionLevels as $level ) {
2615 if ( in_array( $level, $r ) && $level != '' ) {
2626 * Determines if $user is unable to edit this page because it has been protected
2627 * by $wgNamespaceProtection.
2629 * @param User $user User object to check permissions
2632 public function isNamespaceProtected( User
$user ) {
2633 global $wgNamespaceProtection;
2635 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2636 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2637 if ( $right != '' && !$user->isAllowed( $right ) ) {
2646 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2648 * @return bool If the page is subject to cascading restrictions.
2650 public function isCascadeProtected() {
2651 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2652 return ( $sources > 0 );
2656 * Determines whether cascading protection sources have already been loaded from
2659 * @param bool $getPages True to check if the pages are loaded, or false to check
2660 * if the status is loaded.
2661 * @return bool Whether or not the specified information has been loaded
2664 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2665 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2669 * Cascading protection: Get the source of any cascading restrictions on this page.
2671 * @param bool $getPages Whether or not to retrieve the actual pages
2672 * that the restrictions have come from and the actual restrictions
2674 * @return array Two elements: First is an array of Title objects of the
2675 * pages from which cascading restrictions have come, false for
2676 * none, or true if such restrictions exist but $getPages was not
2677 * set. Second is an array like that returned by
2678 * Title::getAllRestrictions(), or an empty array if $getPages is
2681 public function getCascadeProtectionSources( $getPages = true ) {
2682 $pagerestrictions = [];
2684 if ( $this->mCascadeSources
!== null && $getPages ) {
2685 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2686 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2687 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2690 $dbr = wfGetDB( DB_SLAVE
);
2692 if ( $this->getNamespace() == NS_FILE
) {
2693 $tables = [ 'imagelinks', 'page_restrictions' ];
2695 'il_to' => $this->getDBkey(),
2700 $tables = [ 'templatelinks', 'page_restrictions' ];
2702 'tl_namespace' => $this->getNamespace(),
2703 'tl_title' => $this->getDBkey(),
2710 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2711 'pr_expiry', 'pr_type', 'pr_level' ];
2712 $where_clauses[] = 'page_id=pr_page';
2715 $cols = [ 'pr_expiry' ];
2718 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2720 $sources = $getPages ?
[] : false;
2721 $now = wfTimestampNow();
2723 foreach ( $res as $row ) {
2724 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2725 if ( $expiry > $now ) {
2727 $page_id = $row->pr_page
;
2728 $page_ns = $row->page_namespace
;
2729 $page_title = $row->page_title
;
2730 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2731 # Add groups needed for each restriction type if its not already there
2732 # Make sure this restriction type still exists
2734 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2735 $pagerestrictions[$row->pr_type
] = [];
2739 isset( $pagerestrictions[$row->pr_type
] )
2740 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2742 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2751 $this->mCascadeSources
= $sources;
2752 $this->mCascadingRestrictions
= $pagerestrictions;
2754 $this->mHasCascadingRestrictions
= $sources;
2757 return [ $sources, $pagerestrictions ];
2761 * Accessor for mRestrictionsLoaded
2763 * @return bool Whether or not the page's restrictions have already been
2764 * loaded from the database
2767 public function areRestrictionsLoaded() {
2768 return $this->mRestrictionsLoaded
;
2772 * Accessor/initialisation for mRestrictions
2774 * @param string $action Action that permission needs to be checked for
2775 * @return array Restriction levels needed to take the action. All levels are
2776 * required. Note that restriction levels are normally user rights, but 'sysop'
2777 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2778 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2780 public function getRestrictions( $action ) {
2781 if ( !$this->mRestrictionsLoaded
) {
2782 $this->loadRestrictions();
2784 return isset( $this->mRestrictions
[$action] )
2785 ?
$this->mRestrictions
[$action]
2790 * Accessor/initialisation for mRestrictions
2792 * @return array Keys are actions, values are arrays as returned by
2793 * Title::getRestrictions()
2796 public function getAllRestrictions() {
2797 if ( !$this->mRestrictionsLoaded
) {
2798 $this->loadRestrictions();
2800 return $this->mRestrictions
;
2804 * Get the expiry time for the restriction against a given action
2806 * @param string $action
2807 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2808 * or not protected at all, or false if the action is not recognised.
2810 public function getRestrictionExpiry( $action ) {
2811 if ( !$this->mRestrictionsLoaded
) {
2812 $this->loadRestrictions();
2814 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2818 * Returns cascading restrictions for the current article
2822 function areRestrictionsCascading() {
2823 if ( !$this->mRestrictionsLoaded
) {
2824 $this->loadRestrictions();
2827 return $this->mCascadeRestriction
;
2831 * Loads a string into mRestrictions array
2833 * @param ResultWrapper $res Resource restrictions as an SQL result.
2834 * @param string $oldFashionedRestrictions Comma-separated list of page
2835 * restrictions from page table (pre 1.10)
2837 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2840 foreach ( $res as $row ) {
2844 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2848 * Compiles list of active page restrictions from both page table (pre 1.10)
2849 * and page_restrictions table for this existing page.
2850 * Public for usage by LiquidThreads.
2852 * @param array $rows Array of db result objects
2853 * @param string $oldFashionedRestrictions Comma-separated list of page
2854 * restrictions from page table (pre 1.10)
2856 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2857 $dbr = wfGetDB( DB_SLAVE
);
2859 $restrictionTypes = $this->getRestrictionTypes();
2861 foreach ( $restrictionTypes as $type ) {
2862 $this->mRestrictions
[$type] = [];
2863 $this->mRestrictionsExpiry
[$type] = 'infinity';
2866 $this->mCascadeRestriction
= false;
2868 # Backwards-compatibility: also load the restrictions from the page record (old format).
2869 if ( $oldFashionedRestrictions !== null ) {
2870 $this->mOldRestrictions
= $oldFashionedRestrictions;
2873 if ( $this->mOldRestrictions
=== false ) {
2874 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
2875 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
2878 if ( $this->mOldRestrictions
!= '' ) {
2879 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2880 $temp = explode( '=', trim( $restrict ) );
2881 if ( count( $temp ) == 1 ) {
2882 // old old format should be treated as edit/move restriction
2883 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2884 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2886 $restriction = trim( $temp[1] );
2887 if ( $restriction != '' ) { // some old entries are empty
2888 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2894 if ( count( $rows ) ) {
2895 # Current system - load second to make them override.
2896 $now = wfTimestampNow();
2898 # Cycle through all the restrictions.
2899 foreach ( $rows as $row ) {
2901 // Don't take care of restrictions types that aren't allowed
2902 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2906 // This code should be refactored, now that it's being used more generally,
2907 // But I don't really see any harm in leaving it in Block for now -werdna
2908 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2910 // Only apply the restrictions if they haven't expired!
2911 if ( !$expiry ||
$expiry > $now ) {
2912 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2913 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2915 $this->mCascadeRestriction |
= $row->pr_cascade
;
2920 $this->mRestrictionsLoaded
= true;
2924 * Load restrictions from the page_restrictions table
2926 * @param string $oldFashionedRestrictions Comma-separated list of page
2927 * restrictions from page table (pre 1.10)
2929 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2930 if ( !$this->mRestrictionsLoaded
) {
2931 $dbr = wfGetDB( DB_SLAVE
);
2932 if ( $this->exists() ) {
2933 $res = $dbr->select(
2934 'page_restrictions',
2935 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2936 [ 'pr_page' => $this->getArticleID() ],
2940 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2942 $title_protection = $this->getTitleProtection();
2944 if ( $title_protection ) {
2945 $now = wfTimestampNow();
2946 $expiry = $dbr->decodeExpiry( $title_protection['expiry'] );
2948 if ( !$expiry ||
$expiry > $now ) {
2949 // Apply the restrictions
2950 $this->mRestrictionsExpiry
['create'] = $expiry;
2951 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
2952 } else { // Get rid of the old restrictions
2953 $this->mTitleProtection
= false;
2956 $this->mRestrictionsExpiry
['create'] = 'infinity';
2958 $this->mRestrictionsLoaded
= true;
2964 * Flush the protection cache in this object and force reload from the database.
2965 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2967 public function flushRestrictions() {
2968 $this->mRestrictionsLoaded
= false;
2969 $this->mTitleProtection
= null;
2973 * Purge expired restrictions from the page_restrictions table
2975 static function purgeExpiredRestrictions() {
2976 if ( wfReadOnly() ) {
2980 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2981 wfGetDB( DB_MASTER
),
2983 function ( IDatabase
$dbw, $fname ) {
2985 'page_restrictions',
2986 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2991 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2999 * Does this have subpages? (Warning, usually requires an extra DB query.)
3003 public function hasSubpages() {
3004 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3009 # We dynamically add a member variable for the purpose of this method
3010 # alone to cache the result. There's no point in having it hanging
3011 # around uninitialized in every Title object; therefore we only add it
3012 # if needed and don't declare it statically.
3013 if ( $this->mHasSubpages
=== null ) {
3014 $this->mHasSubpages
= false;
3015 $subpages = $this->getSubpages( 1 );
3016 if ( $subpages instanceof TitleArray
) {
3017 $this->mHasSubpages
= (bool)$subpages->count();
3021 return $this->mHasSubpages
;
3025 * Get all subpages of this page.
3027 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3028 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3029 * doesn't allow subpages
3031 public function getSubpages( $limit = -1 ) {
3032 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3036 $dbr = wfGetDB( DB_SLAVE
);
3037 $conds['page_namespace'] = $this->getNamespace();
3038 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3040 if ( $limit > -1 ) {
3041 $options['LIMIT'] = $limit;
3043 $this->mSubpages
= TitleArray
::newFromResult(
3044 $dbr->select( 'page',
3045 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3051 return $this->mSubpages
;
3055 * Is there a version of this page in the deletion archive?
3057 * @return int The number of archived revisions
3059 public function isDeleted() {
3060 if ( $this->getNamespace() < 0 ) {
3063 $dbr = wfGetDB( DB_SLAVE
);
3065 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3066 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3069 if ( $this->getNamespace() == NS_FILE
) {
3070 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3071 [ 'fa_name' => $this->getDBkey() ],
3080 * Is there a version of this page in the deletion archive?
3084 public function isDeletedQuick() {
3085 if ( $this->getNamespace() < 0 ) {
3088 $dbr = wfGetDB( DB_SLAVE
);
3089 $deleted = (bool)$dbr->selectField( 'archive', '1',
3090 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3093 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3094 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3095 [ 'fa_name' => $this->getDBkey() ],
3103 * Get the article ID for this Title from the link cache,
3104 * adding it if necessary
3106 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3108 * @return int The ID
3110 public function getArticleID( $flags = 0 ) {
3111 if ( $this->getNamespace() < 0 ) {
3112 $this->mArticleID
= 0;
3113 return $this->mArticleID
;
3115 $linkCache = LinkCache
::singleton();
3116 if ( $flags & self
::GAID_FOR_UPDATE
) {
3117 $oldUpdate = $linkCache->forUpdate( true );
3118 $linkCache->clearLink( $this );
3119 $this->mArticleID
= $linkCache->addLinkObj( $this );
3120 $linkCache->forUpdate( $oldUpdate );
3122 if ( -1 == $this->mArticleID
) {
3123 $this->mArticleID
= $linkCache->addLinkObj( $this );
3126 return $this->mArticleID
;
3130 * Is this an article that is a redirect page?
3131 * Uses link cache, adding it if necessary
3133 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3136 public function isRedirect( $flags = 0 ) {
3137 if ( !is_null( $this->mRedirect
) ) {
3138 return $this->mRedirect
;
3140 if ( !$this->getArticleID( $flags ) ) {
3141 $this->mRedirect
= false;
3142 return $this->mRedirect
;
3145 $linkCache = LinkCache
::singleton();
3146 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3147 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3148 if ( $cached === null ) {
3149 # Trust LinkCache's state over our own
3150 # LinkCache is telling us that the page doesn't exist, despite there being cached
3151 # data relating to an existing page in $this->mArticleID. Updaters should clear
3152 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3153 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3154 # LinkCache to refresh its data from the master.
3155 $this->mRedirect
= false;
3156 return $this->mRedirect
;
3159 $this->mRedirect
= (bool)$cached;
3161 return $this->mRedirect
;
3165 * What is the length of this page?
3166 * Uses link cache, adding it if necessary
3168 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3171 public function getLength( $flags = 0 ) {
3172 if ( $this->mLength
!= -1 ) {
3173 return $this->mLength
;
3175 if ( !$this->getArticleID( $flags ) ) {
3177 return $this->mLength
;
3179 $linkCache = LinkCache
::singleton();
3180 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3181 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3182 if ( $cached === null ) {
3183 # Trust LinkCache's state over our own, as for isRedirect()
3185 return $this->mLength
;
3188 $this->mLength
= intval( $cached );
3190 return $this->mLength
;
3194 * What is the page_latest field for this page?
3196 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3197 * @return int Int or 0 if the page doesn't exist
3199 public function getLatestRevID( $flags = 0 ) {
3200 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3201 return intval( $this->mLatestID
);
3203 if ( !$this->getArticleID( $flags ) ) {
3204 $this->mLatestID
= 0;
3205 return $this->mLatestID
;
3207 $linkCache = LinkCache
::singleton();
3208 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3209 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3210 if ( $cached === null ) {
3211 # Trust LinkCache's state over our own, as for isRedirect()
3212 $this->mLatestID
= 0;
3213 return $this->mLatestID
;
3216 $this->mLatestID
= intval( $cached );
3218 return $this->mLatestID
;
3222 * This clears some fields in this object, and clears any associated
3223 * keys in the "bad links" section of the link cache.
3225 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3226 * loading of the new page_id. It's also called from
3227 * WikiPage::doDeleteArticleReal()
3229 * @param int $newid The new Article ID
3231 public function resetArticleID( $newid ) {
3232 $linkCache = LinkCache
::singleton();
3233 $linkCache->clearLink( $this );
3235 if ( $newid === false ) {
3236 $this->mArticleID
= -1;
3238 $this->mArticleID
= intval( $newid );
3240 $this->mRestrictionsLoaded
= false;
3241 $this->mRestrictions
= [];
3242 $this->mOldRestrictions
= false;
3243 $this->mRedirect
= null;
3244 $this->mLength
= -1;
3245 $this->mLatestID
= false;
3246 $this->mContentModel
= false;
3247 $this->mEstimateRevisions
= null;
3248 $this->mPageLanguage
= false;
3249 $this->mDbPageLanguage
= false;
3250 $this->mIsBigDeletion
= null;
3253 public static function clearCaches() {
3254 $linkCache = LinkCache
::singleton();
3255 $linkCache->clear();
3257 $titleCache = self
::getTitleCache();
3258 $titleCache->clear();
3262 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3264 * @param string $text Containing title to capitalize
3265 * @param int $ns Namespace index, defaults to NS_MAIN
3266 * @return string Containing capitalized title
3268 public static function capitalize( $text, $ns = NS_MAIN
) {
3271 if ( MWNamespace
::isCapitalized( $ns ) ) {
3272 return $wgContLang->ucfirst( $text );
3279 * Secure and split - main initialisation function for this object
3281 * Assumes that mDbkeyform has been set, and is urldecoded
3282 * and uses underscores, but not otherwise munged. This function
3283 * removes illegal characters, splits off the interwiki and
3284 * namespace prefixes, sets the other forms, and canonicalizes
3287 * @throws MalformedTitleException On invalid titles
3288 * @return bool True on success
3290 private function secureAndSplit() {
3292 $this->mInterwiki
= '';
3293 $this->mFragment
= '';
3294 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3296 $dbkey = $this->mDbkeyform
;
3298 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3299 // the parsing code with Title, while avoiding massive refactoring.
3300 // @todo: get rid of secureAndSplit, refactor parsing code.
3301 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3302 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3303 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3304 // MalformedTitleException can be thrown here
3305 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3308 $this->setFragment( '#' . $parts['fragment'] );
3309 $this->mInterwiki
= $parts['interwiki'];
3310 $this->mLocalInterwiki
= $parts['local_interwiki'];
3311 $this->mNamespace
= $parts['namespace'];
3312 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3314 $this->mDbkeyform
= $parts['dbkey'];
3315 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3316 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3318 # We already know that some pages won't be in the database!
3319 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3320 $this->mArticleID
= 0;
3327 * Get an array of Title objects linking to this Title
3328 * Also stores the IDs in the link cache.
3330 * WARNING: do not use this function on arbitrary user-supplied titles!
3331 * On heavily-used templates it will max out the memory.
3333 * @param array $options May be FOR UPDATE
3334 * @param string $table Table name
3335 * @param string $prefix Fields prefix
3336 * @return Title[] Array of Title objects linking here
3338 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3339 if ( count( $options ) > 0 ) {
3340 $db = wfGetDB( DB_MASTER
);
3342 $db = wfGetDB( DB_SLAVE
);
3347 self
::getSelectFields(),
3349 "{$prefix}_from=page_id",
3350 "{$prefix}_namespace" => $this->getNamespace(),
3351 "{$prefix}_title" => $this->getDBkey() ],
3357 if ( $res->numRows() ) {
3358 $linkCache = LinkCache
::singleton();
3359 foreach ( $res as $row ) {
3360 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3362 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3363 $retVal[] = $titleObj;
3371 * Get an array of Title objects using this Title as a template
3372 * Also stores the IDs in the link cache.
3374 * WARNING: do not use this function on arbitrary user-supplied titles!
3375 * On heavily-used templates it will max out the memory.
3377 * @param array $options Query option to Database::select()
3378 * @return Title[] Array of Title the Title objects linking here
3380 public function getTemplateLinksTo( $options = [] ) {
3381 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3385 * Get an array of Title objects linked from this Title
3386 * Also stores the IDs in the link cache.
3388 * WARNING: do not use this function on arbitrary user-supplied titles!
3389 * On heavily-used templates it will max out the memory.
3391 * @param array $options Query option to Database::select()
3392 * @param string $table Table name
3393 * @param string $prefix Fields prefix
3394 * @return array Array of Title objects linking here
3396 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3397 $id = $this->getArticleID();
3399 # If the page doesn't exist; there can't be any link from this page
3404 $db = wfGetDB( DB_SLAVE
);
3406 $blNamespace = "{$prefix}_namespace";
3407 $blTitle = "{$prefix}_title";
3412 [ $blNamespace, $blTitle ],
3413 WikiPage
::selectFields()
3415 [ "{$prefix}_from" => $id ],
3420 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3425 $linkCache = LinkCache
::singleton();
3426 foreach ( $res as $row ) {
3427 if ( $row->page_id
) {
3428 $titleObj = Title
::newFromRow( $row );
3430 $titleObj = Title
::makeTitle( $row->$blNamespace, $row->$blTitle );
3431 $linkCache->addBadLinkObj( $titleObj );
3433 $retVal[] = $titleObj;
3440 * Get an array of Title objects used on this Title as a template
3441 * Also stores the IDs in the link cache.
3443 * WARNING: do not use this function on arbitrary user-supplied titles!
3444 * On heavily-used templates it will max out the memory.
3446 * @param array $options May be FOR UPDATE
3447 * @return Title[] Array of Title the Title objects used here
3449 public function getTemplateLinksFrom( $options = [] ) {
3450 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3454 * Get an array of Title objects referring to non-existent articles linked
3457 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3458 * should use redirect table in this case).
3459 * @return Title[] Array of Title the Title objects
3461 public function getBrokenLinksFrom() {
3462 if ( $this->getArticleID() == 0 ) {
3463 # All links from article ID 0 are false positives
3467 $dbr = wfGetDB( DB_SLAVE
);
3468 $res = $dbr->select(
3469 [ 'page', 'pagelinks' ],
3470 [ 'pl_namespace', 'pl_title' ],
3472 'pl_from' => $this->getArticleID(),
3473 'page_namespace IS NULL'
3479 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3485 foreach ( $res as $row ) {
3486 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3492 * Get a list of URLs to purge from the CDN cache when this
3495 * @return string[] Array of String the URLs
3497 public function getCdnUrls() {
3499 $this->getInternalURL(),
3500 $this->getInternalURL( 'action=history' )
3503 $pageLang = $this->getPageLanguage();
3504 if ( $pageLang->hasVariants() ) {
3505 $variants = $pageLang->getVariants();
3506 foreach ( $variants as $vCode ) {
3507 $urls[] = $this->getInternalURL( $vCode );
3511 // If we are looking at a css/js user subpage, purge the action=raw.
3512 if ( $this->isJsSubpage() ) {
3513 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3514 } elseif ( $this->isCssSubpage() ) {
3515 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3518 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3523 * @deprecated since 1.27 use getCdnUrls()
3525 public function getSquidURLs() {
3526 return $this->getCdnUrls();
3530 * Purge all applicable CDN URLs
3532 public function purgeSquid() {
3533 DeferredUpdates
::addUpdate(
3534 new CdnCacheUpdate( $this->getCdnUrls() ),
3535 DeferredUpdates
::PRESEND
3540 * Move this page without authentication
3542 * @deprecated since 1.25 use MovePage class instead
3543 * @param Title $nt The new page Title
3544 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3546 public function moveNoAuth( &$nt ) {
3547 wfDeprecated( __METHOD__
, '1.25' );
3548 return $this->moveTo( $nt, false );
3552 * Check whether a given move operation would be valid.
3553 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3555 * @deprecated since 1.25, use MovePage's methods instead
3556 * @param Title $nt The new title
3557 * @param bool $auth Whether to check user permissions (uses $wgUser)
3558 * @param string $reason Is the log summary of the move, used for spam checking
3559 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3561 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3564 if ( !( $nt instanceof Title
) ) {
3565 // Normally we'd add this to $errors, but we'll get
3566 // lots of syntax errors if $nt is not an object
3567 return [ [ 'badtitletext' ] ];
3570 $mp = new MovePage( $this, $nt );
3571 $errors = $mp->isValidMove()->getErrorsArray();
3573 $errors = wfMergeErrorArrays(
3575 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3579 return $errors ?
: true;
3583 * Check if the requested move target is a valid file move target
3584 * @todo move this to MovePage
3585 * @param Title $nt Target title
3586 * @return array List of errors
3588 protected function validateFileMoveOperation( $nt ) {
3593 $destFile = wfLocalFile( $nt );
3594 $destFile->load( File
::READ_LATEST
);
3595 if ( !$wgUser->isAllowed( 'reupload-shared' )
3596 && !$destFile->exists() && wfFindFile( $nt )
3598 $errors[] = [ 'file-exists-sharedrepo' ];
3605 * Move a title to a new location
3607 * @deprecated since 1.25, use the MovePage class instead
3608 * @param Title $nt The new title
3609 * @param bool $auth Indicates whether $wgUser's permissions
3611 * @param string $reason The reason for the move
3612 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3613 * Ignored if the user doesn't have the suppressredirect right.
3614 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3616 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3618 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3619 if ( is_array( $err ) ) {
3620 // Auto-block user's IP if the account was "hard" blocked
3621 $wgUser->spreadAnyEditBlock();
3624 // Check suppressredirect permission
3625 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3626 $createRedirect = true;
3629 $mp = new MovePage( $this, $nt );
3630 $status = $mp->move( $wgUser, $reason, $createRedirect );
3631 if ( $status->isOK() ) {
3634 return $status->getErrorsArray();
3639 * Move this page's subpages to be subpages of $nt
3641 * @param Title $nt Move target
3642 * @param bool $auth Whether $wgUser's permissions should be checked
3643 * @param string $reason The reason for the move
3644 * @param bool $createRedirect Whether to create redirects from the old subpages to
3645 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3646 * @return array Array with old page titles as keys, and strings (new page titles) or
3647 * arrays (errors) as values, or an error array with numeric indices if no pages
3650 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3651 global $wgMaximumMovedPages;
3652 // Check permissions
3653 if ( !$this->userCan( 'move-subpages' ) ) {
3654 return [ 'cant-move-subpages' ];
3656 // Do the source and target namespaces support subpages?
3657 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3658 return [ 'namespace-nosubpages',
3659 MWNamespace
::getCanonicalName( $this->getNamespace() ) ];
3661 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3662 return [ 'namespace-nosubpages',
3663 MWNamespace
::getCanonicalName( $nt->getNamespace() ) ];
3666 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3669 foreach ( $subpages as $oldSubpage ) {
3671 if ( $count > $wgMaximumMovedPages ) {
3672 $retval[$oldSubpage->getPrefixedText()] =
3673 [ 'movepage-max-pages',
3674 $wgMaximumMovedPages ];
3678 // We don't know whether this function was called before
3679 // or after moving the root page, so check both
3681 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3682 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3684 // When moving a page to a subpage of itself,
3685 // don't move it twice
3688 $newPageName = preg_replace(
3689 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3690 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3691 $oldSubpage->getDBkey() );
3692 if ( $oldSubpage->isTalkPage() ) {
3693 $newNs = $nt->getTalkPage()->getNamespace();
3695 $newNs = $nt->getSubjectPage()->getNamespace();
3697 # Bug 14385: we need makeTitleSafe because the new page names may
3698 # be longer than 255 characters.
3699 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3701 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3702 if ( $success === true ) {
3703 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3705 $retval[$oldSubpage->getPrefixedText()] = $success;
3712 * Checks if this page is just a one-rev redirect.
3713 * Adds lock, so don't use just for light purposes.
3717 public function isSingleRevRedirect() {
3718 global $wgContentHandlerUseDB;
3720 $dbw = wfGetDB( DB_MASTER
);
3723 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3724 if ( $wgContentHandlerUseDB ) {
3725 $fields[] = 'page_content_model';
3728 $row = $dbw->selectRow( 'page',
3734 # Cache some fields we may want
3735 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3736 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3737 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3738 $this->mContentModel
= $row && isset( $row->page_content_model
)
3739 ?
strval( $row->page_content_model
)
3742 if ( !$this->mRedirect
) {
3745 # Does the article have a history?
3746 $row = $dbw->selectField( [ 'page', 'revision' ],
3748 [ 'page_namespace' => $this->getNamespace(),
3749 'page_title' => $this->getDBkey(),
3751 'page_latest != rev_id'
3756 # Return true if there was no history
3757 return ( $row === false );
3761 * Checks if $this can be moved to a given Title
3762 * - Selects for update, so don't call it unless you mean business
3764 * @deprecated since 1.25, use MovePage's methods instead
3765 * @param Title $nt The new title to check
3768 public function isValidMoveTarget( $nt ) {
3769 # Is it an existing file?
3770 if ( $nt->getNamespace() == NS_FILE
) {
3771 $file = wfLocalFile( $nt );
3772 $file->load( File
::READ_LATEST
);
3773 if ( $file->exists() ) {
3774 wfDebug( __METHOD__
. ": file exists\n" );
3778 # Is it a redirect with no history?
3779 if ( !$nt->isSingleRevRedirect() ) {
3780 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3783 # Get the article text
3784 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3785 if ( !is_object( $rev ) ) {
3788 $content = $rev->getContent();
3789 # Does the redirect point to the source?
3790 # Or is it a broken self-redirect, usually caused by namespace collisions?
3791 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3793 if ( $redirTitle ) {
3794 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3795 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3796 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3802 # Fail safe (not a redirect after all. strange.)
3803 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3804 " is a redirect, but it doesn't contain a valid redirect.\n" );
3810 * Get categories to which this Title belongs and return an array of
3811 * categories' names.
3813 * @return array Array of parents in the form:
3814 * $parent => $currentarticle
3816 public function getParentCategories() {
3821 $titleKey = $this->getArticleID();
3823 if ( $titleKey === 0 ) {
3827 $dbr = wfGetDB( DB_SLAVE
);
3829 $res = $dbr->select(
3832 [ 'cl_from' => $titleKey ],
3836 if ( $res->numRows() > 0 ) {
3837 foreach ( $res as $row ) {
3838 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3839 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3846 * Get a tree of parent categories
3848 * @param array $children Array with the children in the keys, to check for circular refs
3849 * @return array Tree of parent categories
3851 public function getParentCategoryTree( $children = [] ) {
3853 $parents = $this->getParentCategories();
3856 foreach ( $parents as $parent => $current ) {
3857 if ( array_key_exists( $parent, $children ) ) {
3858 # Circular reference
3859 $stack[$parent] = [];
3861 $nt = Title
::newFromText( $parent );
3863 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3873 * Get an associative array for selecting this title from
3876 * @return array Array suitable for the $where parameter of DB::select()
3878 public function pageCond() {
3879 if ( $this->mArticleID
> 0 ) {
3880 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3881 return [ 'page_id' => $this->mArticleID
];
3883 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3888 * Get the revision ID of the previous revision
3890 * @param int $revId Revision ID. Get the revision that was before this one.
3891 * @param int $flags Title::GAID_FOR_UPDATE
3892 * @return int|bool Old revision ID, or false if none exists
3894 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3895 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3896 $revId = $db->selectField( 'revision', 'rev_id',
3898 'rev_page' => $this->getArticleID( $flags ),
3899 'rev_id < ' . intval( $revId )
3902 [ 'ORDER BY' => 'rev_id DESC' ]
3905 if ( $revId === false ) {
3908 return intval( $revId );
3913 * Get the revision ID of the next revision
3915 * @param int $revId Revision ID. Get the revision that was after this one.
3916 * @param int $flags Title::GAID_FOR_UPDATE
3917 * @return int|bool Next revision ID, or false if none exists
3919 public function getNextRevisionID( $revId, $flags = 0 ) {
3920 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3921 $revId = $db->selectField( 'revision', 'rev_id',
3923 'rev_page' => $this->getArticleID( $flags ),
3924 'rev_id > ' . intval( $revId )
3927 [ 'ORDER BY' => 'rev_id' ]
3930 if ( $revId === false ) {
3933 return intval( $revId );
3938 * Get the first revision of the page
3940 * @param int $flags Title::GAID_FOR_UPDATE
3941 * @return Revision|null If page doesn't exist
3943 public function getFirstRevision( $flags = 0 ) {
3944 $pageId = $this->getArticleID( $flags );
3946 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3947 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3948 [ 'rev_page' => $pageId ],
3950 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
3953 return new Revision( $row );
3960 * Get the oldest revision timestamp of this page
3962 * @param int $flags Title::GAID_FOR_UPDATE
3963 * @return string MW timestamp
3965 public function getEarliestRevTime( $flags = 0 ) {
3966 $rev = $this->getFirstRevision( $flags );
3967 return $rev ?
$rev->getTimestamp() : null;
3971 * Check if this is a new page
3975 public function isNewPage() {
3976 $dbr = wfGetDB( DB_SLAVE
);
3977 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3981 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3985 public function isBigDeletion() {
3986 global $wgDeleteRevisionsLimit;
3988 if ( !$wgDeleteRevisionsLimit ) {
3992 if ( $this->mIsBigDeletion
=== null ) {
3993 $dbr = wfGetDB( DB_SLAVE
);
3995 $revCount = $dbr->selectRowCount(
3998 [ 'rev_page' => $this->getArticleID() ],
4000 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4003 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4006 return $this->mIsBigDeletion
;
4010 * Get the approximate revision count of this page.
4014 public function estimateRevisionCount() {
4015 if ( !$this->exists() ) {
4019 if ( $this->mEstimateRevisions
=== null ) {
4020 $dbr = wfGetDB( DB_SLAVE
);
4021 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4022 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4025 return $this->mEstimateRevisions
;
4029 * Get the number of revisions between the given revision.
4030 * Used for diffs and other things that really need it.
4032 * @param int|Revision $old Old revision or rev ID (first before range)
4033 * @param int|Revision $new New revision or rev ID (first after range)
4034 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4035 * @return int Number of revisions between these revisions.
4037 public function countRevisionsBetween( $old, $new, $max = null ) {
4038 if ( !( $old instanceof Revision
) ) {
4039 $old = Revision
::newFromTitle( $this, (int)$old );
4041 if ( !( $new instanceof Revision
) ) {
4042 $new = Revision
::newFromTitle( $this, (int)$new );
4044 if ( !$old ||
!$new ) {
4045 return 0; // nothing to compare
4047 $dbr = wfGetDB( DB_SLAVE
);
4049 'rev_page' => $this->getArticleID(),
4050 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4051 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4053 if ( $max !== null ) {
4054 return $dbr->selectRowCount( 'revision', '1',
4057 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4060 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4065 * Get the authors between the given revisions or revision IDs.
4066 * Used for diffs and other things that really need it.
4070 * @param int|Revision $old Old revision or rev ID (first before range by default)
4071 * @param int|Revision $new New revision or rev ID (first after range by default)
4072 * @param int $limit Maximum number of authors
4073 * @param string|array $options (Optional): Single option, or an array of options:
4074 * 'include_old' Include $old in the range; $new is excluded.
4075 * 'include_new' Include $new in the range; $old is excluded.
4076 * 'include_both' Include both $old and $new in the range.
4077 * Unknown option values are ignored.
4078 * @return array|null Names of revision authors in the range; null if not both revisions exist
4080 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4081 if ( !( $old instanceof Revision
) ) {
4082 $old = Revision
::newFromTitle( $this, (int)$old );
4084 if ( !( $new instanceof Revision
) ) {
4085 $new = Revision
::newFromTitle( $this, (int)$new );
4087 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4088 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4089 // in the sanity check below?
4090 if ( !$old ||
!$new ) {
4091 return null; // nothing to compare
4096 $options = (array)$options;
4097 if ( in_array( 'include_old', $options ) ) {
4100 if ( in_array( 'include_new', $options ) ) {
4103 if ( in_array( 'include_both', $options ) ) {
4107 // No DB query needed if $old and $new are the same or successive revisions:
4108 if ( $old->getId() === $new->getId() ) {
4109 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4111 [ $old->getUserText( Revision
::RAW
) ];
4112 } elseif ( $old->getId() === $new->getParentId() ) {
4113 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4114 $authors[] = $old->getUserText( Revision
::RAW
);
4115 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4116 $authors[] = $new->getUserText( Revision
::RAW
);
4118 } elseif ( $old_cmp === '>=' ) {
4119 $authors[] = $old->getUserText( Revision
::RAW
);
4120 } elseif ( $new_cmp === '<=' ) {
4121 $authors[] = $new->getUserText( Revision
::RAW
);
4125 $dbr = wfGetDB( DB_SLAVE
);
4126 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4128 'rev_page' => $this->getArticleID(),
4129 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4130 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4132 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4134 foreach ( $res as $row ) {
4135 $authors[] = $row->rev_user_text
;
4141 * Get the number of authors between the given revisions or revision IDs.
4142 * Used for diffs and other things that really need it.
4144 * @param int|Revision $old Old revision or rev ID (first before range by default)
4145 * @param int|Revision $new New revision or rev ID (first after range by default)
4146 * @param int $limit Maximum number of authors
4147 * @param string|array $options (Optional): Single option, or an array of options:
4148 * 'include_old' Include $old in the range; $new is excluded.
4149 * 'include_new' Include $new in the range; $old is excluded.
4150 * 'include_both' Include both $old and $new in the range.
4151 * Unknown option values are ignored.
4152 * @return int Number of revision authors in the range; zero if not both revisions exist
4154 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4155 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4156 return $authors ?
count( $authors ) : 0;
4160 * Compare with another title.
4162 * @param Title $title
4165 public function equals( Title
$title ) {
4166 // Note: === is necessary for proper matching of number-like titles.
4167 return $this->getInterwiki() === $title->getInterwiki()
4168 && $this->getNamespace() == $title->getNamespace()
4169 && $this->getDBkey() === $title->getDBkey();
4173 * Check if this title is a subpage of another title
4175 * @param Title $title
4178 public function isSubpageOf( Title
$title ) {
4179 return $this->getInterwiki() === $title->getInterwiki()
4180 && $this->getNamespace() == $title->getNamespace()
4181 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4185 * Check if page exists. For historical reasons, this function simply
4186 * checks for the existence of the title in the page table, and will
4187 * thus return false for interwiki links, special pages and the like.
4188 * If you want to know if a title can be meaningfully viewed, you should
4189 * probably call the isKnown() method instead.
4191 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4192 * from master/for update
4195 public function exists( $flags = 0 ) {
4196 $exists = $this->getArticleID( $flags ) != 0;
4197 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4202 * Should links to this title be shown as potentially viewable (i.e. as
4203 * "bluelinks"), even if there's no record by this title in the page
4206 * This function is semi-deprecated for public use, as well as somewhat
4207 * misleadingly named. You probably just want to call isKnown(), which
4208 * calls this function internally.
4210 * (ISSUE: Most of these checks are cheap, but the file existence check
4211 * can potentially be quite expensive. Including it here fixes a lot of
4212 * existing code, but we might want to add an optional parameter to skip
4213 * it and any other expensive checks.)
4217 public function isAlwaysKnown() {
4221 * Allows overriding default behavior for determining if a page exists.
4222 * If $isKnown is kept as null, regular checks happen. If it's
4223 * a boolean, this value is returned by the isKnown method.
4227 * @param Title $title
4228 * @param bool|null $isKnown
4230 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4232 if ( !is_null( $isKnown ) ) {
4236 if ( $this->isExternal() ) {
4237 return true; // any interwiki link might be viewable, for all we know
4240 switch ( $this->mNamespace
) {
4243 // file exists, possibly in a foreign repo
4244 return (bool)wfFindFile( $this );
4246 // valid special page
4247 return SpecialPageFactory
::exists( $this->getDBkey() );
4249 // selflink, possibly with fragment
4250 return $this->mDbkeyform
== '';
4252 // known system message
4253 return $this->hasSourceText() !== false;
4260 * Does this title refer to a page that can (or might) be meaningfully
4261 * viewed? In particular, this function may be used to determine if
4262 * links to the title should be rendered as "bluelinks" (as opposed to
4263 * "redlinks" to non-existent pages).
4264 * Adding something else to this function will cause inconsistency
4265 * since LinkHolderArray calls isAlwaysKnown() and does its own
4266 * page existence check.
4270 public function isKnown() {
4271 return $this->isAlwaysKnown() ||
$this->exists();
4275 * Does this page have source text?
4279 public function hasSourceText() {
4280 if ( $this->exists() ) {
4284 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4285 // If the page doesn't exist but is a known system message, default
4286 // message content will be displayed, same for language subpages-
4287 // Use always content language to avoid loading hundreds of languages
4288 // to get the link color.
4290 list( $name, ) = MessageCache
::singleton()->figureMessage(
4291 $wgContLang->lcfirst( $this->getText() )
4293 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4294 return $message->exists();
4301 * Get the default message text or false if the message doesn't exist
4303 * @return string|bool
4305 public function getDefaultMessageText() {
4308 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4312 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4313 $wgContLang->lcfirst( $this->getText() )
4315 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4317 if ( $message->exists() ) {
4318 return $message->plain();
4325 * Updates page_touched for this page; called from LinksUpdate.php
4327 * @param string $purgeTime [optional] TS_MW timestamp
4328 * @return bool True if the update succeeded
4330 public function invalidateCache( $purgeTime = null ) {
4331 if ( wfReadOnly() ) {
4335 if ( $this->mArticleID
=== 0 ) {
4336 return true; // avoid gap locking if we know it's not there
4339 $method = __METHOD__
;
4340 $dbw = wfGetDB( DB_MASTER
);
4341 $conds = $this->pageCond();
4342 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method, $purgeTime ) {
4343 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4347 [ 'page_touched' => $dbTimestamp ],
4348 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4357 * Update page_touched timestamps and send CDN purge messages for
4358 * pages linking to this title. May be sent to the job queue depending
4359 * on the number of links. Typically called on create and delete.
4361 public function touchLinks() {
4362 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4363 if ( $this->getNamespace() == NS_CATEGORY
) {
4364 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4369 * Get the last touched timestamp
4371 * @param IDatabase $db Optional db
4372 * @return string Last-touched timestamp
4374 public function getTouched( $db = null ) {
4375 if ( $db === null ) {
4376 $db = wfGetDB( DB_SLAVE
);
4378 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4383 * Get the timestamp when this page was updated since the user last saw it.
4386 * @return string|null
4388 public function getNotificationTimestamp( $user = null ) {
4391 // Assume current user if none given
4395 // Check cache first
4396 $uid = $user->getId();
4400 // avoid isset here, as it'll return false for null entries
4401 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4402 return $this->mNotificationTimestamp
[$uid];
4404 // Don't cache too much!
4405 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4406 $this->mNotificationTimestamp
= [];
4409 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4410 $watchedItem = $store->getWatchedItem( $user, $this );
4411 if ( $watchedItem ) {
4412 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4414 $this->mNotificationTimestamp
[$uid] = false;
4417 return $this->mNotificationTimestamp
[$uid];
4421 * Generate strings used for xml 'id' names in monobook tabs
4423 * @param string $prepend Defaults to 'nstab-'
4424 * @return string XML 'id' name
4426 public function getNamespaceKey( $prepend = 'nstab-' ) {
4428 // Gets the subject namespace if this title
4429 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4430 // Checks if canonical namespace name exists for namespace
4431 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4432 // Uses canonical namespace name
4433 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4435 // Uses text of namespace
4436 $namespaceKey = $this->getSubjectNsText();
4438 // Makes namespace key lowercase
4439 $namespaceKey = $wgContLang->lc( $namespaceKey );
4441 if ( $namespaceKey == '' ) {
4442 $namespaceKey = 'main';
4444 // Changes file to image for backwards compatibility
4445 if ( $namespaceKey == 'file' ) {
4446 $namespaceKey = 'image';
4448 return $prepend . $namespaceKey;
4452 * Get all extant redirects to this Title
4454 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4455 * @return Title[] Array of Title redirects to this title
4457 public function getRedirectsHere( $ns = null ) {
4460 $dbr = wfGetDB( DB_SLAVE
);
4462 'rd_namespace' => $this->getNamespace(),
4463 'rd_title' => $this->getDBkey(),
4466 if ( $this->isExternal() ) {
4467 $where['rd_interwiki'] = $this->getInterwiki();
4469 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4471 if ( !is_null( $ns ) ) {
4472 $where['page_namespace'] = $ns;
4475 $res = $dbr->select(
4476 [ 'redirect', 'page' ],
4477 [ 'page_namespace', 'page_title' ],
4482 foreach ( $res as $row ) {
4483 $redirs[] = self
::newFromRow( $row );
4489 * Check if this Title is a valid redirect target
4493 public function isValidRedirectTarget() {
4494 global $wgInvalidRedirectTargets;
4496 if ( $this->isSpecialPage() ) {
4497 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4498 if ( $this->isSpecial( 'Userlogout' ) ) {
4502 foreach ( $wgInvalidRedirectTargets as $target ) {
4503 if ( $this->isSpecial( $target ) ) {
4513 * Get a backlink cache object
4515 * @return BacklinkCache
4517 public function getBacklinkCache() {
4518 return BacklinkCache
::get( $this );
4522 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4526 public function canUseNoindex() {
4527 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4529 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4530 ?
$wgContentNamespaces
4531 : $wgExemptFromUserRobotsControl;
4533 return !in_array( $this->mNamespace
, $bannedNamespaces );
4538 * Returns the raw sort key to be used for categories, with the specified
4539 * prefix. This will be fed to Collation::getSortKey() to get a
4540 * binary sortkey that can be used for actual sorting.
4542 * @param string $prefix The prefix to be used, specified using
4543 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4547 public function getCategorySortkey( $prefix = '' ) {
4548 $unprefixed = $this->getText();
4550 // Anything that uses this hook should only depend
4551 // on the Title object passed in, and should probably
4552 // tell the users to run updateCollations.php --force
4553 // in order to re-sort existing category relations.
4554 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4555 if ( $prefix !== '' ) {
4556 # Separate with a line feed, so the unprefixed part is only used as
4557 # a tiebreaker when two pages have the exact same prefix.
4558 # In UCA, tab is the only character that can sort above LF
4559 # so we strip both of them from the original prefix.
4560 $prefix = strtr( $prefix, "\n\t", ' ' );
4561 return "$prefix\n$unprefixed";
4567 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4568 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4569 * the db, it will return NULL.
4571 * @return string|null|bool
4573 private function getDbPageLanguageCode() {
4574 global $wgPageLanguageUseDB;
4576 // check, if the page language could be saved in the database, and if so and
4577 // the value is not requested already, lookup the page language using LinkCache
4578 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4579 $linkCache = LinkCache
::singleton();
4580 $linkCache->addLinkObj( $this );
4581 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4584 return $this->mDbPageLanguage
;
4588 * Get the language in which the content of this page is written in
4589 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4590 * e.g. $wgLang (such as special pages, which are in the user language).
4595 public function getPageLanguage() {
4596 global $wgLang, $wgLanguageCode;
4597 if ( $this->isSpecialPage() ) {
4598 // special pages are in the user language
4602 // Checking if DB language is set
4603 $dbPageLanguage = $this->getDbPageLanguageCode();
4604 if ( $dbPageLanguage ) {
4605 return wfGetLangObj( $dbPageLanguage );
4608 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4609 // Note that this may depend on user settings, so the cache should
4610 // be only per-request.
4611 // NOTE: ContentHandler::getPageLanguage() may need to load the
4612 // content to determine the page language!
4613 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4615 $contentHandler = ContentHandler
::getForTitle( $this );
4616 $langObj = $contentHandler->getPageLanguage( $this );
4617 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4619 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4626 * Get the language in which the content of this page is written when
4627 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4628 * e.g. $wgLang (such as special pages, which are in the user language).
4633 public function getPageViewLanguage() {
4636 if ( $this->isSpecialPage() ) {
4637 // If the user chooses a variant, the content is actually
4638 // in a language whose code is the variant code.
4639 $variant = $wgLang->getPreferredVariant();
4640 if ( $wgLang->getCode() !== $variant ) {
4641 return Language
::factory( $variant );
4647 // Checking if DB language is set
4648 $dbPageLanguage = $this->getDbPageLanguageCode();
4649 if ( $dbPageLanguage ) {
4650 $pageLang = wfGetLangObj( $dbPageLanguage );
4651 $variant = $pageLang->getPreferredVariant();
4652 if ( $pageLang->getCode() !== $variant ) {
4653 $pageLang = Language
::factory( $variant );
4659 // @note Can't be cached persistently, depends on user settings.
4660 // @note ContentHandler::getPageViewLanguage() may need to load the
4661 // content to determine the page language!
4662 $contentHandler = ContentHandler
::getForTitle( $this );
4663 $pageLang = $contentHandler->getPageViewLanguage( $this );
4668 * Get a list of rendered edit notices for this page.
4670 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4671 * they will already be wrapped in paragraphs.
4674 * @param int $oldid Revision ID that's being edited
4677 public function getEditNotices( $oldid = 0 ) {
4680 // Optional notice for the entire namespace
4681 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4682 $msg = wfMessage( $editnotice_ns );
4683 if ( $msg->exists() ) {
4684 $html = $msg->parseAsBlock();
4685 // Edit notices may have complex logic, but output nothing (T91715)
4686 if ( trim( $html ) !== '' ) {
4687 $notices[$editnotice_ns] = Html
::rawElement(
4691 'mw-editnotice-namespace',
4692 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4699 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4700 // Optional notice for page itself and any parent page
4701 $parts = explode( '/', $this->getDBkey() );
4702 $editnotice_base = $editnotice_ns;
4703 while ( count( $parts ) > 0 ) {
4704 $editnotice_base .= '-' . array_shift( $parts );
4705 $msg = wfMessage( $editnotice_base );
4706 if ( $msg->exists() ) {
4707 $html = $msg->parseAsBlock();
4708 if ( trim( $html ) !== '' ) {
4709 $notices[$editnotice_base] = Html
::rawElement(
4713 'mw-editnotice-base',
4714 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4722 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4723 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4724 $msg = wfMessage( $editnoticeText );
4725 if ( $msg->exists() ) {
4726 $html = $msg->parseAsBlock();
4727 if ( trim( $html ) !== '' ) {
4728 $notices[$editnoticeText] = Html
::rawElement(
4732 'mw-editnotice-page',
4733 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4741 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4748 public function __sleep() {
4756 'mDefaultNamespace',
4760 public function __wakeup() {
4761 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4762 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4763 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );