Remove wf* function usage from FSFileBackend
[mediawiki.git] / includes / Title.php
blob5e1e8c61156ab55041c88f5833b18575eb06ed9b
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
5 * See title.txt
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
22 * @file
24 use MediaWiki\Linker\LinkTarget;
25 use MediaWiki\Interwiki\InterwikiLookup;
26 use MediaWiki\MediaWikiServices;
28 /**
29 * Represents a title within MediaWiki.
30 * Optionally may contain an interwiki designation or namespace.
31 * @note This class can fetch various kinds of data from the database;
32 * however, it does so inefficiently.
33 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
34 * and does not rely on global state or the database.
36 class Title implements LinkTarget {
37 /** @var HashBagOStuff */
38 static private $titleCache = null;
40 /**
41 * Title::newFromText maintains a cache to avoid expensive re-normalization of
42 * commonly used titles. On a batch operation this can become a memory leak
43 * if not bounded. After hitting this many titles reset the cache.
45 const CACHE_MAX = 1000;
47 /**
48 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
49 * to use the master DB
51 const GAID_FOR_UPDATE = 1;
53 /**
54 * @name Private member variables
55 * Please use the accessor functions instead.
56 * @private
58 // @{
60 /** @var string Text form (spaces not underscores) of the main part */
61 public $mTextform = '';
63 /** @var string URL-encoded form of the main part */
64 public $mUrlform = '';
66 /** @var string Main part with underscores */
67 public $mDbkeyform = '';
69 /** @var string Database key with the initial letter in the case specified by the user */
70 protected $mUserCaseDBKey;
72 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
73 public $mNamespace = NS_MAIN;
75 /** @var string Interwiki prefix */
76 public $mInterwiki = '';
78 /** @var bool Was this Title created from a string with a local interwiki prefix? */
79 private $mLocalInterwiki = false;
81 /** @var string Title fragment (i.e. the bit after the #) */
82 public $mFragment = '';
84 /** @var int Article ID, fetched from the link cache on demand */
85 public $mArticleID = -1;
87 /** @var bool|int ID of most recent revision */
88 protected $mLatestID = false;
90 /**
91 * @var bool|string ID of the page's content model, i.e. one of the
92 * CONTENT_MODEL_XXX constants
94 private $mContentModel = false;
96 /**
97 * @var bool If a content model was forced via setContentModel()
98 * this will be true to avoid having other code paths reset it
100 private $mForcedContentModel = false;
102 /** @var int Estimated number of revisions; null of not loaded */
103 private $mEstimateRevisions;
105 /** @var array Array of groups allowed to edit this article */
106 public $mRestrictions = [];
108 /** @var string|bool */
109 protected $mOldRestrictions = false;
111 /** @var bool Cascade restrictions on this page to included templates and images? */
112 public $mCascadeRestriction;
114 /** Caching the results of getCascadeProtectionSources */
115 public $mCascadingRestrictions;
117 /** @var array When do the restrictions on this page expire? */
118 protected $mRestrictionsExpiry = [];
120 /** @var bool Are cascading restrictions in effect on this page? */
121 protected $mHasCascadingRestrictions;
123 /** @var array Where are the cascading restrictions coming from on this page? */
124 public $mCascadeSources;
126 /** @var bool Boolean for initialisation on demand */
127 public $mRestrictionsLoaded = false;
129 /** @var string Text form including namespace/interwiki, initialised on demand */
130 protected $mPrefixedText = null;
132 /** @var mixed Cached value for getTitleProtection (create protection) */
133 public $mTitleProtection;
136 * @var int Namespace index when there is no namespace. Don't change the
137 * following default, NS_MAIN is hardcoded in several places. See bug 696.
138 * Zero except in {{transclusion}} tags.
140 public $mDefaultNamespace = NS_MAIN;
142 /** @var int The page length, 0 for special pages */
143 protected $mLength = -1;
145 /** @var null Is the article at this title a redirect? */
146 public $mRedirect = null;
148 /** @var array Associative array of user ID -> timestamp/false */
149 private $mNotificationTimestamp = [];
151 /** @var bool Whether a page has any subpages */
152 private $mHasSubpages;
154 /** @var bool The (string) language code of the page's language and content code. */
155 private $mPageLanguage = false;
157 /** @var string|bool|null The page language code from the database, null if not saved in
158 * the database or false if not loaded, yet. */
159 private $mDbPageLanguage = false;
161 /** @var TitleValue A corresponding TitleValue object */
162 private $mTitleValue = null;
164 /** @var bool Would deleting this page be a big deletion? */
165 private $mIsBigDeletion = null;
166 // @}
169 * B/C kludge: provide a TitleParser for use by Title.
170 * Ideally, Title would have no methods that need this.
171 * Avoid usage of this singleton by using TitleValue
172 * and the associated services when possible.
174 * @return TitleFormatter
176 private static function getTitleFormatter() {
177 return MediaWikiServices::getInstance()->getTitleFormatter();
181 * B/C kludge: provide an InterwikiLookup for use by Title.
182 * Ideally, Title would have no methods that need this.
183 * Avoid usage of this singleton by using TitleValue
184 * and the associated services when possible.
186 * @return InterwikiLookup
188 private static function getInterwikiLookup() {
189 return MediaWikiServices::getInstance()->getInterwikiLookup();
193 * @access protected
195 function __construct() {
199 * Create a new Title from a prefixed DB key
201 * @param string $key The database key, which has underscores
202 * instead of spaces, possibly including namespace and
203 * interwiki prefixes
204 * @return Title|null Title, or null on an error
206 public static function newFromDBkey( $key ) {
207 $t = new Title();
208 $t->mDbkeyform = $key;
210 try {
211 $t->secureAndSplit();
212 return $t;
213 } catch ( MalformedTitleException $ex ) {
214 return null;
219 * Create a new Title from a TitleValue
221 * @param TitleValue $titleValue Assumed to be safe.
223 * @return Title
225 public static function newFromTitleValue( TitleValue $titleValue ) {
226 return self::newFromLinkTarget( $titleValue );
230 * Create a new Title from a LinkTarget
232 * @param LinkTarget $linkTarget Assumed to be safe.
234 * @return Title
236 public static function newFromLinkTarget( LinkTarget $linkTarget ) {
237 if ( $linkTarget instanceof Title ) {
238 // Special case if it's already a Title object
239 return $linkTarget;
241 return self::makeTitle(
242 $linkTarget->getNamespace(),
243 $linkTarget->getText(),
244 $linkTarget->getFragment(),
245 $linkTarget->getInterwiki()
250 * Create a new Title from text, such as what one would find in a link. De-
251 * codes any HTML entities in the text.
253 * @param string|int|null $text The link text; spaces, prefixes, and an
254 * initial ':' indicating the main namespace are accepted.
255 * @param int $defaultNamespace The namespace to use if none is specified
256 * by a prefix. If you want to force a specific namespace even if
257 * $text might begin with a namespace prefix, use makeTitle() or
258 * makeTitleSafe().
259 * @throws InvalidArgumentException
260 * @return Title|null Title or null on an error.
262 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
263 // DWIM: Integers can be passed in here when page titles are used as array keys.
264 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
265 throw new InvalidArgumentException( '$text must be a string.' );
267 if ( $text === null ) {
268 return null;
271 try {
272 return Title::newFromTextThrow( strval( $text ), $defaultNamespace );
273 } catch ( MalformedTitleException $ex ) {
274 return null;
279 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
280 * rather than returning null.
282 * The exception subclasses encode detailed information about why the title is invalid.
284 * @see Title::newFromText
286 * @since 1.25
287 * @param string $text Title text to check
288 * @param int $defaultNamespace
289 * @throws MalformedTitleException If the title is invalid
290 * @return Title
292 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN ) {
293 if ( is_object( $text ) ) {
294 throw new MWException( '$text must be a string, given an object' );
297 $titleCache = self::getTitleCache();
299 // Wiki pages often contain multiple links to the same page.
300 // Title normalization and parsing can become expensive on pages with many
301 // links, so we can save a little time by caching them.
302 // In theory these are value objects and won't get changed...
303 if ( $defaultNamespace == NS_MAIN ) {
304 $t = $titleCache->get( $text );
305 if ( $t ) {
306 return $t;
310 // Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
311 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
313 $t = new Title();
314 $t->mDbkeyform = strtr( $filteredText, ' ', '_' );
315 $t->mDefaultNamespace = intval( $defaultNamespace );
317 $t->secureAndSplit();
318 if ( $defaultNamespace == NS_MAIN ) {
319 $titleCache->set( $text, $t );
321 return $t;
325 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
327 * Example of wrong and broken code:
328 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
330 * Example of right code:
331 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
333 * Create a new Title from URL-encoded text. Ensures that
334 * the given title's length does not exceed the maximum.
336 * @param string $url The title, as might be taken from a URL
337 * @return Title|null The new object, or null on an error
339 public static function newFromURL( $url ) {
340 $t = new Title();
342 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
343 # but some URLs used it as a space replacement and they still come
344 # from some external search tools.
345 if ( strpos( self::legalChars(), '+' ) === false ) {
346 $url = strtr( $url, '+', ' ' );
349 $t->mDbkeyform = strtr( $url, ' ', '_' );
351 try {
352 $t->secureAndSplit();
353 return $t;
354 } catch ( MalformedTitleException $ex ) {
355 return null;
360 * @return HashBagOStuff
362 private static function getTitleCache() {
363 if ( self::$titleCache == null ) {
364 self::$titleCache = new HashBagOStuff( [ 'maxKeys' => self::CACHE_MAX ] );
366 return self::$titleCache;
370 * Returns a list of fields that are to be selected for initializing Title
371 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
372 * whether to include page_content_model.
374 * @return array
376 protected static function getSelectFields() {
377 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
379 $fields = [
380 'page_namespace', 'page_title', 'page_id',
381 'page_len', 'page_is_redirect', 'page_latest',
384 if ( $wgContentHandlerUseDB ) {
385 $fields[] = 'page_content_model';
388 if ( $wgPageLanguageUseDB ) {
389 $fields[] = 'page_lang';
392 return $fields;
396 * Create a new Title from an article ID
398 * @param int $id The page_id corresponding to the Title to create
399 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
400 * @return Title|null The new object, or null on an error
402 public static function newFromID( $id, $flags = 0 ) {
403 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
404 $row = $db->selectRow(
405 'page',
406 self::getSelectFields(),
407 [ 'page_id' => $id ],
408 __METHOD__
410 if ( $row !== false ) {
411 $title = Title::newFromRow( $row );
412 } else {
413 $title = null;
415 return $title;
419 * Make an array of titles from an array of IDs
421 * @param int[] $ids Array of IDs
422 * @return Title[] Array of Titles
424 public static function newFromIDs( $ids ) {
425 if ( !count( $ids ) ) {
426 return [];
428 $dbr = wfGetDB( DB_REPLICA );
430 $res = $dbr->select(
431 'page',
432 self::getSelectFields(),
433 [ 'page_id' => $ids ],
434 __METHOD__
437 $titles = [];
438 foreach ( $res as $row ) {
439 $titles[] = Title::newFromRow( $row );
441 return $titles;
445 * Make a Title object from a DB row
447 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
448 * @return Title Corresponding Title
450 public static function newFromRow( $row ) {
451 $t = self::makeTitle( $row->page_namespace, $row->page_title );
452 $t->loadFromRow( $row );
453 return $t;
457 * Load Title object fields from a DB row.
458 * If false is given, the title will be treated as non-existing.
460 * @param stdClass|bool $row Database row
462 public function loadFromRow( $row ) {
463 if ( $row ) { // page found
464 if ( isset( $row->page_id ) ) {
465 $this->mArticleID = (int)$row->page_id;
467 if ( isset( $row->page_len ) ) {
468 $this->mLength = (int)$row->page_len;
470 if ( isset( $row->page_is_redirect ) ) {
471 $this->mRedirect = (bool)$row->page_is_redirect;
473 if ( isset( $row->page_latest ) ) {
474 $this->mLatestID = (int)$row->page_latest;
476 if ( !$this->mForcedContentModel && isset( $row->page_content_model ) ) {
477 $this->mContentModel = strval( $row->page_content_model );
478 } elseif ( !$this->mForcedContentModel ) {
479 $this->mContentModel = false; # initialized lazily in getContentModel()
481 if ( isset( $row->page_lang ) ) {
482 $this->mDbPageLanguage = (string)$row->page_lang;
484 if ( isset( $row->page_restrictions ) ) {
485 $this->mOldRestrictions = $row->page_restrictions;
487 } else { // page not found
488 $this->mArticleID = 0;
489 $this->mLength = 0;
490 $this->mRedirect = false;
491 $this->mLatestID = 0;
492 if ( !$this->mForcedContentModel ) {
493 $this->mContentModel = false; # initialized lazily in getContentModel()
499 * Create a new Title from a namespace index and a DB key.
500 * It's assumed that $ns and $title are *valid*, for instance when
501 * they came directly from the database or a special page name.
502 * For convenience, spaces are converted to underscores so that
503 * eg user_text fields can be used directly.
505 * @param int $ns The namespace of the article
506 * @param string $title The unprefixed database key form
507 * @param string $fragment The link fragment (after the "#")
508 * @param string $interwiki The interwiki prefix
509 * @return Title The new object
511 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
512 $t = new Title();
513 $t->mInterwiki = $interwiki;
514 $t->mFragment = $fragment;
515 $t->mNamespace = $ns = intval( $ns );
516 $t->mDbkeyform = strtr( $title, ' ', '_' );
517 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
518 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
519 $t->mTextform = strtr( $title, '_', ' ' );
520 $t->mContentModel = false; # initialized lazily in getContentModel()
521 return $t;
525 * Create a new Title from a namespace index and a DB key.
526 * The parameters will be checked for validity, which is a bit slower
527 * than makeTitle() but safer for user-provided data.
529 * @param int $ns The namespace of the article
530 * @param string $title Database key form
531 * @param string $fragment The link fragment (after the "#")
532 * @param string $interwiki Interwiki prefix
533 * @return Title|null The new object, or null on an error
535 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
536 if ( !MWNamespace::exists( $ns ) ) {
537 return null;
540 $t = new Title();
541 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki, true );
543 try {
544 $t->secureAndSplit();
545 return $t;
546 } catch ( MalformedTitleException $ex ) {
547 return null;
552 * Create a new Title for the Main Page
554 * @return Title The new object
556 public static function newMainPage() {
557 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
558 // Don't give fatal errors if the message is broken
559 if ( !$title ) {
560 $title = Title::newFromText( 'Main Page' );
562 return $title;
566 * Get the prefixed DB key associated with an ID
568 * @param int $id The page_id of the article
569 * @return Title|null An object representing the article, or null if no such article was found
571 public static function nameOf( $id ) {
572 $dbr = wfGetDB( DB_REPLICA );
574 $s = $dbr->selectRow(
575 'page',
576 [ 'page_namespace', 'page_title' ],
577 [ 'page_id' => $id ],
578 __METHOD__
580 if ( $s === false ) {
581 return null;
584 $n = self::makeName( $s->page_namespace, $s->page_title );
585 return $n;
589 * Get a regex character class describing the legal characters in a link
591 * @return string The list of characters, not delimited
593 public static function legalChars() {
594 global $wgLegalTitleChars;
595 return $wgLegalTitleChars;
599 * Returns a simple regex that will match on characters and sequences invalid in titles.
600 * Note that this doesn't pick up many things that could be wrong with titles, but that
601 * replacing this regex with something valid will make many titles valid.
603 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
605 * @return string Regex string
607 static function getTitleInvalidRegex() {
608 wfDeprecated( __METHOD__, '1.25' );
609 return MediaWikiTitleCodec::getTitleInvalidRegex();
613 * Utility method for converting a character sequence from bytes to Unicode.
615 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
616 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
618 * @param string $byteClass
619 * @return string
621 public static function convertByteClassToUnicodeClass( $byteClass ) {
622 $length = strlen( $byteClass );
623 // Input token queue
624 $x0 = $x1 = $x2 = '';
625 // Decoded queue
626 $d0 = $d1 = $d2 = '';
627 // Decoded integer codepoints
628 $ord0 = $ord1 = $ord2 = 0;
629 // Re-encoded queue
630 $r0 = $r1 = $r2 = '';
631 // Output
632 $out = '';
633 // Flags
634 $allowUnicode = false;
635 for ( $pos = 0; $pos < $length; $pos++ ) {
636 // Shift the queues down
637 $x2 = $x1;
638 $x1 = $x0;
639 $d2 = $d1;
640 $d1 = $d0;
641 $ord2 = $ord1;
642 $ord1 = $ord0;
643 $r2 = $r1;
644 $r1 = $r0;
645 // Load the current input token and decoded values
646 $inChar = $byteClass[$pos];
647 if ( $inChar == '\\' ) {
648 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
649 $x0 = $inChar . $m[0];
650 $d0 = chr( hexdec( $m[1] ) );
651 $pos += strlen( $m[0] );
652 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
653 $x0 = $inChar . $m[0];
654 $d0 = chr( octdec( $m[0] ) );
655 $pos += strlen( $m[0] );
656 } elseif ( $pos + 1 >= $length ) {
657 $x0 = $d0 = '\\';
658 } else {
659 $d0 = $byteClass[$pos + 1];
660 $x0 = $inChar . $d0;
661 $pos += 1;
663 } else {
664 $x0 = $d0 = $inChar;
666 $ord0 = ord( $d0 );
667 // Load the current re-encoded value
668 if ( $ord0 < 32 || $ord0 == 0x7f ) {
669 $r0 = sprintf( '\x%02x', $ord0 );
670 } elseif ( $ord0 >= 0x80 ) {
671 // Allow unicode if a single high-bit character appears
672 $r0 = sprintf( '\x%02x', $ord0 );
673 $allowUnicode = true;
674 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
675 $r0 = '\\' . $d0;
676 } else {
677 $r0 = $d0;
679 // Do the output
680 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
681 // Range
682 if ( $ord2 > $ord0 ) {
683 // Empty range
684 } elseif ( $ord0 >= 0x80 ) {
685 // Unicode range
686 $allowUnicode = true;
687 if ( $ord2 < 0x80 ) {
688 // Keep the non-unicode section of the range
689 $out .= "$r2-\\x7F";
691 } else {
692 // Normal range
693 $out .= "$r2-$r0";
695 // Reset state to the initial value
696 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
697 } elseif ( $ord2 < 0x80 ) {
698 // ASCII character
699 $out .= $r2;
702 if ( $ord1 < 0x80 ) {
703 $out .= $r1;
705 if ( $ord0 < 0x80 ) {
706 $out .= $r0;
708 if ( $allowUnicode ) {
709 $out .= '\u0080-\uFFFF';
711 return $out;
715 * Make a prefixed DB key from a DB key and a namespace index
717 * @param int $ns Numerical representation of the namespace
718 * @param string $title The DB key form the title
719 * @param string $fragment The link fragment (after the "#")
720 * @param string $interwiki The interwiki prefix
721 * @param bool $canonicalNamespace If true, use the canonical name for
722 * $ns instead of the localized version.
723 * @return string The prefixed form of the title
725 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
726 $canonicalNamespace = false
728 global $wgContLang;
730 if ( $canonicalNamespace ) {
731 $namespace = MWNamespace::getCanonicalName( $ns );
732 } else {
733 $namespace = $wgContLang->getNsText( $ns );
735 $name = $namespace == '' ? $title : "$namespace:$title";
736 if ( strval( $interwiki ) != '' ) {
737 $name = "$interwiki:$name";
739 if ( strval( $fragment ) != '' ) {
740 $name .= '#' . $fragment;
742 return $name;
746 * Escape a text fragment, say from a link, for a URL
748 * @param string $fragment Containing a URL or link fragment (after the "#")
749 * @return string Escaped string
751 static function escapeFragmentForURL( $fragment ) {
752 # Note that we don't urlencode the fragment. urlencoded Unicode
753 # fragments appear not to work in IE (at least up to 7) or in at least
754 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
755 # to care if they aren't encoded.
756 return Sanitizer::escapeId( $fragment, 'noninitial' );
760 * Callback for usort() to do title sorts by (namespace, title)
762 * @param LinkTarget $a
763 * @param LinkTarget $b
765 * @return int Result of string comparison, or namespace comparison
767 public static function compare( LinkTarget $a, LinkTarget $b ) {
768 if ( $a->getNamespace() == $b->getNamespace() ) {
769 return strcmp( $a->getText(), $b->getText() );
770 } else {
771 return $a->getNamespace() - $b->getNamespace();
776 * Determine whether the object refers to a page within
777 * this project (either this wiki or a wiki with a local
778 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
780 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
782 public function isLocal() {
783 if ( $this->isExternal() ) {
784 $iw = self::getInterwikiLookup()->fetch( $this->mInterwiki );
785 if ( $iw ) {
786 return $iw->isLocal();
789 return true;
793 * Is this Title interwiki?
795 * @return bool
797 public function isExternal() {
798 return $this->mInterwiki !== '';
802 * Get the interwiki prefix
804 * Use Title::isExternal to check if a interwiki is set
806 * @return string Interwiki prefix
808 public function getInterwiki() {
809 return $this->mInterwiki;
813 * Was this a local interwiki link?
815 * @return bool
817 public function wasLocalInterwiki() {
818 return $this->mLocalInterwiki;
822 * Determine whether the object refers to a page within
823 * this project and is transcludable.
825 * @return bool True if this is transcludable
827 public function isTrans() {
828 if ( !$this->isExternal() ) {
829 return false;
832 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->isTranscludable();
836 * Returns the DB name of the distant wiki which owns the object.
838 * @return string The DB name
840 public function getTransWikiID() {
841 if ( !$this->isExternal() ) {
842 return false;
845 return self::getInterwikiLookup()->fetch( $this->mInterwiki )->getWikiID();
849 * Get a TitleValue object representing this Title.
851 * @note Not all valid Titles have a corresponding valid TitleValue
852 * (e.g. TitleValues cannot represent page-local links that have a
853 * fragment but no title text).
855 * @return TitleValue|null
857 public function getTitleValue() {
858 if ( $this->mTitleValue === null ) {
859 try {
860 $this->mTitleValue = new TitleValue(
861 $this->getNamespace(),
862 $this->getDBkey(),
863 $this->getFragment(),
864 $this->getInterwiki()
866 } catch ( InvalidArgumentException $ex ) {
867 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
868 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
872 return $this->mTitleValue;
876 * Get the text form (spaces not underscores) of the main part
878 * @return string Main part of the title
880 public function getText() {
881 return $this->mTextform;
885 * Get the URL-encoded form of the main part
887 * @return string Main part of the title, URL-encoded
889 public function getPartialURL() {
890 return $this->mUrlform;
894 * Get the main part with underscores
896 * @return string Main part of the title, with underscores
898 public function getDBkey() {
899 return $this->mDbkeyform;
903 * Get the DB key with the initial letter case as specified by the user
905 * @return string DB key
907 function getUserCaseDBKey() {
908 if ( !is_null( $this->mUserCaseDBKey ) ) {
909 return $this->mUserCaseDBKey;
910 } else {
911 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
912 return $this->mDbkeyform;
917 * Get the namespace index, i.e. one of the NS_xxxx constants.
919 * @return int Namespace index
921 public function getNamespace() {
922 return $this->mNamespace;
926 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
928 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
929 * @return string Content model id
931 public function getContentModel( $flags = 0 ) {
932 if ( !$this->mForcedContentModel
933 && ( !$this->mContentModel || $flags === Title::GAID_FOR_UPDATE )
934 && $this->getArticleID( $flags )
936 $linkCache = LinkCache::singleton();
937 $linkCache->addLinkObj( $this ); # in case we already had an article ID
938 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
941 if ( !$this->mContentModel ) {
942 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
945 return $this->mContentModel;
949 * Convenience method for checking a title's content model name
951 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
952 * @return bool True if $this->getContentModel() == $id
954 public function hasContentModel( $id ) {
955 return $this->getContentModel() == $id;
959 * Set a proposed content model for the page for permissions
960 * checking. This does not actually change the content model
961 * of a title!
963 * Additionally, you should make sure you've checked
964 * ContentHandler::canBeUsedOn() first.
966 * @since 1.28
967 * @param string $model CONTENT_MODEL_XXX constant
969 public function setContentModel( $model ) {
970 $this->mContentModel = $model;
971 $this->mForcedContentModel = true;
975 * Get the namespace text
977 * @return string Namespace text
979 public function getNsText() {
980 if ( $this->isExternal() ) {
981 // This probably shouldn't even happen,
982 // but for interwiki transclusion it sometimes does.
983 // Use the canonical namespaces if possible to try to
984 // resolve a foreign namespace.
985 if ( MWNamespace::exists( $this->mNamespace ) ) {
986 return MWNamespace::getCanonicalName( $this->mNamespace );
990 try {
991 $formatter = self::getTitleFormatter();
992 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
993 } catch ( InvalidArgumentException $ex ) {
994 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
995 return false;
1000 * Get the namespace text of the subject (rather than talk) page
1002 * @return string Namespace text
1004 public function getSubjectNsText() {
1005 global $wgContLang;
1006 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
1010 * Get the namespace text of the talk page
1012 * @return string Namespace text
1014 public function getTalkNsText() {
1015 global $wgContLang;
1016 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
1020 * Could this title have a corresponding talk page?
1022 * @return bool
1024 public function canTalk() {
1025 return MWNamespace::canTalk( $this->mNamespace );
1029 * Is this in a namespace that allows actual pages?
1031 * @return bool
1033 public function canExist() {
1034 return $this->mNamespace >= NS_MAIN;
1038 * Can this title be added to a user's watchlist?
1040 * @return bool
1042 public function isWatchable() {
1043 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
1047 * Returns true if this is a special page.
1049 * @return bool
1051 public function isSpecialPage() {
1052 return $this->getNamespace() == NS_SPECIAL;
1056 * Returns true if this title resolves to the named special page
1058 * @param string $name The special page name
1059 * @return bool
1061 public function isSpecial( $name ) {
1062 if ( $this->isSpecialPage() ) {
1063 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
1064 if ( $name == $thisName ) {
1065 return true;
1068 return false;
1072 * If the Title refers to a special page alias which is not the local default, resolve
1073 * the alias, and localise the name as necessary. Otherwise, return $this
1075 * @return Title
1077 public function fixSpecialName() {
1078 if ( $this->isSpecialPage() ) {
1079 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
1080 if ( $canonicalName ) {
1081 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1082 if ( $localName != $this->mDbkeyform ) {
1083 return Title::makeTitle( NS_SPECIAL, $localName );
1087 return $this;
1091 * Returns true if the title is inside the specified namespace.
1093 * Please make use of this instead of comparing to getNamespace()
1094 * This function is much more resistant to changes we may make
1095 * to namespaces than code that makes direct comparisons.
1096 * @param int $ns The namespace
1097 * @return bool
1098 * @since 1.19
1100 public function inNamespace( $ns ) {
1101 return MWNamespace::equals( $this->getNamespace(), $ns );
1105 * Returns true if the title is inside one of the specified namespaces.
1107 * @param int|int[] $namespaces,... The namespaces to check for
1108 * @return bool
1109 * @since 1.19
1111 public function inNamespaces( /* ... */ ) {
1112 $namespaces = func_get_args();
1113 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1114 $namespaces = $namespaces[0];
1117 foreach ( $namespaces as $ns ) {
1118 if ( $this->inNamespace( $ns ) ) {
1119 return true;
1123 return false;
1127 * Returns true if the title has the same subject namespace as the
1128 * namespace specified.
1129 * For example this method will take NS_USER and return true if namespace
1130 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1131 * as their subject namespace.
1133 * This is MUCH simpler than individually testing for equivalence
1134 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1135 * @since 1.19
1136 * @param int $ns
1137 * @return bool
1139 public function hasSubjectNamespace( $ns ) {
1140 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1144 * Is this Title in a namespace which contains content?
1145 * In other words, is this a content page, for the purposes of calculating
1146 * statistics, etc?
1148 * @return bool
1150 public function isContentPage() {
1151 return MWNamespace::isContent( $this->getNamespace() );
1155 * Would anybody with sufficient privileges be able to move this page?
1156 * Some pages just aren't movable.
1158 * @return bool
1160 public function isMovable() {
1161 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1162 // Interwiki title or immovable namespace. Hooks don't get to override here
1163 return false;
1166 $result = true;
1167 Hooks::run( 'TitleIsMovable', [ $this, &$result ] );
1168 return $result;
1172 * Is this the mainpage?
1173 * @note Title::newFromText seems to be sufficiently optimized by the title
1174 * cache that we don't need to over-optimize by doing direct comparisons and
1175 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1176 * ends up reporting something differently than $title->isMainPage();
1178 * @since 1.18
1179 * @return bool
1181 public function isMainPage() {
1182 return $this->equals( Title::newMainPage() );
1186 * Is this a subpage?
1188 * @return bool
1190 public function isSubpage() {
1191 return MWNamespace::hasSubpages( $this->mNamespace )
1192 ? strpos( $this->getText(), '/' ) !== false
1193 : false;
1197 * Is this a conversion table for the LanguageConverter?
1199 * @return bool
1201 public function isConversionTable() {
1202 // @todo ConversionTable should become a separate content model.
1204 return $this->getNamespace() == NS_MEDIAWIKI &&
1205 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1209 * Does that page contain wikitext, or it is JS, CSS or whatever?
1211 * @return bool
1213 public function isWikitextPage() {
1214 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1218 * Could this page contain custom CSS or JavaScript for the global UI.
1219 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1220 * or CONTENT_MODEL_JAVASCRIPT.
1222 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1223 * for that!
1225 * Note that this method should not return true for pages that contain and
1226 * show "inactive" CSS or JS.
1228 * @return bool
1229 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1231 public function isCssOrJsPage() {
1232 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1233 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1234 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1236 # @note This hook is also called in ContentHandler::getDefaultModel.
1237 # It's called here again to make sure hook functions can force this
1238 # method to return true even outside the MediaWiki namespace.
1240 Hooks::run( 'TitleIsCssOrJsPage', [ $this, &$isCssOrJsPage ], '1.25' );
1242 return $isCssOrJsPage;
1246 * Is this a .css or .js subpage of a user page?
1247 * @return bool
1248 * @todo FIXME: Rename to isUserConfigPage()
1250 public function isCssJsSubpage() {
1251 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1252 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1253 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1257 * Trim down a .css or .js subpage title to get the corresponding skin name
1259 * @return string Containing skin name from .css or .js subpage title
1261 public function getSkinFromCssJsSubpage() {
1262 $subpage = explode( '/', $this->mTextform );
1263 $subpage = $subpage[count( $subpage ) - 1];
1264 $lastdot = strrpos( $subpage, '.' );
1265 if ( $lastdot === false ) {
1266 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1268 return substr( $subpage, 0, $lastdot );
1272 * Is this a .css subpage of a user page?
1274 * @return bool
1276 public function isCssSubpage() {
1277 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1278 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1282 * Is this a .js subpage of a user page?
1284 * @return bool
1286 public function isJsSubpage() {
1287 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1288 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1292 * Is this a talk page of some sort?
1294 * @return bool
1296 public function isTalkPage() {
1297 return MWNamespace::isTalk( $this->getNamespace() );
1301 * Get a Title object associated with the talk page of this article
1303 * @return Title The object for the talk page
1305 public function getTalkPage() {
1306 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1310 * Get a title object associated with the subject page of this
1311 * talk page
1313 * @return Title The object for the subject page
1315 public function getSubjectPage() {
1316 // Is this the same title?
1317 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1318 if ( $this->getNamespace() == $subjectNS ) {
1319 return $this;
1321 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1325 * Get the other title for this page, if this is a subject page
1326 * get the talk page, if it is a subject page get the talk page
1328 * @since 1.25
1329 * @throws MWException
1330 * @return Title
1332 public function getOtherPage() {
1333 if ( $this->isSpecialPage() ) {
1334 throw new MWException( 'Special pages cannot have other pages' );
1336 if ( $this->isTalkPage() ) {
1337 return $this->getSubjectPage();
1338 } else {
1339 return $this->getTalkPage();
1344 * Get the default namespace index, for when there is no namespace
1346 * @return int Default namespace index
1348 public function getDefaultNamespace() {
1349 return $this->mDefaultNamespace;
1353 * Get the Title fragment (i.e.\ the bit after the #) in text form
1355 * Use Title::hasFragment to check for a fragment
1357 * @return string Title fragment
1359 public function getFragment() {
1360 return $this->mFragment;
1364 * Check if a Title fragment is set
1366 * @return bool
1367 * @since 1.23
1369 public function hasFragment() {
1370 return $this->mFragment !== '';
1374 * Get the fragment in URL form, including the "#" character if there is one
1375 * @return string Fragment in URL form
1377 public function getFragmentForURL() {
1378 if ( !$this->hasFragment() ) {
1379 return '';
1380 } else {
1381 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1386 * Set the fragment for this title. Removes the first character from the
1387 * specified fragment before setting, so it assumes you're passing it with
1388 * an initial "#".
1390 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1391 * or Title::createFragmentTarget().
1392 * Still in active use privately.
1394 * @private
1395 * @param string $fragment Text
1397 public function setFragment( $fragment ) {
1398 $this->mFragment = strtr( substr( $fragment, 1 ), '_', ' ' );
1402 * Creates a new Title for a different fragment of the same page.
1404 * @since 1.27
1405 * @param string $fragment
1406 * @return Title
1408 public function createFragmentTarget( $fragment ) {
1409 return self::makeTitle(
1410 $this->getNamespace(),
1411 $this->getText(),
1412 $fragment,
1413 $this->getInterwiki()
1419 * Prefix some arbitrary text with the namespace or interwiki prefix
1420 * of this object
1422 * @param string $name The text
1423 * @return string The prefixed text
1425 private function prefix( $name ) {
1426 $p = '';
1427 if ( $this->isExternal() ) {
1428 $p = $this->mInterwiki . ':';
1431 if ( 0 != $this->mNamespace ) {
1432 $p .= $this->getNsText() . ':';
1434 return $p . $name;
1438 * Get the prefixed database key form
1440 * @return string The prefixed title, with underscores and
1441 * any interwiki and namespace prefixes
1443 public function getPrefixedDBkey() {
1444 $s = $this->prefix( $this->mDbkeyform );
1445 $s = strtr( $s, ' ', '_' );
1446 return $s;
1450 * Get the prefixed title with spaces.
1451 * This is the form usually used for display
1453 * @return string The prefixed title, with spaces
1455 public function getPrefixedText() {
1456 if ( $this->mPrefixedText === null ) {
1457 $s = $this->prefix( $this->mTextform );
1458 $s = strtr( $s, '_', ' ' );
1459 $this->mPrefixedText = $s;
1461 return $this->mPrefixedText;
1465 * Return a string representation of this title
1467 * @return string Representation of this title
1469 public function __toString() {
1470 return $this->getPrefixedText();
1474 * Get the prefixed title with spaces, plus any fragment
1475 * (part beginning with '#')
1477 * @return string The prefixed title, with spaces and the fragment, including '#'
1479 public function getFullText() {
1480 $text = $this->getPrefixedText();
1481 if ( $this->hasFragment() ) {
1482 $text .= '#' . $this->getFragment();
1484 return $text;
1488 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1490 * @par Example:
1491 * @code
1492 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1493 * # returns: 'Foo'
1494 * @endcode
1496 * @return string Root name
1497 * @since 1.20
1499 public function getRootText() {
1500 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1501 return $this->getText();
1504 return strtok( $this->getText(), '/' );
1508 * Get the root page name title, i.e. the leftmost part before any slashes
1510 * @par Example:
1511 * @code
1512 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1513 * # returns: Title{User:Foo}
1514 * @endcode
1516 * @return Title Root title
1517 * @since 1.20
1519 public function getRootTitle() {
1520 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1524 * Get the base page name without a namespace, i.e. the part before the subpage name
1526 * @par Example:
1527 * @code
1528 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1529 * # returns: 'Foo/Bar'
1530 * @endcode
1532 * @return string Base name
1534 public function getBaseText() {
1535 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1536 return $this->getText();
1539 $parts = explode( '/', $this->getText() );
1540 # Don't discard the real title if there's no subpage involved
1541 if ( count( $parts ) > 1 ) {
1542 unset( $parts[count( $parts ) - 1] );
1544 return implode( '/', $parts );
1548 * Get the base page name title, i.e. the part before the subpage name
1550 * @par Example:
1551 * @code
1552 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1553 * # returns: Title{User:Foo/Bar}
1554 * @endcode
1556 * @return Title Base title
1557 * @since 1.20
1559 public function getBaseTitle() {
1560 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1564 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1566 * @par Example:
1567 * @code
1568 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1569 * # returns: "Baz"
1570 * @endcode
1572 * @return string Subpage name
1574 public function getSubpageText() {
1575 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1576 return $this->mTextform;
1578 $parts = explode( '/', $this->mTextform );
1579 return $parts[count( $parts ) - 1];
1583 * Get the title for a subpage of the current page
1585 * @par Example:
1586 * @code
1587 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1588 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1589 * @endcode
1591 * @param string $text The subpage name to add to the title
1592 * @return Title Subpage title
1593 * @since 1.20
1595 public function getSubpage( $text ) {
1596 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1600 * Get a URL-encoded form of the subpage text
1602 * @return string URL-encoded subpage name
1604 public function getSubpageUrlForm() {
1605 $text = $this->getSubpageText();
1606 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1607 return $text;
1611 * Get a URL-encoded title (not an actual URL) including interwiki
1613 * @return string The URL-encoded form
1615 public function getPrefixedURL() {
1616 $s = $this->prefix( $this->mDbkeyform );
1617 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1618 return $s;
1622 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1623 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1624 * second argument named variant. This was deprecated in favor
1625 * of passing an array of option with a "variant" key
1626 * Once $query2 is removed for good, this helper can be dropped
1627 * and the wfArrayToCgi moved to getLocalURL();
1629 * @since 1.19 (r105919)
1630 * @param array|string $query
1631 * @param bool $query2
1632 * @return string
1634 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1635 if ( $query2 !== false ) {
1636 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1637 "method called with a second parameter is deprecated. Add your " .
1638 "parameter to an array passed as the first parameter.", "1.19" );
1640 if ( is_array( $query ) ) {
1641 $query = wfArrayToCgi( $query );
1643 if ( $query2 ) {
1644 if ( is_string( $query2 ) ) {
1645 // $query2 is a string, we will consider this to be
1646 // a deprecated $variant argument and add it to the query
1647 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1648 } else {
1649 $query2 = wfArrayToCgi( $query2 );
1651 // If we have $query content add a & to it first
1652 if ( $query ) {
1653 $query .= '&';
1655 // Now append the queries together
1656 $query .= $query2;
1658 return $query;
1662 * Get a real URL referring to this title, with interwiki link and
1663 * fragment
1665 * @see self::getLocalURL for the arguments.
1666 * @see wfExpandUrl
1667 * @param array|string $query
1668 * @param bool $query2
1669 * @param string $proto Protocol type to use in URL
1670 * @return string The URL
1672 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1673 $query = self::fixUrlQueryArgs( $query, $query2 );
1675 # Hand off all the decisions on urls to getLocalURL
1676 $url = $this->getLocalURL( $query );
1678 # Expand the url to make it a full url. Note that getLocalURL has the
1679 # potential to output full urls for a variety of reasons, so we use
1680 # wfExpandUrl instead of simply prepending $wgServer
1681 $url = wfExpandUrl( $url, $proto );
1683 # Finally, add the fragment.
1684 $url .= $this->getFragmentForURL();
1686 Hooks::run( 'GetFullURL', [ &$this, &$url, $query ] );
1687 return $url;
1691 * Get a URL with no fragment or server name (relative URL) from a Title object.
1692 * If this page is generated with action=render, however,
1693 * $wgServer is prepended to make an absolute URL.
1695 * @see self::getFullURL to always get an absolute URL.
1696 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1697 * valid to link, locally, to the current Title.
1698 * @see self::newFromText to produce a Title object.
1700 * @param string|array $query An optional query string,
1701 * not used for interwiki links. Can be specified as an associative array as well,
1702 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1703 * Some query patterns will trigger various shorturl path replacements.
1704 * @param array $query2 An optional secondary query array. This one MUST
1705 * be an array. If a string is passed it will be interpreted as a deprecated
1706 * variant argument and urlencoded into a variant= argument.
1707 * This second query argument will be added to the $query
1708 * The second parameter is deprecated since 1.19. Pass it as a key,value
1709 * pair in the first parameter array instead.
1711 * @return string String of the URL.
1713 public function getLocalURL( $query = '', $query2 = false ) {
1714 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1716 $query = self::fixUrlQueryArgs( $query, $query2 );
1718 $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
1719 if ( $interwiki ) {
1720 $namespace = $this->getNsText();
1721 if ( $namespace != '' ) {
1722 # Can this actually happen? Interwikis shouldn't be parsed.
1723 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1724 $namespace .= ':';
1726 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1727 $url = wfAppendQuery( $url, $query );
1728 } else {
1729 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1730 if ( $query == '' ) {
1731 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1732 Hooks::run( 'GetLocalURL::Article', [ &$this, &$url ] );
1733 } else {
1734 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1735 $url = false;
1736 $matches = [];
1738 if ( !empty( $wgActionPaths )
1739 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1741 $action = urldecode( $matches[2] );
1742 if ( isset( $wgActionPaths[$action] ) ) {
1743 $query = $matches[1];
1744 if ( isset( $matches[4] ) ) {
1745 $query .= $matches[4];
1747 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1748 if ( $query != '' ) {
1749 $url = wfAppendQuery( $url, $query );
1754 if ( $url === false
1755 && $wgVariantArticlePath
1756 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1757 && $this->getPageLanguage()->equals( $wgContLang )
1758 && $this->getPageLanguage()->hasVariants()
1760 $variant = urldecode( $matches[1] );
1761 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1762 // Only do the variant replacement if the given variant is a valid
1763 // variant for the page's language.
1764 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1765 $url = str_replace( '$1', $dbkey, $url );
1769 if ( $url === false ) {
1770 if ( $query == '-' ) {
1771 $query = '';
1773 $url = "{$wgScript}?title={$dbkey}&{$query}";
1777 Hooks::run( 'GetLocalURL::Internal', [ &$this, &$url, $query ] );
1779 // @todo FIXME: This causes breakage in various places when we
1780 // actually expected a local URL and end up with dupe prefixes.
1781 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1782 $url = $wgServer . $url;
1785 Hooks::run( 'GetLocalURL', [ &$this, &$url, $query ] );
1786 return $url;
1790 * Get a URL that's the simplest URL that will be valid to link, locally,
1791 * to the current Title. It includes the fragment, but does not include
1792 * the server unless action=render is used (or the link is external). If
1793 * there's a fragment but the prefixed text is empty, we just return a link
1794 * to the fragment.
1796 * The result obviously should not be URL-escaped, but does need to be
1797 * HTML-escaped if it's being output in HTML.
1799 * @param array $query
1800 * @param bool $query2
1801 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1802 * or false (default) for no expansion
1803 * @see self::getLocalURL for the arguments.
1804 * @return string The URL
1806 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1807 if ( $this->isExternal() || $proto !== false ) {
1808 $ret = $this->getFullURL( $query, $query2, $proto );
1809 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1810 $ret = $this->getFragmentForURL();
1811 } else {
1812 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1814 return $ret;
1818 * Get the URL form for an internal link.
1819 * - Used in various CDN-related code, in case we have a different
1820 * internal hostname for the server from the exposed one.
1822 * This uses $wgInternalServer to qualify the path, or $wgServer
1823 * if $wgInternalServer is not set. If the server variable used is
1824 * protocol-relative, the URL will be expanded to http://
1826 * @see self::getLocalURL for the arguments.
1827 * @return string The URL
1829 public function getInternalURL( $query = '', $query2 = false ) {
1830 global $wgInternalServer, $wgServer;
1831 $query = self::fixUrlQueryArgs( $query, $query2 );
1832 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1833 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1834 Hooks::run( 'GetInternalURL', [ &$this, &$url, $query ] );
1835 return $url;
1839 * Get the URL for a canonical link, for use in things like IRC and
1840 * e-mail notifications. Uses $wgCanonicalServer and the
1841 * GetCanonicalURL hook.
1843 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1845 * @see self::getLocalURL for the arguments.
1846 * @return string The URL
1847 * @since 1.18
1849 public function getCanonicalURL( $query = '', $query2 = false ) {
1850 $query = self::fixUrlQueryArgs( $query, $query2 );
1851 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1852 Hooks::run( 'GetCanonicalURL', [ &$this, &$url, $query ] );
1853 return $url;
1857 * Get the edit URL for this Title
1859 * @return string The URL, or a null string if this is an interwiki link
1861 public function getEditURL() {
1862 if ( $this->isExternal() ) {
1863 return '';
1865 $s = $this->getLocalURL( 'action=edit' );
1867 return $s;
1871 * Can $user perform $action on this page?
1872 * This skips potentially expensive cascading permission checks
1873 * as well as avoids expensive error formatting
1875 * Suitable for use for nonessential UI controls in common cases, but
1876 * _not_ for functional access control.
1878 * May provide false positives, but should never provide a false negative.
1880 * @param string $action Action that permission needs to be checked for
1881 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1882 * @return bool
1884 public function quickUserCan( $action, $user = null ) {
1885 return $this->userCan( $action, $user, false );
1889 * Can $user perform $action on this page?
1891 * @param string $action Action that permission needs to be checked for
1892 * @param User $user User to check (since 1.19); $wgUser will be used if not
1893 * provided.
1894 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1895 * @return bool
1897 public function userCan( $action, $user = null, $rigor = 'secure' ) {
1898 if ( !$user instanceof User ) {
1899 global $wgUser;
1900 $user = $wgUser;
1903 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
1907 * Can $user perform $action on this page?
1909 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1911 * @param string $action Action that permission needs to be checked for
1912 * @param User $user User to check
1913 * @param string $rigor One of (quick,full,secure)
1914 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
1915 * - full : does cheap and expensive checks possibly from a replica DB
1916 * - secure : does cheap and expensive checks, using the master as needed
1917 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1918 * whose corresponding errors may be ignored.
1919 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
1921 public function getUserPermissionsErrors(
1922 $action, $user, $rigor = 'secure', $ignoreErrors = []
1924 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
1926 // Remove the errors being ignored.
1927 foreach ( $errors as $index => $error ) {
1928 $errKey = is_array( $error ) ? $error[0] : $error;
1930 if ( in_array( $errKey, $ignoreErrors ) ) {
1931 unset( $errors[$index] );
1933 if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
1934 unset( $errors[$index] );
1938 return $errors;
1942 * Permissions checks that fail most often, and which are easiest to test.
1944 * @param string $action The action to check
1945 * @param User $user User to check
1946 * @param array $errors List of current errors
1947 * @param string $rigor Same format as Title::getUserPermissionsErrors()
1948 * @param bool $short Short circuit on first error
1950 * @return array List of errors
1952 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
1953 if ( !Hooks::run( 'TitleQuickPermissions',
1954 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
1956 return $errors;
1959 if ( $action == 'create' ) {
1960 if (
1961 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1962 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1964 $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
1966 } elseif ( $action == 'move' ) {
1967 if ( !$user->isAllowed( 'move-rootuserpages' )
1968 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1969 // Show user page-specific message only if the user can move other pages
1970 $errors[] = [ 'cant-move-user-page' ];
1973 // Check if user is allowed to move files if it's a file
1974 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1975 $errors[] = [ 'movenotallowedfile' ];
1978 // Check if user is allowed to move category pages if it's a category page
1979 if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) {
1980 $errors[] = [ 'cant-move-category-page' ];
1983 if ( !$user->isAllowed( 'move' ) ) {
1984 // User can't move anything
1985 $userCanMove = User::groupHasPermission( 'user', 'move' );
1986 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1987 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1988 // custom message if logged-in users without any special rights can move
1989 $errors[] = [ 'movenologintext' ];
1990 } else {
1991 $errors[] = [ 'movenotallowed' ];
1994 } elseif ( $action == 'move-target' ) {
1995 if ( !$user->isAllowed( 'move' ) ) {
1996 // User can't move anything
1997 $errors[] = [ 'movenotallowed' ];
1998 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1999 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
2000 // Show user page-specific message only if the user can move other pages
2001 $errors[] = [ 'cant-move-to-user-page' ];
2002 } elseif ( !$user->isAllowed( 'move-categorypages' )
2003 && $this->mNamespace == NS_CATEGORY ) {
2004 // Show category page-specific message only if the user can move other pages
2005 $errors[] = [ 'cant-move-to-category-page' ];
2007 } elseif ( !$user->isAllowed( $action ) ) {
2008 $errors[] = $this->missingPermissionError( $action, $short );
2011 return $errors;
2015 * Add the resulting error code to the errors array
2017 * @param array $errors List of current errors
2018 * @param array $result Result of errors
2020 * @return array List of errors
2022 private function resultToError( $errors, $result ) {
2023 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2024 // A single array representing an error
2025 $errors[] = $result;
2026 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2027 // A nested array representing multiple errors
2028 $errors = array_merge( $errors, $result );
2029 } elseif ( $result !== '' && is_string( $result ) ) {
2030 // A string representing a message-id
2031 $errors[] = [ $result ];
2032 } elseif ( $result instanceof MessageSpecifier ) {
2033 // A message specifier representing an error
2034 $errors[] = [ $result ];
2035 } elseif ( $result === false ) {
2036 // a generic "We don't want them to do that"
2037 $errors[] = [ 'badaccess-group0' ];
2039 return $errors;
2043 * Check various permission hooks
2045 * @param string $action The action to check
2046 * @param User $user User to check
2047 * @param array $errors List of current errors
2048 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2049 * @param bool $short Short circuit on first error
2051 * @return array List of errors
2053 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2054 // Use getUserPermissionsErrors instead
2055 $result = '';
2056 if ( !Hooks::run( 'userCan', [ &$this, &$user, $action, &$result ] ) ) {
2057 return $result ? [] : [ [ 'badaccess-group0' ] ];
2059 // Check getUserPermissionsErrors hook
2060 if ( !Hooks::run( 'getUserPermissionsErrors', [ &$this, &$user, $action, &$result ] ) ) {
2061 $errors = $this->resultToError( $errors, $result );
2063 // Check getUserPermissionsErrorsExpensive hook
2064 if (
2065 $rigor !== 'quick'
2066 && !( $short && count( $errors ) > 0 )
2067 && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$this, &$user, $action, &$result ] )
2069 $errors = $this->resultToError( $errors, $result );
2072 return $errors;
2076 * Check permissions on special pages & namespaces
2078 * @param string $action The action to check
2079 * @param User $user User to check
2080 * @param array $errors List of current errors
2081 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2082 * @param bool $short Short circuit on first error
2084 * @return array List of errors
2086 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2087 # Only 'createaccount' can be performed on special pages,
2088 # which don't actually exist in the DB.
2089 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2090 $errors[] = [ 'ns-specialprotected' ];
2093 # Check $wgNamespaceProtection for restricted namespaces
2094 if ( $this->isNamespaceProtected( $user ) ) {
2095 $ns = $this->mNamespace == NS_MAIN ?
2096 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2097 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2098 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2101 return $errors;
2105 * Check CSS/JS sub-page permissions
2107 * @param string $action The action to check
2108 * @param User $user User to check
2109 * @param array $errors List of current errors
2110 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2111 * @param bool $short Short circuit on first error
2113 * @return array List of errors
2115 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2116 # Protect css/js subpages of user pages
2117 # XXX: this might be better using restrictions
2118 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2119 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2120 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2121 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2122 $errors[] = [ 'mycustomcssprotected', $action ];
2123 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2124 $errors[] = [ 'mycustomjsprotected', $action ];
2126 } else {
2127 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2128 $errors[] = [ 'customcssprotected', $action ];
2129 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2130 $errors[] = [ 'customjsprotected', $action ];
2135 return $errors;
2139 * Check against page_restrictions table requirements on this
2140 * page. The user must possess all required rights for this
2141 * action.
2143 * @param string $action The action to check
2144 * @param User $user User to check
2145 * @param array $errors List of current errors
2146 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2147 * @param bool $short Short circuit on first error
2149 * @return array List of errors
2151 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2152 foreach ( $this->getRestrictions( $action ) as $right ) {
2153 // Backwards compatibility, rewrite sysop -> editprotected
2154 if ( $right == 'sysop' ) {
2155 $right = 'editprotected';
2157 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2158 if ( $right == 'autoconfirmed' ) {
2159 $right = 'editsemiprotected';
2161 if ( $right == '' ) {
2162 continue;
2164 if ( !$user->isAllowed( $right ) ) {
2165 $errors[] = [ 'protectedpagetext', $right, $action ];
2166 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2167 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2171 return $errors;
2175 * Check restrictions on cascading pages.
2177 * @param string $action The action to check
2178 * @param User $user User to check
2179 * @param array $errors List of current errors
2180 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2181 * @param bool $short Short circuit on first error
2183 * @return array List of errors
2185 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2186 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2187 # We /could/ use the protection level on the source page, but it's
2188 # fairly ugly as we have to establish a precedence hierarchy for pages
2189 # included by multiple cascade-protected pages. So just restrict
2190 # it to people with 'protect' permission, as they could remove the
2191 # protection anyway.
2192 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2193 # Cascading protection depends on more than this page...
2194 # Several cascading protected pages may include this page...
2195 # Check each cascading level
2196 # This is only for protection restrictions, not for all actions
2197 if ( isset( $restrictions[$action] ) ) {
2198 foreach ( $restrictions[$action] as $right ) {
2199 // Backwards compatibility, rewrite sysop -> editprotected
2200 if ( $right == 'sysop' ) {
2201 $right = 'editprotected';
2203 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2204 if ( $right == 'autoconfirmed' ) {
2205 $right = 'editsemiprotected';
2207 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2208 $pages = '';
2209 foreach ( $cascadingSources as $page ) {
2210 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2212 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2218 return $errors;
2222 * Check action permissions not already checked in checkQuickPermissions
2224 * @param string $action The action to check
2225 * @param User $user User to check
2226 * @param array $errors List of current errors
2227 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2228 * @param bool $short Short circuit on first error
2230 * @return array List of errors
2232 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2233 global $wgDeleteRevisionsLimit, $wgLang;
2235 if ( $action == 'protect' ) {
2236 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2237 // If they can't edit, they shouldn't protect.
2238 $errors[] = [ 'protect-cantedit' ];
2240 } elseif ( $action == 'create' ) {
2241 $title_protection = $this->getTitleProtection();
2242 if ( $title_protection ) {
2243 if ( $title_protection['permission'] == ''
2244 || !$user->isAllowed( $title_protection['permission'] )
2246 $errors[] = [
2247 'titleprotected',
2248 User::whoIs( $title_protection['user'] ),
2249 $title_protection['reason']
2253 } elseif ( $action == 'move' ) {
2254 // Check for immobile pages
2255 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2256 // Specific message for this case
2257 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2258 } elseif ( !$this->isMovable() ) {
2259 // Less specific message for rarer cases
2260 $errors[] = [ 'immobile-source-page' ];
2262 } elseif ( $action == 'move-target' ) {
2263 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2264 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2265 } elseif ( !$this->isMovable() ) {
2266 $errors[] = [ 'immobile-target-page' ];
2268 } elseif ( $action == 'delete' ) {
2269 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2270 if ( !$tempErrors ) {
2271 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2272 $user, $tempErrors, $rigor, true );
2274 if ( $tempErrors ) {
2275 // If protection keeps them from editing, they shouldn't be able to delete.
2276 $errors[] = [ 'deleteprotected' ];
2278 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2279 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2281 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2284 return $errors;
2288 * Check that the user isn't blocked from editing.
2290 * @param string $action The action to check
2291 * @param User $user User to check
2292 * @param array $errors List of current errors
2293 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2294 * @param bool $short Short circuit on first error
2296 * @return array List of errors
2298 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2299 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2300 // Account creation blocks handled at userlogin.
2301 // Unblocking handled in SpecialUnblock
2302 if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2303 return $errors;
2306 // Optimize for a very common case
2307 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2308 return $errors;
2311 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2312 $errors[] = [ 'confirmedittext' ];
2315 $useSlave = ( $rigor !== 'secure' );
2316 if ( ( $action == 'edit' || $action == 'create' )
2317 && !$user->isBlockedFrom( $this, $useSlave )
2319 // Don't block the user from editing their own talk page unless they've been
2320 // explicitly blocked from that too.
2321 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2322 // @todo FIXME: Pass the relevant context into this function.
2323 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2326 return $errors;
2330 * Check that the user is allowed to read this page.
2332 * @param string $action The action to check
2333 * @param User $user User to check
2334 * @param array $errors List of current errors
2335 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2336 * @param bool $short Short circuit on first error
2338 * @return array List of errors
2340 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2341 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2343 $whitelisted = false;
2344 if ( User::isEveryoneAllowed( 'read' ) ) {
2345 # Shortcut for public wikis, allows skipping quite a bit of code
2346 $whitelisted = true;
2347 } elseif ( $user->isAllowed( 'read' ) ) {
2348 # If the user is allowed to read pages, he is allowed to read all pages
2349 $whitelisted = true;
2350 } elseif ( $this->isSpecial( 'Userlogin' )
2351 || $this->isSpecial( 'PasswordReset' )
2352 || $this->isSpecial( 'Userlogout' )
2354 # Always grant access to the login page.
2355 # Even anons need to be able to log in.
2356 $whitelisted = true;
2357 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2358 # Time to check the whitelist
2359 # Only do these checks is there's something to check against
2360 $name = $this->getPrefixedText();
2361 $dbName = $this->getPrefixedDBkey();
2363 // Check for explicit whitelisting with and without underscores
2364 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2365 $whitelisted = true;
2366 } elseif ( $this->getNamespace() == NS_MAIN ) {
2367 # Old settings might have the title prefixed with
2368 # a colon for main-namespace pages
2369 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2370 $whitelisted = true;
2372 } elseif ( $this->isSpecialPage() ) {
2373 # If it's a special page, ditch the subpage bit and check again
2374 $name = $this->getDBkey();
2375 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2376 if ( $name ) {
2377 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2378 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2379 $whitelisted = true;
2385 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2386 $name = $this->getPrefixedText();
2387 // Check for regex whitelisting
2388 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2389 if ( preg_match( $listItem, $name ) ) {
2390 $whitelisted = true;
2391 break;
2396 if ( !$whitelisted ) {
2397 # If the title is not whitelisted, give extensions a chance to do so...
2398 Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2399 if ( !$whitelisted ) {
2400 $errors[] = $this->missingPermissionError( $action, $short );
2404 return $errors;
2408 * Get a description array when the user doesn't have the right to perform
2409 * $action (i.e. when User::isAllowed() returns false)
2411 * @param string $action The action to check
2412 * @param bool $short Short circuit on first error
2413 * @return array List of errors
2415 private function missingPermissionError( $action, $short ) {
2416 // We avoid expensive display logic for quickUserCan's and such
2417 if ( $short ) {
2418 return [ 'badaccess-group0' ];
2421 $groups = array_map( [ 'User', 'makeGroupLinkWiki' ],
2422 User::getGroupsWithPermission( $action ) );
2424 if ( count( $groups ) ) {
2425 global $wgLang;
2426 return [
2427 'badaccess-groups',
2428 $wgLang->commaList( $groups ),
2429 count( $groups )
2431 } else {
2432 return [ 'badaccess-group0' ];
2437 * Can $user perform $action on this page? This is an internal function,
2438 * with multiple levels of checks depending on performance needs; see $rigor below.
2439 * It does not check wfReadOnly().
2441 * @param string $action Action that permission needs to be checked for
2442 * @param User $user User to check
2443 * @param string $rigor One of (quick,full,secure)
2444 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2445 * - full : does cheap and expensive checks possibly from a replica DB
2446 * - secure : does cheap and expensive checks, using the master as needed
2447 * @param bool $short Set this to true to stop after the first permission error.
2448 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2450 protected function getUserPermissionsErrorsInternal(
2451 $action, $user, $rigor = 'secure', $short = false
2453 if ( $rigor === true ) {
2454 $rigor = 'secure'; // b/c
2455 } elseif ( $rigor === false ) {
2456 $rigor = 'quick'; // b/c
2457 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2458 throw new Exception( "Invalid rigor parameter '$rigor'." );
2461 # Read has special handling
2462 if ( $action == 'read' ) {
2463 $checks = [
2464 'checkPermissionHooks',
2465 'checkReadPermissions',
2466 'checkUserBlock', // for wgBlockDisablesLogin
2468 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2469 # here as it will lead to duplicate error messages. This is okay to do
2470 # since anywhere that checks for create will also check for edit, and
2471 # those checks are called for edit.
2472 } elseif ( $action == 'create' ) {
2473 $checks = [
2474 'checkQuickPermissions',
2475 'checkPermissionHooks',
2476 'checkPageRestrictions',
2477 'checkCascadingSourcesRestrictions',
2478 'checkActionPermissions',
2479 'checkUserBlock'
2481 } else {
2482 $checks = [
2483 'checkQuickPermissions',
2484 'checkPermissionHooks',
2485 'checkSpecialsAndNSPermissions',
2486 'checkCSSandJSPermissions',
2487 'checkPageRestrictions',
2488 'checkCascadingSourcesRestrictions',
2489 'checkActionPermissions',
2490 'checkUserBlock'
2494 $errors = [];
2495 while ( count( $checks ) > 0 &&
2496 !( $short && count( $errors ) > 0 ) ) {
2497 $method = array_shift( $checks );
2498 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2501 return $errors;
2505 * Get a filtered list of all restriction types supported by this wiki.
2506 * @param bool $exists True to get all restriction types that apply to
2507 * titles that do exist, False for all restriction types that apply to
2508 * titles that do not exist
2509 * @return array
2511 public static function getFilteredRestrictionTypes( $exists = true ) {
2512 global $wgRestrictionTypes;
2513 $types = $wgRestrictionTypes;
2514 if ( $exists ) {
2515 # Remove the create restriction for existing titles
2516 $types = array_diff( $types, [ 'create' ] );
2517 } else {
2518 # Only the create and upload restrictions apply to non-existing titles
2519 $types = array_intersect( $types, [ 'create', 'upload' ] );
2521 return $types;
2525 * Returns restriction types for the current Title
2527 * @return array Applicable restriction types
2529 public function getRestrictionTypes() {
2530 if ( $this->isSpecialPage() ) {
2531 return [];
2534 $types = self::getFilteredRestrictionTypes( $this->exists() );
2536 if ( $this->getNamespace() != NS_FILE ) {
2537 # Remove the upload restriction for non-file titles
2538 $types = array_diff( $types, [ 'upload' ] );
2541 Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2543 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2544 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2546 return $types;
2550 * Is this title subject to title protection?
2551 * Title protection is the one applied against creation of such title.
2553 * @return array|bool An associative array representing any existent title
2554 * protection, or false if there's none.
2556 public function getTitleProtection() {
2557 // Can't protect pages in special namespaces
2558 if ( $this->getNamespace() < 0 ) {
2559 return false;
2562 // Can't protect pages that exist.
2563 if ( $this->exists() ) {
2564 return false;
2567 if ( $this->mTitleProtection === null ) {
2568 $dbr = wfGetDB( DB_REPLICA );
2569 $res = $dbr->select(
2570 'protected_titles',
2572 'user' => 'pt_user',
2573 'reason' => 'pt_reason',
2574 'expiry' => 'pt_expiry',
2575 'permission' => 'pt_create_perm'
2577 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2578 __METHOD__
2581 // fetchRow returns false if there are no rows.
2582 $row = $dbr->fetchRow( $res );
2583 if ( $row ) {
2584 if ( $row['permission'] == 'sysop' ) {
2585 $row['permission'] = 'editprotected'; // B/C
2587 if ( $row['permission'] == 'autoconfirmed' ) {
2588 $row['permission'] = 'editsemiprotected'; // B/C
2590 $row['expiry'] = $dbr->decodeExpiry( $row['expiry'] );
2592 $this->mTitleProtection = $row;
2594 return $this->mTitleProtection;
2598 * Remove any title protection due to page existing
2600 public function deleteTitleProtection() {
2601 $dbw = wfGetDB( DB_MASTER );
2603 $dbw->delete(
2604 'protected_titles',
2605 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2606 __METHOD__
2608 $this->mTitleProtection = false;
2612 * Is this page "semi-protected" - the *only* protection levels are listed
2613 * in $wgSemiprotectedRestrictionLevels?
2615 * @param string $action Action to check (default: edit)
2616 * @return bool
2618 public function isSemiProtected( $action = 'edit' ) {
2619 global $wgSemiprotectedRestrictionLevels;
2621 $restrictions = $this->getRestrictions( $action );
2622 $semi = $wgSemiprotectedRestrictionLevels;
2623 if ( !$restrictions || !$semi ) {
2624 // Not protected, or all protection is full protection
2625 return false;
2628 // Remap autoconfirmed to editsemiprotected for BC
2629 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2630 $semi[$key] = 'editsemiprotected';
2632 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2633 $restrictions[$key] = 'editsemiprotected';
2636 return !array_diff( $restrictions, $semi );
2640 * Does the title correspond to a protected article?
2642 * @param string $action The action the page is protected from,
2643 * by default checks all actions.
2644 * @return bool
2646 public function isProtected( $action = '' ) {
2647 global $wgRestrictionLevels;
2649 $restrictionTypes = $this->getRestrictionTypes();
2651 # Special pages have inherent protection
2652 if ( $this->isSpecialPage() ) {
2653 return true;
2656 # Check regular protection levels
2657 foreach ( $restrictionTypes as $type ) {
2658 if ( $action == $type || $action == '' ) {
2659 $r = $this->getRestrictions( $type );
2660 foreach ( $wgRestrictionLevels as $level ) {
2661 if ( in_array( $level, $r ) && $level != '' ) {
2662 return true;
2668 return false;
2672 * Determines if $user is unable to edit this page because it has been protected
2673 * by $wgNamespaceProtection.
2675 * @param User $user User object to check permissions
2676 * @return bool
2678 public function isNamespaceProtected( User $user ) {
2679 global $wgNamespaceProtection;
2681 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2682 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2683 if ( $right != '' && !$user->isAllowed( $right ) ) {
2684 return true;
2688 return false;
2692 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2694 * @return bool If the page is subject to cascading restrictions.
2696 public function isCascadeProtected() {
2697 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2698 return ( $sources > 0 );
2702 * Determines whether cascading protection sources have already been loaded from
2703 * the database.
2705 * @param bool $getPages True to check if the pages are loaded, or false to check
2706 * if the status is loaded.
2707 * @return bool Whether or not the specified information has been loaded
2708 * @since 1.23
2710 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2711 return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null;
2715 * Cascading protection: Get the source of any cascading restrictions on this page.
2717 * @param bool $getPages Whether or not to retrieve the actual pages
2718 * that the restrictions have come from and the actual restrictions
2719 * themselves.
2720 * @return array Two elements: First is an array of Title objects of the
2721 * pages from which cascading restrictions have come, false for
2722 * none, or true if such restrictions exist but $getPages was not
2723 * set. Second is an array like that returned by
2724 * Title::getAllRestrictions(), or an empty array if $getPages is
2725 * false.
2727 public function getCascadeProtectionSources( $getPages = true ) {
2728 $pagerestrictions = [];
2730 if ( $this->mCascadeSources !== null && $getPages ) {
2731 return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
2732 } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
2733 return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
2736 $dbr = wfGetDB( DB_REPLICA );
2738 if ( $this->getNamespace() == NS_FILE ) {
2739 $tables = [ 'imagelinks', 'page_restrictions' ];
2740 $where_clauses = [
2741 'il_to' => $this->getDBkey(),
2742 'il_from=pr_page',
2743 'pr_cascade' => 1
2745 } else {
2746 $tables = [ 'templatelinks', 'page_restrictions' ];
2747 $where_clauses = [
2748 'tl_namespace' => $this->getNamespace(),
2749 'tl_title' => $this->getDBkey(),
2750 'tl_from=pr_page',
2751 'pr_cascade' => 1
2755 if ( $getPages ) {
2756 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2757 'pr_expiry', 'pr_type', 'pr_level' ];
2758 $where_clauses[] = 'page_id=pr_page';
2759 $tables[] = 'page';
2760 } else {
2761 $cols = [ 'pr_expiry' ];
2764 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2766 $sources = $getPages ? [] : false;
2767 $now = wfTimestampNow();
2769 foreach ( $res as $row ) {
2770 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2771 if ( $expiry > $now ) {
2772 if ( $getPages ) {
2773 $page_id = $row->pr_page;
2774 $page_ns = $row->page_namespace;
2775 $page_title = $row->page_title;
2776 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2777 # Add groups needed for each restriction type if its not already there
2778 # Make sure this restriction type still exists
2780 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2781 $pagerestrictions[$row->pr_type] = [];
2784 if (
2785 isset( $pagerestrictions[$row->pr_type] )
2786 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2788 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2790 } else {
2791 $sources = true;
2796 if ( $getPages ) {
2797 $this->mCascadeSources = $sources;
2798 $this->mCascadingRestrictions = $pagerestrictions;
2799 } else {
2800 $this->mHasCascadingRestrictions = $sources;
2803 return [ $sources, $pagerestrictions ];
2807 * Accessor for mRestrictionsLoaded
2809 * @return bool Whether or not the page's restrictions have already been
2810 * loaded from the database
2811 * @since 1.23
2813 public function areRestrictionsLoaded() {
2814 return $this->mRestrictionsLoaded;
2818 * Accessor/initialisation for mRestrictions
2820 * @param string $action Action that permission needs to be checked for
2821 * @return array Restriction levels needed to take the action. All levels are
2822 * required. Note that restriction levels are normally user rights, but 'sysop'
2823 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2824 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2826 public function getRestrictions( $action ) {
2827 if ( !$this->mRestrictionsLoaded ) {
2828 $this->loadRestrictions();
2830 return isset( $this->mRestrictions[$action] )
2831 ? $this->mRestrictions[$action]
2832 : [];
2836 * Accessor/initialisation for mRestrictions
2838 * @return array Keys are actions, values are arrays as returned by
2839 * Title::getRestrictions()
2840 * @since 1.23
2842 public function getAllRestrictions() {
2843 if ( !$this->mRestrictionsLoaded ) {
2844 $this->loadRestrictions();
2846 return $this->mRestrictions;
2850 * Get the expiry time for the restriction against a given action
2852 * @param string $action
2853 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2854 * or not protected at all, or false if the action is not recognised.
2856 public function getRestrictionExpiry( $action ) {
2857 if ( !$this->mRestrictionsLoaded ) {
2858 $this->loadRestrictions();
2860 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2864 * Returns cascading restrictions for the current article
2866 * @return bool
2868 function areRestrictionsCascading() {
2869 if ( !$this->mRestrictionsLoaded ) {
2870 $this->loadRestrictions();
2873 return $this->mCascadeRestriction;
2877 * Compiles list of active page restrictions from both page table (pre 1.10)
2878 * and page_restrictions table for this existing page.
2879 * Public for usage by LiquidThreads.
2881 * @param array $rows Array of db result objects
2882 * @param string $oldFashionedRestrictions Comma-separated list of page
2883 * restrictions from page table (pre 1.10)
2885 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2886 $dbr = wfGetDB( DB_REPLICA );
2888 $restrictionTypes = $this->getRestrictionTypes();
2890 foreach ( $restrictionTypes as $type ) {
2891 $this->mRestrictions[$type] = [];
2892 $this->mRestrictionsExpiry[$type] = 'infinity';
2895 $this->mCascadeRestriction = false;
2897 # Backwards-compatibility: also load the restrictions from the page record (old format).
2898 if ( $oldFashionedRestrictions !== null ) {
2899 $this->mOldRestrictions = $oldFashionedRestrictions;
2902 if ( $this->mOldRestrictions === false ) {
2903 $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2904 [ 'page_id' => $this->getArticleID() ], __METHOD__ );
2907 if ( $this->mOldRestrictions != '' ) {
2908 foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
2909 $temp = explode( '=', trim( $restrict ) );
2910 if ( count( $temp ) == 1 ) {
2911 // old old format should be treated as edit/move restriction
2912 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2913 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2914 } else {
2915 $restriction = trim( $temp[1] );
2916 if ( $restriction != '' ) { // some old entries are empty
2917 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2923 if ( count( $rows ) ) {
2924 # Current system - load second to make them override.
2925 $now = wfTimestampNow();
2927 # Cycle through all the restrictions.
2928 foreach ( $rows as $row ) {
2930 // Don't take care of restrictions types that aren't allowed
2931 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2932 continue;
2935 // This code should be refactored, now that it's being used more generally,
2936 // But I don't really see any harm in leaving it in Block for now -werdna
2937 $expiry = $dbr->decodeExpiry( $row->pr_expiry );
2939 // Only apply the restrictions if they haven't expired!
2940 if ( !$expiry || $expiry > $now ) {
2941 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2942 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2944 $this->mCascadeRestriction |= $row->pr_cascade;
2949 $this->mRestrictionsLoaded = true;
2953 * Load restrictions from the page_restrictions table
2955 * @param string $oldFashionedRestrictions Comma-separated list of page
2956 * restrictions from page table (pre 1.10)
2958 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2959 if ( $this->mRestrictionsLoaded ) {
2960 return;
2963 $id = $this->getArticleID();
2964 if ( $id ) {
2965 $cache = ObjectCache::getMainWANInstance();
2966 $rows = $cache->getWithSetCallback(
2967 // Page protections always leave a new null revision
2968 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
2969 $cache::TTL_DAY,
2970 function ( $curValue, &$ttl, array &$setOpts ) {
2971 $dbr = wfGetDB( DB_REPLICA );
2973 $setOpts += Database::getCacheSetOptions( $dbr );
2975 return iterator_to_array(
2976 $dbr->select(
2977 'page_restrictions',
2978 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2979 [ 'pr_page' => $this->getArticleID() ],
2980 __METHOD__
2986 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2987 } else {
2988 $title_protection = $this->getTitleProtection();
2990 if ( $title_protection ) {
2991 $now = wfTimestampNow();
2992 $expiry = wfGetDB( DB_REPLICA )->decodeExpiry( $title_protection['expiry'] );
2994 if ( !$expiry || $expiry > $now ) {
2995 // Apply the restrictions
2996 $this->mRestrictionsExpiry['create'] = $expiry;
2997 $this->mRestrictions['create'] =
2998 explode( ',', trim( $title_protection['permission'] ) );
2999 } else { // Get rid of the old restrictions
3000 $this->mTitleProtection = false;
3002 } else {
3003 $this->mRestrictionsExpiry['create'] = 'infinity';
3005 $this->mRestrictionsLoaded = true;
3010 * Flush the protection cache in this object and force reload from the database.
3011 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3013 public function flushRestrictions() {
3014 $this->mRestrictionsLoaded = false;
3015 $this->mTitleProtection = null;
3019 * Purge expired restrictions from the page_restrictions table
3021 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3023 static function purgeExpiredRestrictions() {
3024 if ( wfReadOnly() ) {
3025 return;
3028 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3029 wfGetDB( DB_MASTER ),
3030 __METHOD__,
3031 function ( IDatabase $dbw, $fname ) {
3032 $config = MediaWikiServices::getInstance()->getMainConfig();
3033 $ids = $dbw->selectFieldValues(
3034 'page_restrictions',
3035 'pr_id',
3036 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3037 $fname,
3038 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3040 if ( $ids ) {
3041 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3044 ) );
3046 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
3047 wfGetDB( DB_MASTER ),
3048 __METHOD__,
3049 function ( IDatabase $dbw, $fname ) {
3050 $dbw->delete(
3051 'protected_titles',
3052 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3053 $fname
3056 ) );
3060 * Does this have subpages? (Warning, usually requires an extra DB query.)
3062 * @return bool
3064 public function hasSubpages() {
3065 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
3066 # Duh
3067 return false;
3070 # We dynamically add a member variable for the purpose of this method
3071 # alone to cache the result. There's no point in having it hanging
3072 # around uninitialized in every Title object; therefore we only add it
3073 # if needed and don't declare it statically.
3074 if ( $this->mHasSubpages === null ) {
3075 $this->mHasSubpages = false;
3076 $subpages = $this->getSubpages( 1 );
3077 if ( $subpages instanceof TitleArray ) {
3078 $this->mHasSubpages = (bool)$subpages->count();
3082 return $this->mHasSubpages;
3086 * Get all subpages of this page.
3088 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3089 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3090 * doesn't allow subpages
3092 public function getSubpages( $limit = -1 ) {
3093 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3094 return [];
3097 $dbr = wfGetDB( DB_REPLICA );
3098 $conds['page_namespace'] = $this->getNamespace();
3099 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3100 $options = [];
3101 if ( $limit > -1 ) {
3102 $options['LIMIT'] = $limit;
3104 $this->mSubpages = TitleArray::newFromResult(
3105 $dbr->select( 'page',
3106 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3107 $conds,
3108 __METHOD__,
3109 $options
3112 return $this->mSubpages;
3116 * Is there a version of this page in the deletion archive?
3118 * @return int The number of archived revisions
3120 public function isDeleted() {
3121 if ( $this->getNamespace() < 0 ) {
3122 $n = 0;
3123 } else {
3124 $dbr = wfGetDB( DB_REPLICA );
3126 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3127 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3128 __METHOD__
3130 if ( $this->getNamespace() == NS_FILE ) {
3131 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3132 [ 'fa_name' => $this->getDBkey() ],
3133 __METHOD__
3137 return (int)$n;
3141 * Is there a version of this page in the deletion archive?
3143 * @return bool
3145 public function isDeletedQuick() {
3146 if ( $this->getNamespace() < 0 ) {
3147 return false;
3149 $dbr = wfGetDB( DB_REPLICA );
3150 $deleted = (bool)$dbr->selectField( 'archive', '1',
3151 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3152 __METHOD__
3154 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3155 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3156 [ 'fa_name' => $this->getDBkey() ],
3157 __METHOD__
3160 return $deleted;
3164 * Get the article ID for this Title from the link cache,
3165 * adding it if necessary
3167 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3168 * for update
3169 * @return int The ID
3171 public function getArticleID( $flags = 0 ) {
3172 if ( $this->getNamespace() < 0 ) {
3173 $this->mArticleID = 0;
3174 return $this->mArticleID;
3176 $linkCache = LinkCache::singleton();
3177 if ( $flags & self::GAID_FOR_UPDATE ) {
3178 $oldUpdate = $linkCache->forUpdate( true );
3179 $linkCache->clearLink( $this );
3180 $this->mArticleID = $linkCache->addLinkObj( $this );
3181 $linkCache->forUpdate( $oldUpdate );
3182 } else {
3183 if ( -1 == $this->mArticleID ) {
3184 $this->mArticleID = $linkCache->addLinkObj( $this );
3187 return $this->mArticleID;
3191 * Is this an article that is a redirect page?
3192 * Uses link cache, adding it if necessary
3194 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3195 * @return bool
3197 public function isRedirect( $flags = 0 ) {
3198 if ( !is_null( $this->mRedirect ) ) {
3199 return $this->mRedirect;
3201 if ( !$this->getArticleID( $flags ) ) {
3202 $this->mRedirect = false;
3203 return $this->mRedirect;
3206 $linkCache = LinkCache::singleton();
3207 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3208 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3209 if ( $cached === null ) {
3210 # Trust LinkCache's state over our own
3211 # LinkCache is telling us that the page doesn't exist, despite there being cached
3212 # data relating to an existing page in $this->mArticleID. Updaters should clear
3213 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3214 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3215 # LinkCache to refresh its data from the master.
3216 $this->mRedirect = false;
3217 return $this->mRedirect;
3220 $this->mRedirect = (bool)$cached;
3222 return $this->mRedirect;
3226 * What is the length of this page?
3227 * Uses link cache, adding it if necessary
3229 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3230 * @return int
3232 public function getLength( $flags = 0 ) {
3233 if ( $this->mLength != -1 ) {
3234 return $this->mLength;
3236 if ( !$this->getArticleID( $flags ) ) {
3237 $this->mLength = 0;
3238 return $this->mLength;
3240 $linkCache = LinkCache::singleton();
3241 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3242 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3243 if ( $cached === null ) {
3244 # Trust LinkCache's state over our own, as for isRedirect()
3245 $this->mLength = 0;
3246 return $this->mLength;
3249 $this->mLength = intval( $cached );
3251 return $this->mLength;
3255 * What is the page_latest field for this page?
3257 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3258 * @return int Int or 0 if the page doesn't exist
3260 public function getLatestRevID( $flags = 0 ) {
3261 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3262 return intval( $this->mLatestID );
3264 if ( !$this->getArticleID( $flags ) ) {
3265 $this->mLatestID = 0;
3266 return $this->mLatestID;
3268 $linkCache = LinkCache::singleton();
3269 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3270 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3271 if ( $cached === null ) {
3272 # Trust LinkCache's state over our own, as for isRedirect()
3273 $this->mLatestID = 0;
3274 return $this->mLatestID;
3277 $this->mLatestID = intval( $cached );
3279 return $this->mLatestID;
3283 * This clears some fields in this object, and clears any associated
3284 * keys in the "bad links" section of the link cache.
3286 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3287 * loading of the new page_id. It's also called from
3288 * WikiPage::doDeleteArticleReal()
3290 * @param int $newid The new Article ID
3292 public function resetArticleID( $newid ) {
3293 $linkCache = LinkCache::singleton();
3294 $linkCache->clearLink( $this );
3296 if ( $newid === false ) {
3297 $this->mArticleID = -1;
3298 } else {
3299 $this->mArticleID = intval( $newid );
3301 $this->mRestrictionsLoaded = false;
3302 $this->mRestrictions = [];
3303 $this->mOldRestrictions = false;
3304 $this->mRedirect = null;
3305 $this->mLength = -1;
3306 $this->mLatestID = false;
3307 $this->mContentModel = false;
3308 $this->mEstimateRevisions = null;
3309 $this->mPageLanguage = false;
3310 $this->mDbPageLanguage = false;
3311 $this->mIsBigDeletion = null;
3314 public static function clearCaches() {
3315 $linkCache = LinkCache::singleton();
3316 $linkCache->clear();
3318 $titleCache = self::getTitleCache();
3319 $titleCache->clear();
3323 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3325 * @param string $text Containing title to capitalize
3326 * @param int $ns Namespace index, defaults to NS_MAIN
3327 * @return string Containing capitalized title
3329 public static function capitalize( $text, $ns = NS_MAIN ) {
3330 global $wgContLang;
3332 if ( MWNamespace::isCapitalized( $ns ) ) {
3333 return $wgContLang->ucfirst( $text );
3334 } else {
3335 return $text;
3340 * Secure and split - main initialisation function for this object
3342 * Assumes that mDbkeyform has been set, and is urldecoded
3343 * and uses underscores, but not otherwise munged. This function
3344 * removes illegal characters, splits off the interwiki and
3345 * namespace prefixes, sets the other forms, and canonicalizes
3346 * everything.
3348 * @throws MalformedTitleException On invalid titles
3349 * @return bool True on success
3351 private function secureAndSplit() {
3352 # Initialisation
3353 $this->mInterwiki = '';
3354 $this->mFragment = '';
3355 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3357 $dbkey = $this->mDbkeyform;
3359 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3360 // the parsing code with Title, while avoiding massive refactoring.
3361 // @todo: get rid of secureAndSplit, refactor parsing code.
3362 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3363 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3364 $titleCodec = MediaWikiServices::getInstance()->getTitleParser();
3365 // MalformedTitleException can be thrown here
3366 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3368 # Fill fields
3369 $this->setFragment( '#' . $parts['fragment'] );
3370 $this->mInterwiki = $parts['interwiki'];
3371 $this->mLocalInterwiki = $parts['local_interwiki'];
3372 $this->mNamespace = $parts['namespace'];
3373 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3375 $this->mDbkeyform = $parts['dbkey'];
3376 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3377 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );
3379 # We already know that some pages won't be in the database!
3380 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3381 $this->mArticleID = 0;
3384 return true;
3388 * Get an array of Title objects linking to this Title
3389 * Also stores the IDs in the link cache.
3391 * WARNING: do not use this function on arbitrary user-supplied titles!
3392 * On heavily-used templates it will max out the memory.
3394 * @param array $options May be FOR UPDATE
3395 * @param string $table Table name
3396 * @param string $prefix Fields prefix
3397 * @return Title[] Array of Title objects linking here
3399 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3400 if ( count( $options ) > 0 ) {
3401 $db = wfGetDB( DB_MASTER );
3402 } else {
3403 $db = wfGetDB( DB_REPLICA );
3406 $res = $db->select(
3407 [ 'page', $table ],
3408 self::getSelectFields(),
3410 "{$prefix}_from=page_id",
3411 "{$prefix}_namespace" => $this->getNamespace(),
3412 "{$prefix}_title" => $this->getDBkey() ],
3413 __METHOD__,
3414 $options
3417 $retVal = [];
3418 if ( $res->numRows() ) {
3419 $linkCache = LinkCache::singleton();
3420 foreach ( $res as $row ) {
3421 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3422 if ( $titleObj ) {
3423 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3424 $retVal[] = $titleObj;
3428 return $retVal;
3432 * Get an array of Title objects using this Title as a template
3433 * Also stores the IDs in the link cache.
3435 * WARNING: do not use this function on arbitrary user-supplied titles!
3436 * On heavily-used templates it will max out the memory.
3438 * @param array $options Query option to Database::select()
3439 * @return Title[] Array of Title the Title objects linking here
3441 public function getTemplateLinksTo( $options = [] ) {
3442 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3446 * Get an array of Title objects linked from this Title
3447 * Also stores the IDs in the link cache.
3449 * WARNING: do not use this function on arbitrary user-supplied titles!
3450 * On heavily-used templates it will max out the memory.
3452 * @param array $options Query option to Database::select()
3453 * @param string $table Table name
3454 * @param string $prefix Fields prefix
3455 * @return array Array of Title objects linking here
3457 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3458 $id = $this->getArticleID();
3460 # If the page doesn't exist; there can't be any link from this page
3461 if ( !$id ) {
3462 return [];
3465 $db = wfGetDB( DB_REPLICA );
3467 $blNamespace = "{$prefix}_namespace";
3468 $blTitle = "{$prefix}_title";
3470 $res = $db->select(
3471 [ $table, 'page' ],
3472 array_merge(
3473 [ $blNamespace, $blTitle ],
3474 WikiPage::selectFields()
3476 [ "{$prefix}_from" => $id ],
3477 __METHOD__,
3478 $options,
3479 [ 'page' => [
3480 'LEFT JOIN',
3481 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3485 $retVal = [];
3486 $linkCache = LinkCache::singleton();
3487 foreach ( $res as $row ) {
3488 if ( $row->page_id ) {
3489 $titleObj = Title::newFromRow( $row );
3490 } else {
3491 $titleObj = Title::makeTitle( $row->$blNamespace, $row->$blTitle );
3492 $linkCache->addBadLinkObj( $titleObj );
3494 $retVal[] = $titleObj;
3497 return $retVal;
3501 * Get an array of Title objects used on this Title as a template
3502 * Also stores the IDs in the link cache.
3504 * WARNING: do not use this function on arbitrary user-supplied titles!
3505 * On heavily-used templates it will max out the memory.
3507 * @param array $options May be FOR UPDATE
3508 * @return Title[] Array of Title the Title objects used here
3510 public function getTemplateLinksFrom( $options = [] ) {
3511 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3515 * Get an array of Title objects referring to non-existent articles linked
3516 * from this page.
3518 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3519 * should use redirect table in this case).
3520 * @return Title[] Array of Title the Title objects
3522 public function getBrokenLinksFrom() {
3523 if ( $this->getArticleID() == 0 ) {
3524 # All links from article ID 0 are false positives
3525 return [];
3528 $dbr = wfGetDB( DB_REPLICA );
3529 $res = $dbr->select(
3530 [ 'page', 'pagelinks' ],
3531 [ 'pl_namespace', 'pl_title' ],
3533 'pl_from' => $this->getArticleID(),
3534 'page_namespace IS NULL'
3536 __METHOD__, [],
3538 'page' => [
3539 'LEFT JOIN',
3540 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3545 $retVal = [];
3546 foreach ( $res as $row ) {
3547 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3549 return $retVal;
3553 * Get a list of URLs to purge from the CDN cache when this
3554 * page changes
3556 * @return string[] Array of String the URLs
3558 public function getCdnUrls() {
3559 $urls = [
3560 $this->getInternalURL(),
3561 $this->getInternalURL( 'action=history' )
3564 $pageLang = $this->getPageLanguage();
3565 if ( $pageLang->hasVariants() ) {
3566 $variants = $pageLang->getVariants();
3567 foreach ( $variants as $vCode ) {
3568 $urls[] = $this->getInternalURL( $vCode );
3572 // If we are looking at a css/js user subpage, purge the action=raw.
3573 if ( $this->isJsSubpage() ) {
3574 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3575 } elseif ( $this->isCssSubpage() ) {
3576 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3579 Hooks::run( 'TitleSquidURLs', [ $this, &$urls ] );
3580 return $urls;
3584 * @deprecated since 1.27 use getCdnUrls()
3586 public function getSquidURLs() {
3587 return $this->getCdnUrls();
3591 * Purge all applicable CDN URLs
3593 public function purgeSquid() {
3594 DeferredUpdates::addUpdate(
3595 new CdnCacheUpdate( $this->getCdnUrls() ),
3596 DeferredUpdates::PRESEND
3601 * Move this page without authentication
3603 * @deprecated since 1.25 use MovePage class instead
3604 * @param Title $nt The new page Title
3605 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3607 public function moveNoAuth( &$nt ) {
3608 wfDeprecated( __METHOD__, '1.25' );
3609 return $this->moveTo( $nt, false );
3613 * Check whether a given move operation would be valid.
3614 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3616 * @deprecated since 1.25, use MovePage's methods instead
3617 * @param Title $nt The new title
3618 * @param bool $auth Whether to check user permissions (uses $wgUser)
3619 * @param string $reason Is the log summary of the move, used for spam checking
3620 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3622 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3623 global $wgUser;
3625 if ( !( $nt instanceof Title ) ) {
3626 // Normally we'd add this to $errors, but we'll get
3627 // lots of syntax errors if $nt is not an object
3628 return [ [ 'badtitletext' ] ];
3631 $mp = new MovePage( $this, $nt );
3632 $errors = $mp->isValidMove()->getErrorsArray();
3633 if ( $auth ) {
3634 $errors = wfMergeErrorArrays(
3635 $errors,
3636 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3640 return $errors ?: true;
3644 * Check if the requested move target is a valid file move target
3645 * @todo move this to MovePage
3646 * @param Title $nt Target title
3647 * @return array List of errors
3649 protected function validateFileMoveOperation( $nt ) {
3650 global $wgUser;
3652 $errors = [];
3654 $destFile = wfLocalFile( $nt );
3655 $destFile->load( File::READ_LATEST );
3656 if ( !$wgUser->isAllowed( 'reupload-shared' )
3657 && !$destFile->exists() && wfFindFile( $nt )
3659 $errors[] = [ 'file-exists-sharedrepo' ];
3662 return $errors;
3666 * Move a title to a new location
3668 * @deprecated since 1.25, use the MovePage class instead
3669 * @param Title $nt The new title
3670 * @param bool $auth Indicates whether $wgUser's permissions
3671 * should be checked
3672 * @param string $reason The reason for the move
3673 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3674 * Ignored if the user doesn't have the suppressredirect right.
3675 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3677 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3678 global $wgUser;
3679 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3680 if ( is_array( $err ) ) {
3681 // Auto-block user's IP if the account was "hard" blocked
3682 $wgUser->spreadAnyEditBlock();
3683 return $err;
3685 // Check suppressredirect permission
3686 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3687 $createRedirect = true;
3690 $mp = new MovePage( $this, $nt );
3691 $status = $mp->move( $wgUser, $reason, $createRedirect );
3692 if ( $status->isOK() ) {
3693 return true;
3694 } else {
3695 return $status->getErrorsArray();
3700 * Move this page's subpages to be subpages of $nt
3702 * @param Title $nt Move target
3703 * @param bool $auth Whether $wgUser's permissions should be checked
3704 * @param string $reason The reason for the move
3705 * @param bool $createRedirect Whether to create redirects from the old subpages to
3706 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3707 * @return array Array with old page titles as keys, and strings (new page titles) or
3708 * arrays (errors) as values, or an error array with numeric indices if no pages
3709 * were moved
3711 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3712 global $wgMaximumMovedPages;
3713 // Check permissions
3714 if ( !$this->userCan( 'move-subpages' ) ) {
3715 return [ 'cant-move-subpages' ];
3717 // Do the source and target namespaces support subpages?
3718 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3719 return [ 'namespace-nosubpages',
3720 MWNamespace::getCanonicalName( $this->getNamespace() ) ];
3722 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3723 return [ 'namespace-nosubpages',
3724 MWNamespace::getCanonicalName( $nt->getNamespace() ) ];
3727 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3728 $retval = [];
3729 $count = 0;
3730 foreach ( $subpages as $oldSubpage ) {
3731 $count++;
3732 if ( $count > $wgMaximumMovedPages ) {
3733 $retval[$oldSubpage->getPrefixedText()] =
3734 [ 'movepage-max-pages',
3735 $wgMaximumMovedPages ];
3736 break;
3739 // We don't know whether this function was called before
3740 // or after moving the root page, so check both
3741 // $this and $nt
3742 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3743 || $oldSubpage->getArticleID() == $nt->getArticleID()
3745 // When moving a page to a subpage of itself,
3746 // don't move it twice
3747 continue;
3749 $newPageName = preg_replace(
3750 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3751 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3752 $oldSubpage->getDBkey() );
3753 if ( $oldSubpage->isTalkPage() ) {
3754 $newNs = $nt->getTalkPage()->getNamespace();
3755 } else {
3756 $newNs = $nt->getSubjectPage()->getNamespace();
3758 # Bug 14385: we need makeTitleSafe because the new page names may
3759 # be longer than 255 characters.
3760 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3762 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3763 if ( $success === true ) {
3764 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3765 } else {
3766 $retval[$oldSubpage->getPrefixedText()] = $success;
3769 return $retval;
3773 * Checks if this page is just a one-rev redirect.
3774 * Adds lock, so don't use just for light purposes.
3776 * @return bool
3778 public function isSingleRevRedirect() {
3779 global $wgContentHandlerUseDB;
3781 $dbw = wfGetDB( DB_MASTER );
3783 # Is it a redirect?
3784 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3785 if ( $wgContentHandlerUseDB ) {
3786 $fields[] = 'page_content_model';
3789 $row = $dbw->selectRow( 'page',
3790 $fields,
3791 $this->pageCond(),
3792 __METHOD__,
3793 [ 'FOR UPDATE' ]
3795 # Cache some fields we may want
3796 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3797 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3798 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3799 $this->mContentModel = $row && isset( $row->page_content_model )
3800 ? strval( $row->page_content_model )
3801 : false;
3803 if ( !$this->mRedirect ) {
3804 return false;
3806 # Does the article have a history?
3807 $row = $dbw->selectField( [ 'page', 'revision' ],
3808 'rev_id',
3809 [ 'page_namespace' => $this->getNamespace(),
3810 'page_title' => $this->getDBkey(),
3811 'page_id=rev_page',
3812 'page_latest != rev_id'
3814 __METHOD__,
3815 [ 'FOR UPDATE' ]
3817 # Return true if there was no history
3818 return ( $row === false );
3822 * Checks if $this can be moved to a given Title
3823 * - Selects for update, so don't call it unless you mean business
3825 * @deprecated since 1.25, use MovePage's methods instead
3826 * @param Title $nt The new title to check
3827 * @return bool
3829 public function isValidMoveTarget( $nt ) {
3830 # Is it an existing file?
3831 if ( $nt->getNamespace() == NS_FILE ) {
3832 $file = wfLocalFile( $nt );
3833 $file->load( File::READ_LATEST );
3834 if ( $file->exists() ) {
3835 wfDebug( __METHOD__ . ": file exists\n" );
3836 return false;
3839 # Is it a redirect with no history?
3840 if ( !$nt->isSingleRevRedirect() ) {
3841 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3842 return false;
3844 # Get the article text
3845 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
3846 if ( !is_object( $rev ) ) {
3847 return false;
3849 $content = $rev->getContent();
3850 # Does the redirect point to the source?
3851 # Or is it a broken self-redirect, usually caused by namespace collisions?
3852 $redirTitle = $content ? $content->getRedirectTarget() : null;
3854 if ( $redirTitle ) {
3855 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3856 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3857 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3858 return false;
3859 } else {
3860 return true;
3862 } else {
3863 # Fail safe (not a redirect after all. strange.)
3864 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3865 " is a redirect, but it doesn't contain a valid redirect.\n" );
3866 return false;
3871 * Get categories to which this Title belongs and return an array of
3872 * categories' names.
3874 * @return array Array of parents in the form:
3875 * $parent => $currentarticle
3877 public function getParentCategories() {
3878 global $wgContLang;
3880 $data = [];
3882 $titleKey = $this->getArticleID();
3884 if ( $titleKey === 0 ) {
3885 return $data;
3888 $dbr = wfGetDB( DB_REPLICA );
3890 $res = $dbr->select(
3891 'categorylinks',
3892 'cl_to',
3893 [ 'cl_from' => $titleKey ],
3894 __METHOD__
3897 if ( $res->numRows() > 0 ) {
3898 foreach ( $res as $row ) {
3899 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3900 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3903 return $data;
3907 * Get a tree of parent categories
3909 * @param array $children Array with the children in the keys, to check for circular refs
3910 * @return array Tree of parent categories
3912 public function getParentCategoryTree( $children = [] ) {
3913 $stack = [];
3914 $parents = $this->getParentCategories();
3916 if ( $parents ) {
3917 foreach ( $parents as $parent => $current ) {
3918 if ( array_key_exists( $parent, $children ) ) {
3919 # Circular reference
3920 $stack[$parent] = [];
3921 } else {
3922 $nt = Title::newFromText( $parent );
3923 if ( $nt ) {
3924 $stack[$parent] = $nt->getParentCategoryTree( $children + [ $parent => 1 ] );
3930 return $stack;
3934 * Get an associative array for selecting this title from
3935 * the "page" table
3937 * @return array Array suitable for the $where parameter of DB::select()
3939 public function pageCond() {
3940 if ( $this->mArticleID > 0 ) {
3941 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3942 return [ 'page_id' => $this->mArticleID ];
3943 } else {
3944 return [ 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform ];
3949 * Get the revision ID of the previous revision
3951 * @param int $revId Revision ID. Get the revision that was before this one.
3952 * @param int $flags Title::GAID_FOR_UPDATE
3953 * @return int|bool Old revision ID, or false if none exists
3955 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3956 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
3957 $revId = $db->selectField( 'revision', 'rev_id',
3959 'rev_page' => $this->getArticleID( $flags ),
3960 'rev_id < ' . intval( $revId )
3962 __METHOD__,
3963 [ 'ORDER BY' => 'rev_id DESC' ]
3966 if ( $revId === false ) {
3967 return false;
3968 } else {
3969 return intval( $revId );
3974 * Get the revision ID of the next revision
3976 * @param int $revId Revision ID. Get the revision that was after this one.
3977 * @param int $flags Title::GAID_FOR_UPDATE
3978 * @return int|bool Next revision ID, or false if none exists
3980 public function getNextRevisionID( $revId, $flags = 0 ) {
3981 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
3982 $revId = $db->selectField( 'revision', 'rev_id',
3984 'rev_page' => $this->getArticleID( $flags ),
3985 'rev_id > ' . intval( $revId )
3987 __METHOD__,
3988 [ 'ORDER BY' => 'rev_id' ]
3991 if ( $revId === false ) {
3992 return false;
3993 } else {
3994 return intval( $revId );
3999 * Get the first revision of the page
4001 * @param int $flags Title::GAID_FOR_UPDATE
4002 * @return Revision|null If page doesn't exist
4004 public function getFirstRevision( $flags = 0 ) {
4005 $pageId = $this->getArticleID( $flags );
4006 if ( $pageId ) {
4007 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_REPLICA );
4008 $row = $db->selectRow( 'revision', Revision::selectFields(),
4009 [ 'rev_page' => $pageId ],
4010 __METHOD__,
4011 [ 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 ]
4013 if ( $row ) {
4014 return new Revision( $row );
4017 return null;
4021 * Get the oldest revision timestamp of this page
4023 * @param int $flags Title::GAID_FOR_UPDATE
4024 * @return string MW timestamp
4026 public function getEarliestRevTime( $flags = 0 ) {
4027 $rev = $this->getFirstRevision( $flags );
4028 return $rev ? $rev->getTimestamp() : null;
4032 * Check if this is a new page
4034 * @return bool
4036 public function isNewPage() {
4037 $dbr = wfGetDB( DB_REPLICA );
4038 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4042 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4044 * @return bool
4046 public function isBigDeletion() {
4047 global $wgDeleteRevisionsLimit;
4049 if ( !$wgDeleteRevisionsLimit ) {
4050 return false;
4053 if ( $this->mIsBigDeletion === null ) {
4054 $dbr = wfGetDB( DB_REPLICA );
4056 $revCount = $dbr->selectRowCount(
4057 'revision',
4058 '1',
4059 [ 'rev_page' => $this->getArticleID() ],
4060 __METHOD__,
4061 [ 'LIMIT' => $wgDeleteRevisionsLimit + 1 ]
4064 $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit;
4067 return $this->mIsBigDeletion;
4071 * Get the approximate revision count of this page.
4073 * @return int
4075 public function estimateRevisionCount() {
4076 if ( !$this->exists() ) {
4077 return 0;
4080 if ( $this->mEstimateRevisions === null ) {
4081 $dbr = wfGetDB( DB_REPLICA );
4082 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4083 [ 'rev_page' => $this->getArticleID() ], __METHOD__ );
4086 return $this->mEstimateRevisions;
4090 * Get the number of revisions between the given revision.
4091 * Used for diffs and other things that really need it.
4093 * @param int|Revision $old Old revision or rev ID (first before range)
4094 * @param int|Revision $new New revision or rev ID (first after range)
4095 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4096 * @return int Number of revisions between these revisions.
4098 public function countRevisionsBetween( $old, $new, $max = null ) {
4099 if ( !( $old instanceof Revision ) ) {
4100 $old = Revision::newFromTitle( $this, (int)$old );
4102 if ( !( $new instanceof Revision ) ) {
4103 $new = Revision::newFromTitle( $this, (int)$new );
4105 if ( !$old || !$new ) {
4106 return 0; // nothing to compare
4108 $dbr = wfGetDB( DB_REPLICA );
4109 $conds = [
4110 'rev_page' => $this->getArticleID(),
4111 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4112 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4114 if ( $max !== null ) {
4115 return $dbr->selectRowCount( 'revision', '1',
4116 $conds,
4117 __METHOD__,
4118 [ 'LIMIT' => $max + 1 ] // extra to detect truncation
4120 } else {
4121 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4126 * Get the authors between the given revisions or revision IDs.
4127 * Used for diffs and other things that really need it.
4129 * @since 1.23
4131 * @param int|Revision $old Old revision or rev ID (first before range by default)
4132 * @param int|Revision $new New revision or rev ID (first after range by default)
4133 * @param int $limit Maximum number of authors
4134 * @param string|array $options (Optional): Single option, or an array of options:
4135 * 'include_old' Include $old in the range; $new is excluded.
4136 * 'include_new' Include $new in the range; $old is excluded.
4137 * 'include_both' Include both $old and $new in the range.
4138 * Unknown option values are ignored.
4139 * @return array|null Names of revision authors in the range; null if not both revisions exist
4141 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4142 if ( !( $old instanceof Revision ) ) {
4143 $old = Revision::newFromTitle( $this, (int)$old );
4145 if ( !( $new instanceof Revision ) ) {
4146 $new = Revision::newFromTitle( $this, (int)$new );
4148 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4149 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4150 // in the sanity check below?
4151 if ( !$old || !$new ) {
4152 return null; // nothing to compare
4154 $authors = [];
4155 $old_cmp = '>';
4156 $new_cmp = '<';
4157 $options = (array)$options;
4158 if ( in_array( 'include_old', $options ) ) {
4159 $old_cmp = '>=';
4161 if ( in_array( 'include_new', $options ) ) {
4162 $new_cmp = '<=';
4164 if ( in_array( 'include_both', $options ) ) {
4165 $old_cmp = '>=';
4166 $new_cmp = '<=';
4168 // No DB query needed if $old and $new are the same or successive revisions:
4169 if ( $old->getId() === $new->getId() ) {
4170 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4171 [] :
4172 [ $old->getUserText( Revision::RAW ) ];
4173 } elseif ( $old->getId() === $new->getParentId() ) {
4174 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4175 $authors[] = $old->getUserText( Revision::RAW );
4176 if ( $old->getUserText( Revision::RAW ) != $new->getUserText( Revision::RAW ) ) {
4177 $authors[] = $new->getUserText( Revision::RAW );
4179 } elseif ( $old_cmp === '>=' ) {
4180 $authors[] = $old->getUserText( Revision::RAW );
4181 } elseif ( $new_cmp === '<=' ) {
4182 $authors[] = $new->getUserText( Revision::RAW );
4184 return $authors;
4186 $dbr = wfGetDB( DB_REPLICA );
4187 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4189 'rev_page' => $this->getArticleID(),
4190 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4191 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4192 ], __METHOD__,
4193 [ 'LIMIT' => $limit + 1 ] // add one so caller knows it was truncated
4195 foreach ( $res as $row ) {
4196 $authors[] = $row->rev_user_text;
4198 return $authors;
4202 * Get the number of authors between the given revisions or revision IDs.
4203 * Used for diffs and other things that really need it.
4205 * @param int|Revision $old Old revision or rev ID (first before range by default)
4206 * @param int|Revision $new New revision or rev ID (first after range by default)
4207 * @param int $limit Maximum number of authors
4208 * @param string|array $options (Optional): Single option, or an array of options:
4209 * 'include_old' Include $old in the range; $new is excluded.
4210 * 'include_new' Include $new in the range; $old is excluded.
4211 * 'include_both' Include both $old and $new in the range.
4212 * Unknown option values are ignored.
4213 * @return int Number of revision authors in the range; zero if not both revisions exist
4215 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4216 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4217 return $authors ? count( $authors ) : 0;
4221 * Compare with another title.
4223 * @param Title $title
4224 * @return bool
4226 public function equals( Title $title ) {
4227 // Note: === is necessary for proper matching of number-like titles.
4228 return $this->getInterwiki() === $title->getInterwiki()
4229 && $this->getNamespace() == $title->getNamespace()
4230 && $this->getDBkey() === $title->getDBkey();
4234 * Check if this title is a subpage of another title
4236 * @param Title $title
4237 * @return bool
4239 public function isSubpageOf( Title $title ) {
4240 return $this->getInterwiki() === $title->getInterwiki()
4241 && $this->getNamespace() == $title->getNamespace()
4242 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4246 * Check if page exists. For historical reasons, this function simply
4247 * checks for the existence of the title in the page table, and will
4248 * thus return false for interwiki links, special pages and the like.
4249 * If you want to know if a title can be meaningfully viewed, you should
4250 * probably call the isKnown() method instead.
4252 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4253 * from master/for update
4254 * @return bool
4256 public function exists( $flags = 0 ) {
4257 $exists = $this->getArticleID( $flags ) != 0;
4258 Hooks::run( 'TitleExists', [ $this, &$exists ] );
4259 return $exists;
4263 * Should links to this title be shown as potentially viewable (i.e. as
4264 * "bluelinks"), even if there's no record by this title in the page
4265 * table?
4267 * This function is semi-deprecated for public use, as well as somewhat
4268 * misleadingly named. You probably just want to call isKnown(), which
4269 * calls this function internally.
4271 * (ISSUE: Most of these checks are cheap, but the file existence check
4272 * can potentially be quite expensive. Including it here fixes a lot of
4273 * existing code, but we might want to add an optional parameter to skip
4274 * it and any other expensive checks.)
4276 * @return bool
4278 public function isAlwaysKnown() {
4279 $isKnown = null;
4282 * Allows overriding default behavior for determining if a page exists.
4283 * If $isKnown is kept as null, regular checks happen. If it's
4284 * a boolean, this value is returned by the isKnown method.
4286 * @since 1.20
4288 * @param Title $title
4289 * @param bool|null $isKnown
4291 Hooks::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4293 if ( !is_null( $isKnown ) ) {
4294 return $isKnown;
4297 if ( $this->isExternal() ) {
4298 return true; // any interwiki link might be viewable, for all we know
4301 switch ( $this->mNamespace ) {
4302 case NS_MEDIA:
4303 case NS_FILE:
4304 // file exists, possibly in a foreign repo
4305 return (bool)wfFindFile( $this );
4306 case NS_SPECIAL:
4307 // valid special page
4308 return SpecialPageFactory::exists( $this->getDBkey() );
4309 case NS_MAIN:
4310 // selflink, possibly with fragment
4311 return $this->mDbkeyform == '';
4312 case NS_MEDIAWIKI:
4313 // known system message
4314 return $this->hasSourceText() !== false;
4315 default:
4316 return false;
4321 * Does this title refer to a page that can (or might) be meaningfully
4322 * viewed? In particular, this function may be used to determine if
4323 * links to the title should be rendered as "bluelinks" (as opposed to
4324 * "redlinks" to non-existent pages).
4325 * Adding something else to this function will cause inconsistency
4326 * since LinkHolderArray calls isAlwaysKnown() and does its own
4327 * page existence check.
4329 * @return bool
4331 public function isKnown() {
4332 return $this->isAlwaysKnown() || $this->exists();
4336 * Does this page have source text?
4338 * @return bool
4340 public function hasSourceText() {
4341 if ( $this->exists() ) {
4342 return true;
4345 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4346 // If the page doesn't exist but is a known system message, default
4347 // message content will be displayed, same for language subpages-
4348 // Use always content language to avoid loading hundreds of languages
4349 // to get the link color.
4350 global $wgContLang;
4351 list( $name, ) = MessageCache::singleton()->figureMessage(
4352 $wgContLang->lcfirst( $this->getText() )
4354 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4355 return $message->exists();
4358 return false;
4362 * Get the default message text or false if the message doesn't exist
4364 * @return string|bool
4366 public function getDefaultMessageText() {
4367 global $wgContLang;
4369 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4370 return false;
4373 list( $name, $lang ) = MessageCache::singleton()->figureMessage(
4374 $wgContLang->lcfirst( $this->getText() )
4376 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4378 if ( $message->exists() ) {
4379 return $message->plain();
4380 } else {
4381 return false;
4386 * Updates page_touched for this page; called from LinksUpdate.php
4388 * @param string $purgeTime [optional] TS_MW timestamp
4389 * @return bool True if the update succeeded
4391 public function invalidateCache( $purgeTime = null ) {
4392 if ( wfReadOnly() ) {
4393 return false;
4396 if ( $this->mArticleID === 0 ) {
4397 return true; // avoid gap locking if we know it's not there
4400 $conds = $this->pageCond();
4401 DeferredUpdates::addUpdate(
4402 new AutoCommitUpdate(
4403 wfGetDB( DB_MASTER ),
4404 __METHOD__,
4405 function ( IDatabase $dbw, $fname ) use ( $conds, $purgeTime ) {
4406 $dbTimestamp = $dbw->timestamp( $purgeTime ?: time() );
4407 $dbw->update(
4408 'page',
4409 [ 'page_touched' => $dbTimestamp ],
4410 $conds + [ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4411 $fname
4413 MediaWikiServices::getInstance()->getLinkCache()->invalidateTitle( $this );
4416 DeferredUpdates::PRESEND
4419 return true;
4423 * Update page_touched timestamps and send CDN purge messages for
4424 * pages linking to this title. May be sent to the job queue depending
4425 * on the number of links. Typically called on create and delete.
4427 public function touchLinks() {
4428 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks' ) );
4429 if ( $this->getNamespace() == NS_CATEGORY ) {
4430 DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this, 'categorylinks' ) );
4435 * Get the last touched timestamp
4437 * @param IDatabase $db Optional db
4438 * @return string Last-touched timestamp
4440 public function getTouched( $db = null ) {
4441 if ( $db === null ) {
4442 $db = wfGetDB( DB_REPLICA );
4444 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4445 return $touched;
4449 * Get the timestamp when this page was updated since the user last saw it.
4451 * @param User $user
4452 * @return string|null
4454 public function getNotificationTimestamp( $user = null ) {
4455 global $wgUser;
4457 // Assume current user if none given
4458 if ( !$user ) {
4459 $user = $wgUser;
4461 // Check cache first
4462 $uid = $user->getId();
4463 if ( !$uid ) {
4464 return false;
4466 // avoid isset here, as it'll return false for null entries
4467 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4468 return $this->mNotificationTimestamp[$uid];
4470 // Don't cache too much!
4471 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4472 $this->mNotificationTimestamp = [];
4475 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
4476 $watchedItem = $store->getWatchedItem( $user, $this );
4477 if ( $watchedItem ) {
4478 $this->mNotificationTimestamp[$uid] = $watchedItem->getNotificationTimestamp();
4479 } else {
4480 $this->mNotificationTimestamp[$uid] = false;
4483 return $this->mNotificationTimestamp[$uid];
4487 * Generate strings used for xml 'id' names in monobook tabs
4489 * @param string $prepend Defaults to 'nstab-'
4490 * @return string XML 'id' name
4492 public function getNamespaceKey( $prepend = 'nstab-' ) {
4493 global $wgContLang;
4494 // Gets the subject namespace if this title
4495 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4496 // Checks if canonical namespace name exists for namespace
4497 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4498 // Uses canonical namespace name
4499 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4500 } else {
4501 // Uses text of namespace
4502 $namespaceKey = $this->getSubjectNsText();
4504 // Makes namespace key lowercase
4505 $namespaceKey = $wgContLang->lc( $namespaceKey );
4506 // Uses main
4507 if ( $namespaceKey == '' ) {
4508 $namespaceKey = 'main';
4510 // Changes file to image for backwards compatibility
4511 if ( $namespaceKey == 'file' ) {
4512 $namespaceKey = 'image';
4514 return $prepend . $namespaceKey;
4518 * Get all extant redirects to this Title
4520 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4521 * @return Title[] Array of Title redirects to this title
4523 public function getRedirectsHere( $ns = null ) {
4524 $redirs = [];
4526 $dbr = wfGetDB( DB_REPLICA );
4527 $where = [
4528 'rd_namespace' => $this->getNamespace(),
4529 'rd_title' => $this->getDBkey(),
4530 'rd_from = page_id'
4532 if ( $this->isExternal() ) {
4533 $where['rd_interwiki'] = $this->getInterwiki();
4534 } else {
4535 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4537 if ( !is_null( $ns ) ) {
4538 $where['page_namespace'] = $ns;
4541 $res = $dbr->select(
4542 [ 'redirect', 'page' ],
4543 [ 'page_namespace', 'page_title' ],
4544 $where,
4545 __METHOD__
4548 foreach ( $res as $row ) {
4549 $redirs[] = self::newFromRow( $row );
4551 return $redirs;
4555 * Check if this Title is a valid redirect target
4557 * @return bool
4559 public function isValidRedirectTarget() {
4560 global $wgInvalidRedirectTargets;
4562 if ( $this->isSpecialPage() ) {
4563 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4564 if ( $this->isSpecial( 'Userlogout' ) ) {
4565 return false;
4568 foreach ( $wgInvalidRedirectTargets as $target ) {
4569 if ( $this->isSpecial( $target ) ) {
4570 return false;
4575 return true;
4579 * Get a backlink cache object
4581 * @return BacklinkCache
4583 public function getBacklinkCache() {
4584 return BacklinkCache::get( $this );
4588 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4590 * @return bool
4592 public function canUseNoindex() {
4593 global $wgExemptFromUserRobotsControl;
4595 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4596 ? MWNamespace::getContentNamespaces()
4597 : $wgExemptFromUserRobotsControl;
4599 return !in_array( $this->mNamespace, $bannedNamespaces );
4604 * Returns the raw sort key to be used for categories, with the specified
4605 * prefix. This will be fed to Collation::getSortKey() to get a
4606 * binary sortkey that can be used for actual sorting.
4608 * @param string $prefix The prefix to be used, specified using
4609 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4610 * prefix.
4611 * @return string
4613 public function getCategorySortkey( $prefix = '' ) {
4614 $unprefixed = $this->getText();
4616 // Anything that uses this hook should only depend
4617 // on the Title object passed in, and should probably
4618 // tell the users to run updateCollations.php --force
4619 // in order to re-sort existing category relations.
4620 Hooks::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4621 if ( $prefix !== '' ) {
4622 # Separate with a line feed, so the unprefixed part is only used as
4623 # a tiebreaker when two pages have the exact same prefix.
4624 # In UCA, tab is the only character that can sort above LF
4625 # so we strip both of them from the original prefix.
4626 $prefix = strtr( $prefix, "\n\t", ' ' );
4627 return "$prefix\n$unprefixed";
4629 return $unprefixed;
4633 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4634 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4635 * the db, it will return NULL.
4637 * @return string|null|bool
4639 private function getDbPageLanguageCode() {
4640 global $wgPageLanguageUseDB;
4642 // check, if the page language could be saved in the database, and if so and
4643 // the value is not requested already, lookup the page language using LinkCache
4644 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage === false ) {
4645 $linkCache = LinkCache::singleton();
4646 $linkCache->addLinkObj( $this );
4647 $this->mDbPageLanguage = $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4650 return $this->mDbPageLanguage;
4654 * Get the language in which the content of this page is written in
4655 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4656 * e.g. $wgLang (such as special pages, which are in the user language).
4658 * @since 1.18
4659 * @return Language
4661 public function getPageLanguage() {
4662 global $wgLang, $wgLanguageCode;
4663 if ( $this->isSpecialPage() ) {
4664 // special pages are in the user language
4665 return $wgLang;
4668 // Checking if DB language is set
4669 $dbPageLanguage = $this->getDbPageLanguageCode();
4670 if ( $dbPageLanguage ) {
4671 return wfGetLangObj( $dbPageLanguage );
4674 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4675 // Note that this may depend on user settings, so the cache should
4676 // be only per-request.
4677 // NOTE: ContentHandler::getPageLanguage() may need to load the
4678 // content to determine the page language!
4679 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4680 // tests.
4681 $contentHandler = ContentHandler::getForTitle( $this );
4682 $langObj = $contentHandler->getPageLanguage( $this );
4683 $this->mPageLanguage = [ $langObj->getCode(), $wgLanguageCode ];
4684 } else {
4685 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4688 return $langObj;
4692 * Get the language in which the content of this page is written when
4693 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4694 * e.g. $wgLang (such as special pages, which are in the user language).
4696 * @since 1.20
4697 * @return Language
4699 public function getPageViewLanguage() {
4700 global $wgLang;
4702 if ( $this->isSpecialPage() ) {
4703 // If the user chooses a variant, the content is actually
4704 // in a language whose code is the variant code.
4705 $variant = $wgLang->getPreferredVariant();
4706 if ( $wgLang->getCode() !== $variant ) {
4707 return Language::factory( $variant );
4710 return $wgLang;
4713 // Checking if DB language is set
4714 $dbPageLanguage = $this->getDbPageLanguageCode();
4715 if ( $dbPageLanguage ) {
4716 $pageLang = wfGetLangObj( $dbPageLanguage );
4717 $variant = $pageLang->getPreferredVariant();
4718 if ( $pageLang->getCode() !== $variant ) {
4719 $pageLang = Language::factory( $variant );
4722 return $pageLang;
4725 // @note Can't be cached persistently, depends on user settings.
4726 // @note ContentHandler::getPageViewLanguage() may need to load the
4727 // content to determine the page language!
4728 $contentHandler = ContentHandler::getForTitle( $this );
4729 $pageLang = $contentHandler->getPageViewLanguage( $this );
4730 return $pageLang;
4734 * Get a list of rendered edit notices for this page.
4736 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4737 * they will already be wrapped in paragraphs.
4739 * @since 1.21
4740 * @param int $oldid Revision ID that's being edited
4741 * @return array
4743 public function getEditNotices( $oldid = 0 ) {
4744 $notices = [];
4746 // Optional notice for the entire namespace
4747 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4748 $msg = wfMessage( $editnotice_ns );
4749 if ( $msg->exists() ) {
4750 $html = $msg->parseAsBlock();
4751 // Edit notices may have complex logic, but output nothing (T91715)
4752 if ( trim( $html ) !== '' ) {
4753 $notices[$editnotice_ns] = Html::rawElement(
4754 'div',
4755 [ 'class' => [
4756 'mw-editnotice',
4757 'mw-editnotice-namespace',
4758 Sanitizer::escapeClass( "mw-$editnotice_ns" )
4759 ] ],
4760 $html
4765 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4766 // Optional notice for page itself and any parent page
4767 $parts = explode( '/', $this->getDBkey() );
4768 $editnotice_base = $editnotice_ns;
4769 while ( count( $parts ) > 0 ) {
4770 $editnotice_base .= '-' . array_shift( $parts );
4771 $msg = wfMessage( $editnotice_base );
4772 if ( $msg->exists() ) {
4773 $html = $msg->parseAsBlock();
4774 if ( trim( $html ) !== '' ) {
4775 $notices[$editnotice_base] = Html::rawElement(
4776 'div',
4777 [ 'class' => [
4778 'mw-editnotice',
4779 'mw-editnotice-base',
4780 Sanitizer::escapeClass( "mw-$editnotice_base" )
4781 ] ],
4782 $html
4787 } else {
4788 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4789 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4790 $msg = wfMessage( $editnoticeText );
4791 if ( $msg->exists() ) {
4792 $html = $msg->parseAsBlock();
4793 if ( trim( $html ) !== '' ) {
4794 $notices[$editnoticeText] = Html::rawElement(
4795 'div',
4796 [ 'class' => [
4797 'mw-editnotice',
4798 'mw-editnotice-page',
4799 Sanitizer::escapeClass( "mw-$editnoticeText" )
4800 ] ],
4801 $html
4807 Hooks::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4808 return $notices;
4812 * @return array
4814 public function __sleep() {
4815 return [
4816 'mNamespace',
4817 'mDbkeyform',
4818 'mFragment',
4819 'mInterwiki',
4820 'mLocalInterwiki',
4821 'mUserCaseDBKey',
4822 'mDefaultNamespace',
4826 public function __wakeup() {
4827 $this->mArticleID = ( $this->mNamespace >= 0 ) ? -1 : 0;
4828 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
4829 $this->mTextform = strtr( $this->mDbkeyform, '_', ' ' );