3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\Permissions\PermissionManager
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use MediaWiki\Linker\LinkTarget
;
29 use MediaWiki\Interwiki\InterwikiLookup
;
30 use MediaWiki\MediaWikiServices
;
33 * Represents a title within MediaWiki.
34 * Optionally may contain an interwiki designation or namespace.
35 * @note This class can fetch various kinds of data from the database;
36 * however, it does so inefficiently.
37 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
38 * and does not rely on global state or the database.
40 class Title
implements LinkTarget
, IDBAccessObject
{
41 /** @var MapCacheLRU|null */
42 private static $titleCache = null;
45 * Title::newFromText maintains a cache to avoid expensive re-normalization of
46 * commonly used titles. On a batch operation this can become a memory leak
47 * if not bounded. After hitting this many titles reset the cache.
49 const CACHE_MAX
= 1000;
52 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
53 * to use the master DB
55 const GAID_FOR_UPDATE
= 1;
58 * Flag for use with factory methods like newFromLinkTarget() that have
59 * a $forceClone parameter. If set, the method must return a new instance.
60 * Without this flag, some factory methods may return existing instances.
64 const NEW_CLONE
= 'clone';
67 * @name Private member variables
68 * Please use the accessor functions instead.
73 /** @var string Text form (spaces not underscores) of the main part */
74 public $mTextform = '';
76 /** @var string URL-encoded form of the main part */
77 public $mUrlform = '';
79 /** @var string Main part with underscores */
80 public $mDbkeyform = '';
82 /** @var string Database key with the initial letter in the case specified by the user */
83 protected $mUserCaseDBKey;
85 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
86 public $mNamespace = NS_MAIN
;
88 /** @var string Interwiki prefix */
89 public $mInterwiki = '';
91 /** @var bool Was this Title created from a string with a local interwiki prefix? */
92 private $mLocalInterwiki = false;
94 /** @var string Title fragment (i.e. the bit after the #) */
95 public $mFragment = '';
97 /** @var int Article ID, fetched from the link cache on demand */
98 public $mArticleID = -1;
100 /** @var bool|int ID of most recent revision */
101 protected $mLatestID = false;
104 * @var bool|string ID of the page's content model, i.e. one of the
105 * CONTENT_MODEL_XXX constants
107 private $mContentModel = false;
110 * @var bool If a content model was forced via setContentModel()
111 * this will be true to avoid having other code paths reset it
113 private $mForcedContentModel = false;
115 /** @var int Estimated number of revisions; null of not loaded */
116 private $mEstimateRevisions;
118 /** @var array Array of groups allowed to edit this article */
119 public $mRestrictions = [];
122 * @var string|bool Comma-separated set of permission keys
123 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
124 * Edit and move sections are separated by a colon
125 * Example: "edit=autoconfirmed,sysop:move=sysop"
127 protected $mOldRestrictions = false;
129 /** @var bool Cascade restrictions on this page to included templates and images? */
130 public $mCascadeRestriction;
132 /** Caching the results of getCascadeProtectionSources */
133 public $mCascadingRestrictions;
135 /** @var array When do the restrictions on this page expire? */
136 protected $mRestrictionsExpiry = [];
138 /** @var bool Are cascading restrictions in effect on this page? */
139 protected $mHasCascadingRestrictions;
141 /** @var array Where are the cascading restrictions coming from on this page? */
142 public $mCascadeSources;
144 /** @var bool Boolean for initialisation on demand */
145 public $mRestrictionsLoaded = false;
148 * Text form including namespace/interwiki, initialised on demand
150 * Only public to share cache with TitleFormatter
155 public $prefixedText = null;
157 /** @var mixed Cached value for getTitleProtection (create protection) */
158 public $mTitleProtection;
161 * @var int Namespace index when there is no namespace. Don't change the
162 * following default, NS_MAIN is hardcoded in several places. See T2696.
163 * Zero except in {{transclusion}} tags.
165 public $mDefaultNamespace = NS_MAIN
;
167 /** @var int The page length, 0 for special pages */
168 protected $mLength = -1;
170 /** @var null Is the article at this title a redirect? */
171 public $mRedirect = null;
173 /** @var array Associative array of user ID -> timestamp/false */
174 private $mNotificationTimestamp = [];
176 /** @var bool Whether a page has any subpages */
177 private $mHasSubpages;
179 /** @var bool The (string) language code of the page's language and content code. */
180 private $mPageLanguage = false;
182 /** @var string|bool|null The page language code from the database, null if not saved in
183 * the database or false if not loaded, yet. */
184 private $mDbPageLanguage = false;
186 /** @var TitleValue|null A corresponding TitleValue object */
187 private $mTitleValue = null;
189 /** @var bool|null Would deleting this page be a big deletion? */
190 private $mIsBigDeletion = null;
194 * B/C kludge: provide a TitleParser for use by Title.
195 * Ideally, Title would have no methods that need this.
196 * Avoid usage of this singleton by using TitleValue
197 * and the associated services when possible.
199 * @return TitleFormatter
201 private static function getTitleFormatter() {
202 return MediaWikiServices
::getInstance()->getTitleFormatter();
206 * B/C kludge: provide an InterwikiLookup for use by Title.
207 * Ideally, Title would have no methods that need this.
208 * Avoid usage of this singleton by using TitleValue
209 * and the associated services when possible.
211 * @return InterwikiLookup
213 private static function getInterwikiLookup() {
214 return MediaWikiServices
::getInstance()->getInterwikiLookup();
220 function __construct() {
224 * Create a new Title from a prefixed DB key
226 * @param string $key The database key, which has underscores
227 * instead of spaces, possibly including namespace and
229 * @return Title|null Title, or null on an error
231 public static function newFromDBkey( $key ) {
233 $t->mDbkeyform
= $key;
236 $t->secureAndSplit();
238 } catch ( MalformedTitleException
$ex ) {
244 * Returns a Title given a TitleValue.
245 * If the given TitleValue is already a Title instance, that instance is returned,
246 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
247 * is already a Title instance, that instance is copied using the clone operator.
249 * @param TitleValue $titleValue Assumed to be safe.
250 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
254 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
255 return self
::newFromLinkTarget( $titleValue, $forceClone );
259 * Returns a Title given a LinkTarget.
260 * If the given LinkTarget is already a Title instance, that instance is returned,
261 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
262 * is already a Title instance, that instance is copied using the clone operator.
264 * @param LinkTarget $linkTarget Assumed to be safe.
265 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
269 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
270 if ( $linkTarget instanceof Title
) {
271 // Special case if it's already a Title object
272 if ( $forceClone === self
::NEW_CLONE
) {
273 return clone $linkTarget;
278 return self
::makeTitle(
279 $linkTarget->getNamespace(),
280 $linkTarget->getText(),
281 $linkTarget->getFragment(),
282 $linkTarget->getInterwiki()
287 * Create a new Title from text, such as what one would find in a link. De-
288 * codes any HTML entities in the text.
290 * Title objects returned by this method are guaranteed to be valid, and
291 * thus return true from the isValid() method.
293 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
294 * It may instead be a cached instance created previously, with references to it remaining
297 * @param string|int|null $text The link text; spaces, prefixes, and an
298 * initial ':' indicating the main namespace are accepted.
299 * @param int $defaultNamespace The namespace to use if none is specified
300 * by a prefix. If you want to force a specific namespace even if
301 * $text might begin with a namespace prefix, use makeTitle() or
303 * @throws InvalidArgumentException
304 * @return Title|null Title or null on an error.
306 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
307 // DWIM: Integers can be passed in here when page titles are used as array keys.
308 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
309 throw new InvalidArgumentException( '$text must be a string.' );
311 if ( $text === null ) {
316 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
317 } catch ( MalformedTitleException
$ex ) {
323 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
324 * rather than returning null.
326 * The exception subclasses encode detailed information about why the title is invalid.
328 * Title objects returned by this method are guaranteed to be valid, and
329 * thus return true from the isValid() method.
331 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
332 * It may instead be a cached instance created previously, with references to it remaining
335 * @see Title::newFromText
338 * @param string $text Title text to check
339 * @param int $defaultNamespace
340 * @throws MalformedTitleException If the title is invalid
343 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
344 if ( is_object( $text ) ) {
345 throw new MWException( '$text must be a string, given an object' );
346 } elseif ( $text === null ) {
347 // Legacy code relies on MalformedTitleException being thrown in this case
348 // (happens when URL with no title in it is parsed). TODO fix
349 throw new MalformedTitleException( 'title-invalid-empty' );
352 $titleCache = self
::getTitleCache();
354 // Wiki pages often contain multiple links to the same page.
355 // Title normalization and parsing can become expensive on pages with many
356 // links, so we can save a little time by caching them.
357 // In theory these are value objects and won't get changed...
358 if ( $defaultNamespace == NS_MAIN
) {
359 $t = $titleCache->get( $text );
365 // Convert things like é ā or 〗 into normalized (T16952) text
366 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
369 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
370 $t->mDefaultNamespace
= (int)$defaultNamespace;
372 $t->secureAndSplit();
373 if ( $defaultNamespace == NS_MAIN
) {
374 $titleCache->set( $text, $t );
380 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
382 * Example of wrong and broken code:
383 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
385 * Example of right code:
386 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
388 * Create a new Title from URL-encoded text. Ensures that
389 * the given title's length does not exceed the maximum.
391 * @param string $url The title, as might be taken from a URL
392 * @return Title|null The new object, or null on an error
394 public static function newFromURL( $url ) {
397 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
398 # but some URLs used it as a space replacement and they still come
399 # from some external search tools.
400 if ( strpos( self
::legalChars(), '+' ) === false ) {
401 $url = strtr( $url, '+', ' ' );
404 $t->mDbkeyform
= strtr( $url, ' ', '_' );
407 $t->secureAndSplit();
409 } catch ( MalformedTitleException
$ex ) {
415 * @return MapCacheLRU
417 private static function getTitleCache() {
418 if ( self
::$titleCache === null ) {
419 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
421 return self
::$titleCache;
425 * Returns a list of fields that are to be selected for initializing Title
426 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
427 * whether to include page_content_model.
431 protected static function getSelectFields() {
432 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
435 'page_namespace', 'page_title', 'page_id',
436 'page_len', 'page_is_redirect', 'page_latest',
439 if ( $wgContentHandlerUseDB ) {
440 $fields[] = 'page_content_model';
443 if ( $wgPageLanguageUseDB ) {
444 $fields[] = 'page_lang';
451 * Create a new Title from an article ID
453 * @param int $id The page_id corresponding to the Title to create
454 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
455 * @return Title|null The new object, or null on an error
457 public static function newFromID( $id, $flags = 0 ) {
458 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
459 $row = $db->selectRow(
461 self
::getSelectFields(),
462 [ 'page_id' => $id ],
465 if ( $row !== false ) {
466 $title = self
::newFromRow( $row );
475 * Make an array of titles from an array of IDs
477 * @param int[] $ids Array of IDs
478 * @return Title[] Array of Titles
480 public static function newFromIDs( $ids ) {
481 if ( !count( $ids ) ) {
484 $dbr = wfGetDB( DB_REPLICA
);
488 self
::getSelectFields(),
489 [ 'page_id' => $ids ],
494 foreach ( $res as $row ) {
495 $titles[] = self
::newFromRow( $row );
501 * Make a Title object from a DB row
503 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
504 * @return Title Corresponding Title
506 public static function newFromRow( $row ) {
507 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
508 $t->loadFromRow( $row );
513 * Load Title object fields from a DB row.
514 * If false is given, the title will be treated as non-existing.
516 * @param stdClass|bool $row Database row
518 public function loadFromRow( $row ) {
519 if ( $row ) { // page found
520 if ( isset( $row->page_id
) ) {
521 $this->mArticleID
= (int)$row->page_id
;
523 if ( isset( $row->page_len
) ) {
524 $this->mLength
= (int)$row->page_len
;
526 if ( isset( $row->page_is_redirect
) ) {
527 $this->mRedirect
= (bool)$row->page_is_redirect
;
529 if ( isset( $row->page_latest
) ) {
530 $this->mLatestID
= (int)$row->page_latest
;
532 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
533 $this->mContentModel
= (string)$row->page_content_model
;
534 } elseif ( !$this->mForcedContentModel
) {
535 $this->mContentModel
= false; # initialized lazily in getContentModel()
537 if ( isset( $row->page_lang
) ) {
538 $this->mDbPageLanguage
= (string)$row->page_lang
;
540 if ( isset( $row->page_restrictions
) ) {
541 $this->mOldRestrictions
= $row->page_restrictions
;
543 } else { // page not found
544 $this->mArticleID
= 0;
546 $this->mRedirect
= false;
547 $this->mLatestID
= 0;
548 if ( !$this->mForcedContentModel
) {
549 $this->mContentModel
= false; # initialized lazily in getContentModel()
555 * Create a new Title from a namespace index and a DB key.
557 * It's assumed that $ns and $title are safe, for instance when
558 * they came directly from the database or a special page name,
559 * not from user input.
561 * No validation is applied. For convenience, spaces are normalized
562 * to underscores, so that e.g. user_text fields can be used directly.
564 * @note This method may return Title objects that are "invalid"
565 * according to the isValid() method. This is usually caused by
566 * configuration changes: e.g. a namespace that was once defined is
567 * no longer configured, or a character that was once allowed in
568 * titles is now forbidden.
570 * @param int $ns The namespace of the article
571 * @param string $title The unprefixed database key form
572 * @param string $fragment The link fragment (after the "#")
573 * @param string $interwiki The interwiki prefix
574 * @return Title The new object
576 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
578 $t->mInterwiki
= $interwiki;
579 $t->mFragment
= $fragment;
580 $t->mNamespace
= $ns = (int)$ns;
581 $t->mDbkeyform
= strtr( $title, ' ', '_' );
582 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
583 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
584 $t->mTextform
= strtr( $title, '_', ' ' );
585 $t->mContentModel
= false; # initialized lazily in getContentModel()
590 * Create a new Title from a namespace index and a DB key.
591 * The parameters will be checked for validity, which is a bit slower
592 * than makeTitle() but safer for user-provided data.
594 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
595 * that is, they return true from the isValid() method. If no valid Title
596 * can be constructed from the input, this method returns null.
598 * @param int $ns The namespace of the article
599 * @param string $title Database key form
600 * @param string $fragment The link fragment (after the "#")
601 * @param string $interwiki Interwiki prefix
602 * @return Title|null The new object, or null on an error
604 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
605 // NOTE: ideally, this would just call makeTitle() and then isValid(),
606 // but presently, that means more overhead on a potential performance hotspot.
608 if ( !MWNamespace
::exists( $ns ) ) {
613 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
616 $t->secureAndSplit();
618 } catch ( MalformedTitleException
$ex ) {
624 * Create a new Title for the Main Page
626 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
627 * It may instead be a cached instance created previously, with references to it remaining
630 * @return Title The new object
632 public static function newMainPage() {
633 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
634 // Don't give fatal errors if the message is broken
636 $title = self
::newFromText( 'Main Page' );
642 * Get the prefixed DB key associated with an ID
644 * @param int $id The page_id of the article
645 * @return Title|null An object representing the article, or null if no such article was found
647 public static function nameOf( $id ) {
648 $dbr = wfGetDB( DB_REPLICA
);
650 $s = $dbr->selectRow(
652 [ 'page_namespace', 'page_title' ],
653 [ 'page_id' => $id ],
656 if ( $s === false ) {
660 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
665 * Get a regex character class describing the legal characters in a link
667 * @return string The list of characters, not delimited
669 public static function legalChars() {
670 global $wgLegalTitleChars;
671 return $wgLegalTitleChars;
675 * Utility method for converting a character sequence from bytes to Unicode.
677 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
678 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
680 * @param string $byteClass
683 public static function convertByteClassToUnicodeClass( $byteClass ) {
684 $length = strlen( $byteClass );
686 $x0 = $x1 = $x2 = '';
688 $d0 = $d1 = $d2 = '';
689 // Decoded integer codepoints
690 $ord0 = $ord1 = $ord2 = 0;
692 $r0 = $r1 = $r2 = '';
696 $allowUnicode = false;
697 for ( $pos = 0; $pos < $length; $pos++
) {
698 // Shift the queues down
707 // Load the current input token and decoded values
708 $inChar = $byteClass[$pos];
709 if ( $inChar == '\\' ) {
710 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
711 $x0 = $inChar . $m[0];
712 $d0 = chr( hexdec( $m[1] ) );
713 $pos +
= strlen( $m[0] );
714 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
715 $x0 = $inChar . $m[0];
716 $d0 = chr( octdec( $m[0] ) );
717 $pos +
= strlen( $m[0] );
718 } elseif ( $pos +
1 >= $length ) {
721 $d0 = $byteClass[$pos +
1];
729 // Load the current re-encoded value
730 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
731 $r0 = sprintf( '\x%02x', $ord0 );
732 } elseif ( $ord0 >= 0x80 ) {
733 // Allow unicode if a single high-bit character appears
734 $r0 = sprintf( '\x%02x', $ord0 );
735 $allowUnicode = true;
736 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
737 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
743 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
745 if ( $ord2 > $ord0 ) {
747 } elseif ( $ord0 >= 0x80 ) {
749 $allowUnicode = true;
750 if ( $ord2 < 0x80 ) {
751 // Keep the non-unicode section of the range
758 // Reset state to the initial value
759 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
760 } elseif ( $ord2 < 0x80 ) {
765 if ( $ord1 < 0x80 ) {
768 if ( $ord0 < 0x80 ) {
771 if ( $allowUnicode ) {
772 $out .= '\u0080-\uFFFF';
778 * Make a prefixed DB key from a DB key and a namespace index
780 * @param int $ns Numerical representation of the namespace
781 * @param string $title The DB key form the title
782 * @param string $fragment The link fragment (after the "#")
783 * @param string $interwiki The interwiki prefix
784 * @param bool $canonicalNamespace If true, use the canonical name for
785 * $ns instead of the localized version.
786 * @return string The prefixed form of the title
788 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
789 $canonicalNamespace = false
791 if ( $canonicalNamespace ) {
792 $namespace = MWNamespace
::getCanonicalName( $ns );
794 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
796 $name = $namespace == '' ?
$title : "$namespace:$title";
797 if ( strval( $interwiki ) != '' ) {
798 $name = "$interwiki:$name";
800 if ( strval( $fragment ) != '' ) {
801 $name .= '#' . $fragment;
807 * Callback for usort() to do title sorts by (namespace, title)
809 * @param LinkTarget $a
810 * @param LinkTarget $b
812 * @return int Result of string comparison, or namespace comparison
814 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
815 return $a->getNamespace() <=> $b->getNamespace()
816 ?
: strcmp( $a->getText(), $b->getText() );
820 * Returns true if the title is valid, false if it is invalid.
822 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
823 * Invalid titles may get returned from makeTitle(), and it may be useful to
824 * allow them to exist, e.g. in order to process log entries about pages in
825 * namespaces that belong to extensions that are no longer installed.
827 * @note This method is relatively expensive. When constructing Title
828 * objects that need to be valid, use an instantiator method that is guaranteed
829 * to return valid titles, such as makeTitleSafe() or newFromText().
833 public function isValid() {
834 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
839 $parser = MediaWikiServices
::getInstance()->getTitleParser();
840 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
842 } catch ( MalformedTitleException
$ex ) {
848 * Determine whether the object refers to a page within
849 * this project (either this wiki or a wiki with a local
850 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
852 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
854 public function isLocal() {
855 if ( $this->isExternal() ) {
856 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
858 return $iw->isLocal();
865 * Is this Title interwiki?
869 public function isExternal() {
870 return $this->mInterwiki
!== '';
874 * Get the interwiki prefix
876 * Use Title::isExternal to check if a interwiki is set
878 * @return string Interwiki prefix
880 public function getInterwiki() {
881 return $this->mInterwiki
;
885 * Was this a local interwiki link?
889 public function wasLocalInterwiki() {
890 return $this->mLocalInterwiki
;
894 * Determine whether the object refers to a page within
895 * this project and is transcludable.
897 * @return bool True if this is transcludable
899 public function isTrans() {
900 if ( !$this->isExternal() ) {
904 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
908 * Returns the DB name of the distant wiki which owns the object.
910 * @return string|false The DB name
912 public function getTransWikiID() {
913 if ( !$this->isExternal() ) {
917 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
921 * Get a TitleValue object representing this Title.
923 * @note Not all valid Titles have a corresponding valid TitleValue
924 * (e.g. TitleValues cannot represent page-local links that have a
925 * fragment but no title text).
927 * @return TitleValue|null
929 public function getTitleValue() {
930 if ( $this->mTitleValue
=== null ) {
932 $this->mTitleValue
= new TitleValue(
938 } catch ( InvalidArgumentException
$ex ) {
939 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
940 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
944 return $this->mTitleValue
;
948 * Get the text form (spaces not underscores) of the main part
950 * @return string Main part of the title
952 public function getText() {
953 return $this->mTextform
;
957 * Get the URL-encoded form of the main part
959 * @return string Main part of the title, URL-encoded
961 public function getPartialURL() {
962 return $this->mUrlform
;
966 * Get the main part with underscores
968 * @return string Main part of the title, with underscores
970 public function getDBkey() {
971 return $this->mDbkeyform
;
975 * Get the DB key with the initial letter case as specified by the user
976 * @deprecated since 1.33; please use Title::getDBKey() instead
978 * @return string DB key
980 function getUserCaseDBKey() {
981 if ( !is_null( $this->mUserCaseDBKey
) ) {
982 return $this->mUserCaseDBKey
;
984 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
985 return $this->mDbkeyform
;
990 * Get the namespace index, i.e. one of the NS_xxxx constants.
992 * @return int Namespace index
994 public function getNamespace() {
995 return $this->mNamespace
;
999 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1001 * @todo Deprecate this in favor of SlotRecord::getModel()
1003 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1004 * @return string Content model id
1006 public function getContentModel( $flags = 0 ) {
1007 if ( !$this->mForcedContentModel
1008 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1009 && $this->getArticleID( $flags )
1011 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1012 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1013 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1016 if ( !$this->mContentModel
) {
1017 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1020 return $this->mContentModel
;
1024 * Convenience method for checking a title's content model name
1026 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1027 * @return bool True if $this->getContentModel() == $id
1029 public function hasContentModel( $id ) {
1030 return $this->getContentModel() == $id;
1034 * Set a proposed content model for the page for permissions
1035 * checking. This does not actually change the content model
1038 * Additionally, you should make sure you've checked
1039 * ContentHandler::canBeUsedOn() first.
1042 * @param string $model CONTENT_MODEL_XXX constant
1044 public function setContentModel( $model ) {
1045 $this->mContentModel
= $model;
1046 $this->mForcedContentModel
= true;
1050 * Get the namespace text
1052 * @return string|false Namespace text
1054 public function getNsText() {
1055 if ( $this->isExternal() ) {
1056 // This probably shouldn't even happen, except for interwiki transclusion.
1057 // If possible, use the canonical name for the foreign namespace.
1058 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1059 if ( $nsText !== false ) {
1065 $formatter = self
::getTitleFormatter();
1066 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1067 } catch ( InvalidArgumentException
$ex ) {
1068 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1074 * Get the namespace text of the subject (rather than talk) page
1076 * @return string Namespace text
1078 public function getSubjectNsText() {
1079 return MediaWikiServices
::getInstance()->getContentLanguage()->
1080 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1084 * Get the namespace text of the talk page
1086 * @return string Namespace text
1088 public function getTalkNsText() {
1089 return MediaWikiServices
::getInstance()->getContentLanguage()->
1090 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1094 * Can this title have a corresponding talk page?
1096 * @see MWNamespace::hasTalkNamespace
1099 * @return bool True if this title either is a talk page or can have a talk page associated.
1101 public function canHaveTalkPage() {
1102 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1106 * Is this in a namespace that allows actual pages?
1110 public function canExist() {
1111 return $this->mNamespace
>= NS_MAIN
;
1115 * Can this title be added to a user's watchlist?
1119 public function isWatchable() {
1120 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1124 * Returns true if this is a special page.
1128 public function isSpecialPage() {
1129 return $this->mNamespace
== NS_SPECIAL
;
1133 * Returns true if this title resolves to the named special page
1135 * @param string $name The special page name
1138 public function isSpecial( $name ) {
1139 if ( $this->isSpecialPage() ) {
1140 list( $thisName, /* $subpage */ ) =
1141 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1142 resolveAlias( $this->mDbkeyform
);
1143 if ( $name == $thisName ) {
1151 * If the Title refers to a special page alias which is not the local default, resolve
1152 * the alias, and localise the name as necessary. Otherwise, return $this
1156 public function fixSpecialName() {
1157 if ( $this->isSpecialPage() ) {
1158 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1159 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1160 if ( $canonicalName ) {
1161 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1162 if ( $localName != $this->mDbkeyform
) {
1163 return self
::makeTitle( NS_SPECIAL
, $localName );
1171 * Returns true if the title is inside the specified namespace.
1173 * Please make use of this instead of comparing to getNamespace()
1174 * This function is much more resistant to changes we may make
1175 * to namespaces than code that makes direct comparisons.
1176 * @param int $ns The namespace
1180 public function inNamespace( $ns ) {
1181 return MWNamespace
::equals( $this->mNamespace
, $ns );
1185 * Returns true if the title is inside one of the specified namespaces.
1187 * @param int|int[] $namespaces,... The namespaces to check for
1191 public function inNamespaces( /* ... */ ) {
1192 $namespaces = func_get_args();
1193 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1194 $namespaces = $namespaces[0];
1197 foreach ( $namespaces as $ns ) {
1198 if ( $this->inNamespace( $ns ) ) {
1207 * Returns true if the title has the same subject namespace as the
1208 * namespace specified.
1209 * For example this method will take NS_USER and return true if namespace
1210 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1211 * as their subject namespace.
1213 * This is MUCH simpler than individually testing for equivalence
1214 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1219 public function hasSubjectNamespace( $ns ) {
1220 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1224 * Is this Title in a namespace which contains content?
1225 * In other words, is this a content page, for the purposes of calculating
1230 public function isContentPage() {
1231 return MWNamespace
::isContent( $this->mNamespace
);
1235 * Would anybody with sufficient privileges be able to move this page?
1236 * Some pages just aren't movable.
1240 public function isMovable() {
1241 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1242 // Interwiki title or immovable namespace. Hooks don't get to override here
1247 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1252 * Is this the mainpage?
1253 * @note Title::newFromText seems to be sufficiently optimized by the title
1254 * cache that we don't need to over-optimize by doing direct comparisons and
1255 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1256 * ends up reporting something differently than $title->isMainPage();
1261 public function isMainPage() {
1262 return $this->equals( self
::newMainPage() );
1266 * Is this a subpage?
1270 public function isSubpage() {
1271 return MWNamespace
::hasSubpages( $this->mNamespace
)
1272 ?
strpos( $this->getText(), '/' ) !== false
1277 * Is this a conversion table for the LanguageConverter?
1281 public function isConversionTable() {
1282 // @todo ConversionTable should become a separate content model.
1284 return $this->mNamespace
== NS_MEDIAWIKI
&&
1285 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1289 * Does that page contain wikitext, or it is JS, CSS or whatever?
1293 public function isWikitextPage() {
1294 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1298 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1299 * global UI. This is generally true for pages in the MediaWiki namespace having
1300 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1302 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1305 * Note that this method should not return true for pages that contain and show
1306 * "inactive" CSS, JSON, or JS.
1311 public function isSiteConfigPage() {
1313 $this->isSiteCssConfigPage()
1314 ||
$this->isSiteJsonConfigPage()
1315 ||
$this->isSiteJsConfigPage()
1320 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1325 public function isUserConfigPage() {
1327 $this->isUserCssConfigPage()
1328 ||
$this->isUserJsonConfigPage()
1329 ||
$this->isUserJsConfigPage()
1334 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1336 * @return string Containing skin name from .css, .json, or .js subpage title
1339 public function getSkinFromConfigSubpage() {
1340 $subpage = explode( '/', $this->mTextform
);
1341 $subpage = $subpage[count( $subpage ) - 1];
1342 $lastdot = strrpos( $subpage, '.' );
1343 if ( $lastdot === false ) {
1344 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1346 return substr( $subpage, 0, $lastdot );
1350 * Is this a CSS "config" sub-page of a user page?
1355 public function isUserCssConfigPage() {
1357 NS_USER
== $this->mNamespace
1358 && $this->isSubpage()
1359 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1364 * Is this a JSON "config" sub-page of a user page?
1369 public function isUserJsonConfigPage() {
1371 NS_USER
== $this->mNamespace
1372 && $this->isSubpage()
1373 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1378 * Is this a JS "config" sub-page of a user page?
1383 public function isUserJsConfigPage() {
1385 NS_USER
== $this->mNamespace
1386 && $this->isSubpage()
1387 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1392 * Is this a sitewide CSS "config" page?
1397 public function isSiteCssConfigPage() {
1399 NS_MEDIAWIKI
== $this->mNamespace
1401 $this->hasContentModel( CONTENT_MODEL_CSS
)
1402 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1403 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1404 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1410 * Is this a sitewide JSON "config" page?
1415 public function isSiteJsonConfigPage() {
1417 NS_MEDIAWIKI
== $this->mNamespace
1419 $this->hasContentModel( CONTENT_MODEL_JSON
)
1420 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1421 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1422 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1428 * Is this a sitewide JS "config" page?
1433 public function isSiteJsConfigPage() {
1435 NS_MEDIAWIKI
== $this->mNamespace
1437 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1438 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1439 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1440 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1446 * Is this a message which can contain raw HTML?
1451 public function isRawHtmlMessage() {
1452 global $wgRawHtmlMessages;
1454 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1457 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1458 return in_array( $message, $wgRawHtmlMessages, true );
1462 * Is this a talk page of some sort?
1466 public function isTalkPage() {
1467 return MWNamespace
::isTalk( $this->mNamespace
);
1471 * Get a Title object associated with the talk page of this article
1473 * @return Title The object for the talk page
1475 public function getTalkPage() {
1476 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1480 * Get a Title object associated with the talk page of this article,
1481 * if such a talk page can exist.
1485 * @return Title|null The object for the talk page,
1486 * or null if no associated talk page can exist, according to canHaveTalkPage().
1488 public function getTalkPageIfDefined() {
1489 if ( !$this->canHaveTalkPage() ) {
1493 return $this->getTalkPage();
1497 * Get a title object associated with the subject page of this
1500 * @return Title The object for the subject page
1502 public function getSubjectPage() {
1503 // Is this the same title?
1504 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1505 if ( $this->mNamespace
== $subjectNS ) {
1508 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1512 * Get the other title for this page, if this is a subject page
1513 * get the talk page, if it is a subject page get the talk page
1516 * @throws MWException If the page doesn't have an other page
1519 public function getOtherPage() {
1520 if ( $this->isSpecialPage() ) {
1521 throw new MWException( 'Special pages cannot have other pages' );
1523 if ( $this->isTalkPage() ) {
1524 return $this->getSubjectPage();
1526 if ( !$this->canHaveTalkPage() ) {
1527 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1529 return $this->getTalkPage();
1534 * Get the default namespace index, for when there is no namespace
1536 * @return int Default namespace index
1538 public function getDefaultNamespace() {
1539 return $this->mDefaultNamespace
;
1543 * Get the Title fragment (i.e.\ the bit after the #) in text form
1545 * Use Title::hasFragment to check for a fragment
1547 * @return string Title fragment
1549 public function getFragment() {
1550 return $this->mFragment
;
1554 * Check if a Title fragment is set
1559 public function hasFragment() {
1560 return $this->mFragment
!== '';
1564 * Get the fragment in URL form, including the "#" character if there is one
1566 * @return string Fragment in URL form
1568 public function getFragmentForURL() {
1569 if ( !$this->hasFragment() ) {
1571 } elseif ( $this->isExternal() ) {
1572 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1573 // so we treat it like a local interwiki.
1574 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1575 if ( $interwiki && !$interwiki->isLocal() ) {
1576 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1580 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1584 * Set the fragment for this title. Removes the first character from the
1585 * specified fragment before setting, so it assumes you're passing it with
1588 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1589 * or Title::createFragmentTarget().
1590 * Still in active use privately.
1593 * @param string $fragment Text
1595 public function setFragment( $fragment ) {
1596 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1600 * Creates a new Title for a different fragment of the same page.
1603 * @param string $fragment
1606 public function createFragmentTarget( $fragment ) {
1607 return self
::makeTitle(
1616 * Prefix some arbitrary text with the namespace or interwiki prefix
1619 * @param string $name The text
1620 * @return string The prefixed text
1622 private function prefix( $name ) {
1624 if ( $this->isExternal() ) {
1625 $p = $this->mInterwiki
. ':';
1628 if ( $this->mNamespace
!= 0 ) {
1629 $nsText = $this->getNsText();
1631 if ( $nsText === false ) {
1632 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1633 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1634 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1637 $p .= $nsText . ':';
1643 * Get the prefixed database key form
1645 * @return string The prefixed title, with underscores and
1646 * any interwiki and namespace prefixes
1648 public function getPrefixedDBkey() {
1649 $s = $this->prefix( $this->mDbkeyform
);
1650 $s = strtr( $s, ' ', '_' );
1655 * Get the prefixed title with spaces.
1656 * This is the form usually used for display
1658 * @return string The prefixed title, with spaces
1660 public function getPrefixedText() {
1661 if ( $this->prefixedText
=== null ) {
1662 $s = $this->prefix( $this->mTextform
);
1663 $s = strtr( $s, '_', ' ' );
1664 $this->prefixedText
= $s;
1666 return $this->prefixedText
;
1670 * Return a string representation of this title
1672 * @return string Representation of this title
1674 public function __toString() {
1675 return $this->getPrefixedText();
1679 * Get the prefixed title with spaces, plus any fragment
1680 * (part beginning with '#')
1682 * @return string The prefixed title, with spaces and the fragment, including '#'
1684 public function getFullText() {
1685 $text = $this->getPrefixedText();
1686 if ( $this->hasFragment() ) {
1687 $text .= '#' . $this->mFragment
;
1693 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1697 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1701 * @return string Root name
1704 public function getRootText() {
1705 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1706 return $this->getText();
1709 return strtok( $this->getText(), '/' );
1713 * Get the root page name title, i.e. the leftmost part before any slashes
1717 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1718 * # returns: Title{User:Foo}
1721 * @return Title Root title
1724 public function getRootTitle() {
1725 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1729 * Get the base page name without a namespace, i.e. the part before the subpage name
1733 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1734 * # returns: 'Foo/Bar'
1737 * @return string Base name
1739 public function getBaseText() {
1740 $text = $this->getText();
1741 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1745 $lastSlashPos = strrpos( $text, '/' );
1746 // Don't discard the real title if there's no subpage involved
1747 if ( $lastSlashPos === false ) {
1751 return substr( $text, 0, $lastSlashPos );
1755 * Get the base page name title, i.e. the part before the subpage name
1759 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1760 * # returns: Title{User:Foo/Bar}
1763 * @return Title Base title
1766 public function getBaseTitle() {
1767 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1771 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1775 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1779 * @return string Subpage name
1781 public function getSubpageText() {
1782 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1783 return $this->mTextform
;
1785 $parts = explode( '/', $this->mTextform
);
1786 return $parts[count( $parts ) - 1];
1790 * Get the title for a subpage of the current page
1794 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1795 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1798 * @param string $text The subpage name to add to the title
1799 * @return Title|null Subpage title, or null on an error
1802 public function getSubpage( $text ) {
1803 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1807 * Get a URL-encoded form of the subpage text
1809 * @return string URL-encoded subpage name
1811 public function getSubpageUrlForm() {
1812 $text = $this->getSubpageText();
1813 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1818 * Get a URL-encoded title (not an actual URL) including interwiki
1820 * @return string The URL-encoded form
1822 public function getPrefixedURL() {
1823 $s = $this->prefix( $this->mDbkeyform
);
1824 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1829 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1830 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1831 * second argument named variant. This was deprecated in favor
1832 * of passing an array of option with a "variant" key
1833 * Once $query2 is removed for good, this helper can be dropped
1834 * and the wfArrayToCgi moved to getLocalURL();
1836 * @since 1.19 (r105919)
1837 * @param array|string $query
1838 * @param string|string[]|bool $query2
1841 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1842 if ( $query2 !== false ) {
1843 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1844 "method called with a second parameter is deprecated. Add your " .
1845 "parameter to an array passed as the first parameter.", "1.19" );
1847 if ( is_array( $query ) ) {
1848 $query = wfArrayToCgi( $query );
1851 if ( is_string( $query2 ) ) {
1852 // $query2 is a string, we will consider this to be
1853 // a deprecated $variant argument and add it to the query
1854 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1856 $query2 = wfArrayToCgi( $query2 );
1858 // If we have $query content add a & to it first
1862 // Now append the queries together
1869 * Get a real URL referring to this title, with interwiki link and
1872 * @see self::getLocalURL for the arguments.
1874 * @param string|string[] $query
1875 * @param string|string[]|bool $query2
1876 * @param string|int|null $proto Protocol type to use in URL
1877 * @return string The URL
1879 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1880 $query = self
::fixUrlQueryArgs( $query, $query2 );
1882 # Hand off all the decisions on urls to getLocalURL
1883 $url = $this->getLocalURL( $query );
1885 # Expand the url to make it a full url. Note that getLocalURL has the
1886 # potential to output full urls for a variety of reasons, so we use
1887 # wfExpandUrl instead of simply prepending $wgServer
1888 $url = wfExpandUrl( $url, $proto );
1890 # Finally, add the fragment.
1891 $url .= $this->getFragmentForURL();
1892 // Avoid PHP 7.1 warning from passing $this by reference
1894 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1899 * Get a url appropriate for making redirects based on an untrusted url arg
1901 * This is basically the same as getFullUrl(), but in the case of external
1902 * interwikis, we send the user to a landing page, to prevent possible
1903 * phishing attacks and the like.
1905 * @note Uses current protocol by default, since technically relative urls
1906 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1907 * places where the url gets cached, as might pollute between
1908 * https and non-https users.
1909 * @see self::getLocalURL for the arguments.
1910 * @param array|string $query
1911 * @param string $proto Protocol type to use in URL
1912 * @return string A url suitable to use in an HTTP location header.
1914 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1916 if ( $this->isExternal() ) {
1917 $target = SpecialPage
::getTitleFor(
1919 $this->getPrefixedDBkey()
1922 return $target->getFullURL( $query, false, $proto );
1926 * Get a URL with no fragment or server name (relative URL) from a Title object.
1927 * If this page is generated with action=render, however,
1928 * $wgServer is prepended to make an absolute URL.
1930 * @see self::getFullURL to always get an absolute URL.
1931 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1932 * valid to link, locally, to the current Title.
1933 * @see self::newFromText to produce a Title object.
1935 * @param string|string[] $query An optional query string,
1936 * not used for interwiki links. Can be specified as an associative array as well,
1937 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1938 * Some query patterns will trigger various shorturl path replacements.
1939 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1940 * be an array. If a string is passed it will be interpreted as a deprecated
1941 * variant argument and urlencoded into a variant= argument.
1942 * This second query argument will be added to the $query
1943 * The second parameter is deprecated since 1.19. Pass it as a key,value
1944 * pair in the first parameter array instead.
1946 * @return string String of the URL.
1948 public function getLocalURL( $query = '', $query2 = false ) {
1949 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1951 $query = self
::fixUrlQueryArgs( $query, $query2 );
1953 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1955 $namespace = $this->getNsText();
1956 if ( $namespace != '' ) {
1957 # Can this actually happen? Interwikis shouldn't be parsed.
1958 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1961 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1962 $url = wfAppendQuery( $url, $query );
1964 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1965 if ( $query == '' ) {
1966 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1967 // Avoid PHP 7.1 warning from passing $this by reference
1969 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1971 global $wgVariantArticlePath, $wgActionPaths;
1975 if ( !empty( $wgActionPaths )
1976 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1978 $action = urldecode( $matches[2] );
1979 if ( isset( $wgActionPaths[$action] ) ) {
1980 $query = $matches[1];
1981 if ( isset( $matches[4] ) ) {
1982 $query .= $matches[4];
1984 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1985 if ( $query != '' ) {
1986 $url = wfAppendQuery( $url, $query );
1992 && $wgVariantArticlePath
1993 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1994 && $this->getPageLanguage()->equals(
1995 MediaWikiServices
::getInstance()->getContentLanguage() )
1996 && $this->getPageLanguage()->hasVariants()
1998 $variant = urldecode( $matches[1] );
1999 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2000 // Only do the variant replacement if the given variant is a valid
2001 // variant for the page's language.
2002 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2003 $url = str_replace( '$1', $dbkey, $url );
2007 if ( $url === false ) {
2008 if ( $query == '-' ) {
2011 $url = "{$wgScript}?title={$dbkey}&{$query}";
2014 // Avoid PHP 7.1 warning from passing $this by reference
2016 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2018 // @todo FIXME: This causes breakage in various places when we
2019 // actually expected a local URL and end up with dupe prefixes.
2020 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2021 $url = $wgServer . $url;
2024 // Avoid PHP 7.1 warning from passing $this by reference
2026 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2031 * Get a URL that's the simplest URL that will be valid to link, locally,
2032 * to the current Title. It includes the fragment, but does not include
2033 * the server unless action=render is used (or the link is external). If
2034 * there's a fragment but the prefixed text is empty, we just return a link
2037 * The result obviously should not be URL-escaped, but does need to be
2038 * HTML-escaped if it's being output in HTML.
2040 * @param string|string[] $query
2041 * @param bool $query2
2042 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2043 * or false (default) for no expansion
2044 * @see self::getLocalURL for the arguments.
2045 * @return string The URL
2047 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2048 if ( $this->isExternal() ||
$proto !== false ) {
2049 $ret = $this->getFullURL( $query, $query2, $proto );
2050 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2051 $ret = $this->getFragmentForURL();
2053 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2059 * Get the URL form for an internal link.
2060 * - Used in various CDN-related code, in case we have a different
2061 * internal hostname for the server from the exposed one.
2063 * This uses $wgInternalServer to qualify the path, or $wgServer
2064 * if $wgInternalServer is not set. If the server variable used is
2065 * protocol-relative, the URL will be expanded to http://
2067 * @see self::getLocalURL for the arguments.
2068 * @param string|string[] $query
2069 * @param string|bool $query2 Deprecated
2070 * @return string The URL
2072 public function getInternalURL( $query = '', $query2 = false ) {
2073 global $wgInternalServer, $wgServer;
2074 $query = self
::fixUrlQueryArgs( $query, $query2 );
2075 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2076 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2077 // Avoid PHP 7.1 warning from passing $this by reference
2079 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2084 * Get the URL for a canonical link, for use in things like IRC and
2085 * e-mail notifications. Uses $wgCanonicalServer and the
2086 * GetCanonicalURL hook.
2088 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2090 * @see self::getLocalURL for the arguments.
2091 * @param string|string[] $query
2092 * @param string|bool $query2 Deprecated
2093 * @return string The URL
2096 public function getCanonicalURL( $query = '', $query2 = false ) {
2097 $query = self
::fixUrlQueryArgs( $query, $query2 );
2098 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2099 // Avoid PHP 7.1 warning from passing $this by reference
2101 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2106 * Get the edit URL for this Title
2108 * @return string The URL, or a null string if this is an interwiki link
2110 public function getEditURL() {
2111 if ( $this->isExternal() ) {
2114 $s = $this->getLocalURL( 'action=edit' );
2120 * Can $user perform $action on this page?
2121 * This skips potentially expensive cascading permission checks
2122 * as well as avoids expensive error formatting
2124 * Suitable for use for nonessential UI controls in common cases, but
2125 * _not_ for functional access control.
2127 * May provide false positives, but should never provide a false negative.
2129 * @param string $action Action that permission needs to be checked for
2130 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2135 * @deprecated since 1.33,
2136 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2139 public function quickUserCan( $action, $user = null ) {
2140 return $this->userCan( $action, $user, false );
2144 * Can $user perform $action on this page?
2146 * @param string $action Action that permission needs to be checked for
2147 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2149 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2154 * @deprecated since 1.33,
2155 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2158 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2159 if ( !$user instanceof User
) {
2164 // TODO: this is for b/c, eventually will be removed
2165 if ( $rigor === true ) {
2166 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2167 } elseif ( $rigor === false ) {
2168 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2171 return MediaWikiServices
::getInstance()->getPermissionManager()
2172 ->userCan( $action, $user, $this, $rigor );
2176 * Can $user perform $action on this page?
2178 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2180 * @param string $action Action that permission needs to be checked for
2181 * @param User $user User to check
2182 * @param string $rigor One of (quick,full,secure)
2183 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2184 * - full : does cheap and expensive checks possibly from a replica DB
2185 * - secure : does cheap and expensive checks, using the master as needed
2186 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2187 * whose corresponding errors may be ignored.
2189 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2192 * @deprecated since 1.33,
2193 * use MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissionsErrors()
2196 public function getUserPermissionsErrors(
2197 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2199 // TODO: this is for b/c, eventually will be removed
2200 if ( $rigor === true ) {
2201 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2202 } elseif ( $rigor === false ) {
2203 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2206 return MediaWikiServices
::getInstance()->getPermissionManager()
2207 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2211 * Add the resulting error code to the errors array
2213 * @param array $errors List of current errors
2214 * @param array $result Result of errors
2216 * @return array List of errors
2218 private function resultToError( $errors, $result ) {
2219 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2220 // A single array representing an error
2221 $errors[] = $result;
2222 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2223 // A nested array representing multiple errors
2224 $errors = array_merge( $errors, $result );
2225 } elseif ( $result !== '' && is_string( $result ) ) {
2226 // A string representing a message-id
2227 $errors[] = [ $result ];
2228 } elseif ( $result instanceof MessageSpecifier
) {
2229 // A message specifier representing an error
2230 $errors[] = [ $result ];
2231 } elseif ( $result === false ) {
2232 // a generic "We don't want them to do that"
2233 $errors[] = [ 'badaccess-group0' ];
2239 * Get a filtered list of all restriction types supported by this wiki.
2240 * @param bool $exists True to get all restriction types that apply to
2241 * titles that do exist, False for all restriction types that apply to
2242 * titles that do not exist
2245 public static function getFilteredRestrictionTypes( $exists = true ) {
2246 global $wgRestrictionTypes;
2247 $types = $wgRestrictionTypes;
2249 # Remove the create restriction for existing titles
2250 $types = array_diff( $types, [ 'create' ] );
2252 # Only the create and upload restrictions apply to non-existing titles
2253 $types = array_intersect( $types, [ 'create', 'upload' ] );
2259 * Returns restriction types for the current Title
2261 * @return array Applicable restriction types
2263 public function getRestrictionTypes() {
2264 if ( $this->isSpecialPage() ) {
2268 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2270 if ( $this->mNamespace
!= NS_FILE
) {
2271 # Remove the upload restriction for non-file titles
2272 $types = array_diff( $types, [ 'upload' ] );
2275 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2277 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2278 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2284 * Is this title subject to title protection?
2285 * Title protection is the one applied against creation of such title.
2287 * @return array|bool An associative array representing any existent title
2288 * protection, or false if there's none.
2290 public function getTitleProtection() {
2291 $protection = $this->getTitleProtectionInternal();
2292 if ( $protection ) {
2293 if ( $protection['permission'] == 'sysop' ) {
2294 $protection['permission'] = 'editprotected'; // B/C
2296 if ( $protection['permission'] == 'autoconfirmed' ) {
2297 $protection['permission'] = 'editsemiprotected'; // B/C
2304 * Fetch title protection settings
2306 * To work correctly, $this->loadRestrictions() needs to have access to the
2307 * actual protections in the database without munging 'sysop' =>
2308 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2309 * callers probably want $this->getTitleProtection() instead.
2311 * @return array|bool
2313 protected function getTitleProtectionInternal() {
2314 // Can't protect pages in special namespaces
2315 if ( $this->mNamespace
< 0 ) {
2319 // Can't protect pages that exist.
2320 if ( $this->exists() ) {
2324 if ( $this->mTitleProtection
=== null ) {
2325 $dbr = wfGetDB( DB_REPLICA
);
2326 $commentStore = CommentStore
::getStore();
2327 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2328 $res = $dbr->select(
2329 [ 'protected_titles' ] +
$commentQuery['tables'],
2331 'user' => 'pt_user',
2332 'expiry' => 'pt_expiry',
2333 'permission' => 'pt_create_perm'
2334 ] +
$commentQuery['fields'],
2335 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2338 $commentQuery['joins']
2341 // fetchRow returns false if there are no rows.
2342 $row = $dbr->fetchRow( $res );
2344 $this->mTitleProtection
= [
2345 'user' => $row['user'],
2346 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2347 'permission' => $row['permission'],
2348 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2351 $this->mTitleProtection
= false;
2354 return $this->mTitleProtection
;
2358 * Remove any title protection due to page existing
2360 public function deleteTitleProtection() {
2361 $dbw = wfGetDB( DB_MASTER
);
2365 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2368 $this->mTitleProtection
= false;
2372 * Is this page "semi-protected" - the *only* protection levels are listed
2373 * in $wgSemiprotectedRestrictionLevels?
2375 * @param string $action Action to check (default: edit)
2378 public function isSemiProtected( $action = 'edit' ) {
2379 global $wgSemiprotectedRestrictionLevels;
2381 $restrictions = $this->getRestrictions( $action );
2382 $semi = $wgSemiprotectedRestrictionLevels;
2383 if ( !$restrictions ||
!$semi ) {
2384 // Not protected, or all protection is full protection
2388 // Remap autoconfirmed to editsemiprotected for BC
2389 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2390 $semi[$key] = 'editsemiprotected';
2392 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2393 $restrictions[$key] = 'editsemiprotected';
2396 return !array_diff( $restrictions, $semi );
2400 * Does the title correspond to a protected article?
2402 * @param string $action The action the page is protected from,
2403 * by default checks all actions.
2406 public function isProtected( $action = '' ) {
2407 global $wgRestrictionLevels;
2409 $restrictionTypes = $this->getRestrictionTypes();
2411 # Special pages have inherent protection
2412 if ( $this->isSpecialPage() ) {
2416 # Check regular protection levels
2417 foreach ( $restrictionTypes as $type ) {
2418 if ( $action == $type ||
$action == '' ) {
2419 $r = $this->getRestrictions( $type );
2420 foreach ( $wgRestrictionLevels as $level ) {
2421 if ( in_array( $level, $r ) && $level != '' ) {
2432 * Determines if $user is unable to edit this page because it has been protected
2433 * by $wgNamespaceProtection.
2435 * @param User $user User object to check permissions
2438 public function isNamespaceProtected( User
$user ) {
2439 global $wgNamespaceProtection;
2441 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2442 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2443 if ( $right != '' && !$user->isAllowed( $right ) ) {
2452 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2454 * @return bool If the page is subject to cascading restrictions.
2456 public function isCascadeProtected() {
2457 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2458 return ( $sources > 0 );
2462 * Determines whether cascading protection sources have already been loaded from
2465 * @param bool $getPages True to check if the pages are loaded, or false to check
2466 * if the status is loaded.
2467 * @return bool Whether or not the specified information has been loaded
2470 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2471 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2475 * Cascading protection: Get the source of any cascading restrictions on this page.
2477 * @param bool $getPages Whether or not to retrieve the actual pages
2478 * that the restrictions have come from and the actual restrictions
2480 * @return array Two elements: First is an array of Title objects of the
2481 * pages from which cascading restrictions have come, false for
2482 * none, or true if such restrictions exist but $getPages was not
2483 * set. Second is an array like that returned by
2484 * Title::getAllRestrictions(), or an empty array if $getPages is
2487 public function getCascadeProtectionSources( $getPages = true ) {
2488 $pagerestrictions = [];
2490 if ( $this->mCascadeSources
!== null && $getPages ) {
2491 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2492 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2493 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2496 $dbr = wfGetDB( DB_REPLICA
);
2498 if ( $this->mNamespace
== NS_FILE
) {
2499 $tables = [ 'imagelinks', 'page_restrictions' ];
2501 'il_to' => $this->mDbkeyform
,
2506 $tables = [ 'templatelinks', 'page_restrictions' ];
2508 'tl_namespace' => $this->mNamespace
,
2509 'tl_title' => $this->mDbkeyform
,
2516 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2517 'pr_expiry', 'pr_type', 'pr_level' ];
2518 $where_clauses[] = 'page_id=pr_page';
2521 $cols = [ 'pr_expiry' ];
2524 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2526 $sources = $getPages ?
[] : false;
2527 $now = wfTimestampNow();
2529 foreach ( $res as $row ) {
2530 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2531 if ( $expiry > $now ) {
2533 $page_id = $row->pr_page
;
2534 $page_ns = $row->page_namespace
;
2535 $page_title = $row->page_title
;
2536 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2537 # Add groups needed for each restriction type if its not already there
2538 # Make sure this restriction type still exists
2540 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2541 $pagerestrictions[$row->pr_type
] = [];
2545 isset( $pagerestrictions[$row->pr_type
] )
2546 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2548 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2557 $this->mCascadeSources
= $sources;
2558 $this->mCascadingRestrictions
= $pagerestrictions;
2560 $this->mHasCascadingRestrictions
= $sources;
2563 return [ $sources, $pagerestrictions ];
2567 * Accessor for mRestrictionsLoaded
2569 * @return bool Whether or not the page's restrictions have already been
2570 * loaded from the database
2573 public function areRestrictionsLoaded() {
2574 return $this->mRestrictionsLoaded
;
2578 * Accessor/initialisation for mRestrictions
2580 * @param string $action Action that permission needs to be checked for
2581 * @return array Restriction levels needed to take the action. All levels are
2582 * required. Note that restriction levels are normally user rights, but 'sysop'
2583 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2584 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2586 public function getRestrictions( $action ) {
2587 if ( !$this->mRestrictionsLoaded
) {
2588 $this->loadRestrictions();
2590 return $this->mRestrictions
[$action] ??
[];
2594 * Accessor/initialisation for mRestrictions
2596 * @return array Keys are actions, values are arrays as returned by
2597 * Title::getRestrictions()
2600 public function getAllRestrictions() {
2601 if ( !$this->mRestrictionsLoaded
) {
2602 $this->loadRestrictions();
2604 return $this->mRestrictions
;
2608 * Get the expiry time for the restriction against a given action
2610 * @param string $action
2611 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2612 * or not protected at all, or false if the action is not recognised.
2614 public function getRestrictionExpiry( $action ) {
2615 if ( !$this->mRestrictionsLoaded
) {
2616 $this->loadRestrictions();
2618 return $this->mRestrictionsExpiry
[$action] ??
false;
2622 * Returns cascading restrictions for the current article
2626 function areRestrictionsCascading() {
2627 if ( !$this->mRestrictionsLoaded
) {
2628 $this->loadRestrictions();
2631 return $this->mCascadeRestriction
;
2635 * Compiles list of active page restrictions from both page table (pre 1.10)
2636 * and page_restrictions table for this existing page.
2637 * Public for usage by LiquidThreads.
2639 * @param array $rows Array of db result objects
2640 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2641 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2642 * Edit and move sections are separated by a colon
2643 * Example: "edit=autoconfirmed,sysop:move=sysop"
2645 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2646 // This function will only read rows from a table that we migrated away
2647 // from before adding READ_LATEST support to loadRestrictions, so we
2648 // don't need to support reading from DB_MASTER here.
2649 $dbr = wfGetDB( DB_REPLICA
);
2651 $restrictionTypes = $this->getRestrictionTypes();
2653 foreach ( $restrictionTypes as $type ) {
2654 $this->mRestrictions
[$type] = [];
2655 $this->mRestrictionsExpiry
[$type] = 'infinity';
2658 $this->mCascadeRestriction
= false;
2660 # Backwards-compatibility: also load the restrictions from the page record (old format).
2661 if ( $oldFashionedRestrictions !== null ) {
2662 $this->mOldRestrictions
= $oldFashionedRestrictions;
2665 if ( $this->mOldRestrictions
=== false ) {
2666 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2667 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2668 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2671 if ( $this->mOldRestrictions
!= '' ) {
2672 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2673 $temp = explode( '=', trim( $restrict ) );
2674 if ( count( $temp ) == 1 ) {
2675 // old old format should be treated as edit/move restriction
2676 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2677 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2679 $restriction = trim( $temp[1] );
2680 if ( $restriction != '' ) { // some old entries are empty
2681 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2687 if ( count( $rows ) ) {
2688 # Current system - load second to make them override.
2689 $now = wfTimestampNow();
2691 # Cycle through all the restrictions.
2692 foreach ( $rows as $row ) {
2693 // Don't take care of restrictions types that aren't allowed
2694 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2698 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2700 // Only apply the restrictions if they haven't expired!
2701 if ( !$expiry ||
$expiry > $now ) {
2702 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2703 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2705 $this->mCascadeRestriction |
= $row->pr_cascade
;
2710 $this->mRestrictionsLoaded
= true;
2714 * Load restrictions from the page_restrictions table
2716 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2717 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2718 * Edit and move sections are separated by a colon
2719 * Example: "edit=autoconfirmed,sysop:move=sysop"
2720 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2721 * from the master DB.
2723 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2724 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2725 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2729 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2730 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2731 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2732 $id = $this->getArticleID();
2734 $fname = __METHOD__
;
2735 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2736 return iterator_to_array(
2738 'page_restrictions',
2739 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2740 [ 'pr_page' => $id ],
2746 if ( $readLatest ) {
2747 $dbr = wfGetDB( DB_MASTER
);
2748 $rows = $loadRestrictionsFromDb( $dbr );
2750 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2751 $rows = $cache->getWithSetCallback(
2752 // Page protections always leave a new null revision
2753 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2755 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2756 $dbr = wfGetDB( DB_REPLICA
);
2758 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2759 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2760 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2761 // @TODO: cleanup Title cache and caller assumption mess in general
2762 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2765 return $loadRestrictionsFromDb( $dbr );
2770 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2772 $title_protection = $this->getTitleProtectionInternal();
2774 if ( $title_protection ) {
2775 $now = wfTimestampNow();
2776 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2778 if ( !$expiry ||
$expiry > $now ) {
2779 // Apply the restrictions
2780 $this->mRestrictionsExpiry
['create'] = $expiry;
2781 $this->mRestrictions
['create'] =
2782 explode( ',', trim( $title_protection['permission'] ) );
2783 } else { // Get rid of the old restrictions
2784 $this->mTitleProtection
= false;
2787 $this->mRestrictionsExpiry
['create'] = 'infinity';
2789 $this->mRestrictionsLoaded
= true;
2794 * Flush the protection cache in this object and force reload from the database.
2795 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2797 public function flushRestrictions() {
2798 $this->mRestrictionsLoaded
= false;
2799 $this->mTitleProtection
= null;
2803 * Purge expired restrictions from the page_restrictions table
2805 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2807 static function purgeExpiredRestrictions() {
2808 if ( wfReadOnly() ) {
2812 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2813 wfGetDB( DB_MASTER
),
2815 function ( IDatabase
$dbw, $fname ) {
2816 $config = MediaWikiServices
::getInstance()->getMainConfig();
2817 $ids = $dbw->selectFieldValues(
2818 'page_restrictions',
2820 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2822 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2825 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2830 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2831 wfGetDB( DB_MASTER
),
2833 function ( IDatabase
$dbw, $fname ) {
2836 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2844 * Does this have subpages? (Warning, usually requires an extra DB query.)
2848 public function hasSubpages() {
2849 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2854 # We dynamically add a member variable for the purpose of this method
2855 # alone to cache the result. There's no point in having it hanging
2856 # around uninitialized in every Title object; therefore we only add it
2857 # if needed and don't declare it statically.
2858 if ( $this->mHasSubpages
=== null ) {
2859 $this->mHasSubpages
= false;
2860 $subpages = $this->getSubpages( 1 );
2861 if ( $subpages instanceof TitleArray
) {
2862 $this->mHasSubpages
= (bool)$subpages->count();
2866 return $this->mHasSubpages
;
2870 * Get all subpages of this page.
2872 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2873 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2874 * doesn't allow subpages
2876 public function getSubpages( $limit = -1 ) {
2877 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2881 $dbr = wfGetDB( DB_REPLICA
);
2882 $conds['page_namespace'] = $this->mNamespace
;
2883 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2885 if ( $limit > -1 ) {
2886 $options['LIMIT'] = $limit;
2888 return TitleArray
::newFromResult(
2889 $dbr->select( 'page',
2890 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2899 * Is there a version of this page in the deletion archive?
2901 * @return int The number of archived revisions
2903 public function isDeleted() {
2904 if ( $this->mNamespace
< 0 ) {
2907 $dbr = wfGetDB( DB_REPLICA
);
2909 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2910 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2913 if ( $this->mNamespace
== NS_FILE
) {
2914 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2915 [ 'fa_name' => $this->mDbkeyform
],
2924 * Is there a version of this page in the deletion archive?
2928 public function isDeletedQuick() {
2929 if ( $this->mNamespace
< 0 ) {
2932 $dbr = wfGetDB( DB_REPLICA
);
2933 $deleted = (bool)$dbr->selectField( 'archive', '1',
2934 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2937 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
2938 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2939 [ 'fa_name' => $this->mDbkeyform
],
2947 * Get the article ID for this Title from the link cache,
2948 * adding it if necessary
2950 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
2952 * @return int The ID
2954 public function getArticleID( $flags = 0 ) {
2955 if ( $this->mNamespace
< 0 ) {
2956 $this->mArticleID
= 0;
2957 return $this->mArticleID
;
2959 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2960 if ( $flags & self
::GAID_FOR_UPDATE
) {
2961 $oldUpdate = $linkCache->forUpdate( true );
2962 $linkCache->clearLink( $this );
2963 $this->mArticleID
= $linkCache->addLinkObj( $this );
2964 $linkCache->forUpdate( $oldUpdate );
2965 } elseif ( $this->mArticleID
== -1 ) {
2966 $this->mArticleID
= $linkCache->addLinkObj( $this );
2968 return $this->mArticleID
;
2972 * Is this an article that is a redirect page?
2973 * Uses link cache, adding it if necessary
2975 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
2978 public function isRedirect( $flags = 0 ) {
2979 if ( !is_null( $this->mRedirect
) ) {
2980 return $this->mRedirect
;
2982 if ( !$this->getArticleID( $flags ) ) {
2983 $this->mRedirect
= false;
2984 return $this->mRedirect
;
2987 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2988 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2989 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2990 if ( $cached === null ) {
2991 # Trust LinkCache's state over our own
2992 # LinkCache is telling us that the page doesn't exist, despite there being cached
2993 # data relating to an existing page in $this->mArticleID. Updaters should clear
2994 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
2995 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
2996 # LinkCache to refresh its data from the master.
2997 $this->mRedirect
= false;
2998 return $this->mRedirect
;
3001 $this->mRedirect
= (bool)$cached;
3003 return $this->mRedirect
;
3007 * What is the length of this page?
3008 * Uses link cache, adding it if necessary
3010 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3013 public function getLength( $flags = 0 ) {
3014 if ( $this->mLength
!= -1 ) {
3015 return $this->mLength
;
3017 if ( !$this->getArticleID( $flags ) ) {
3019 return $this->mLength
;
3021 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3022 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3023 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3024 if ( $cached === null ) {
3025 # Trust LinkCache's state over our own, as for isRedirect()
3027 return $this->mLength
;
3030 $this->mLength
= intval( $cached );
3032 return $this->mLength
;
3036 * What is the page_latest field for this page?
3038 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3039 * @return int Int or 0 if the page doesn't exist
3041 public function getLatestRevID( $flags = 0 ) {
3042 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3043 return intval( $this->mLatestID
);
3045 if ( !$this->getArticleID( $flags ) ) {
3046 $this->mLatestID
= 0;
3047 return $this->mLatestID
;
3049 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3050 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3051 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3052 if ( $cached === null ) {
3053 # Trust LinkCache's state over our own, as for isRedirect()
3054 $this->mLatestID
= 0;
3055 return $this->mLatestID
;
3058 $this->mLatestID
= intval( $cached );
3060 return $this->mLatestID
;
3064 * This clears some fields in this object, and clears any associated
3065 * keys in the "bad links" section of the link cache.
3067 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3068 * loading of the new page_id. It's also called from
3069 * WikiPage::doDeleteArticleReal()
3071 * @param int $newid The new Article ID
3073 public function resetArticleID( $newid ) {
3074 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3075 $linkCache->clearLink( $this );
3077 if ( $newid === false ) {
3078 $this->mArticleID
= -1;
3080 $this->mArticleID
= intval( $newid );
3082 $this->mRestrictionsLoaded
= false;
3083 $this->mRestrictions
= [];
3084 $this->mOldRestrictions
= false;
3085 $this->mRedirect
= null;
3086 $this->mLength
= -1;
3087 $this->mLatestID
= false;
3088 $this->mContentModel
= false;
3089 $this->mEstimateRevisions
= null;
3090 $this->mPageLanguage
= false;
3091 $this->mDbPageLanguage
= false;
3092 $this->mIsBigDeletion
= null;
3095 public static function clearCaches() {
3096 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3097 $linkCache->clear();
3099 $titleCache = self
::getTitleCache();
3100 $titleCache->clear();
3104 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3106 * @param string $text Containing title to capitalize
3107 * @param int $ns Namespace index, defaults to NS_MAIN
3108 * @return string Containing capitalized title
3110 public static function capitalize( $text, $ns = NS_MAIN
) {
3111 if ( MWNamespace
::isCapitalized( $ns ) ) {
3112 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3119 * Secure and split - main initialisation function for this object
3121 * Assumes that mDbkeyform has been set, and is urldecoded
3122 * and uses underscores, but not otherwise munged. This function
3123 * removes illegal characters, splits off the interwiki and
3124 * namespace prefixes, sets the other forms, and canonicalizes
3127 * @throws MalformedTitleException On invalid titles
3128 * @return bool True on success
3130 private function secureAndSplit() {
3131 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3132 // the parsing code with Title, while avoiding massive refactoring.
3133 // @todo: get rid of secureAndSplit, refactor parsing code.
3134 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3135 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3136 /** @var MediaWikiTitleCodec $titleCodec */
3137 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3138 // MalformedTitleException can be thrown here
3139 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3142 $this->setFragment( '#' . $parts['fragment'] );
3143 $this->mInterwiki
= $parts['interwiki'];
3144 $this->mLocalInterwiki
= $parts['local_interwiki'];
3145 $this->mNamespace
= $parts['namespace'];
3146 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3148 $this->mDbkeyform
= $parts['dbkey'];
3149 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3150 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3152 # We already know that some pages won't be in the database!
3153 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3154 $this->mArticleID
= 0;
3161 * Get an array of Title objects linking to this Title
3162 * Also stores the IDs in the link cache.
3164 * WARNING: do not use this function on arbitrary user-supplied titles!
3165 * On heavily-used templates it will max out the memory.
3167 * @param array $options May be FOR UPDATE
3168 * @param string $table Table name
3169 * @param string $prefix Fields prefix
3170 * @return Title[] Array of Title objects linking here
3172 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3173 if ( count( $options ) > 0 ) {
3174 $db = wfGetDB( DB_MASTER
);
3176 $db = wfGetDB( DB_REPLICA
);
3181 self
::getSelectFields(),
3183 "{$prefix}_from=page_id",
3184 "{$prefix}_namespace" => $this->mNamespace
,
3185 "{$prefix}_title" => $this->mDbkeyform
],
3191 if ( $res->numRows() ) {
3192 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3193 foreach ( $res as $row ) {
3194 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3196 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3197 $retVal[] = $titleObj;
3205 * Get an array of Title objects using this Title as a template
3206 * Also stores the IDs in the link cache.
3208 * WARNING: do not use this function on arbitrary user-supplied titles!
3209 * On heavily-used templates it will max out the memory.
3211 * @param array $options Query option to Database::select()
3212 * @return Title[] Array of Title the Title objects linking here
3214 public function getTemplateLinksTo( $options = [] ) {
3215 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3219 * Get an array of Title objects linked from this Title
3220 * Also stores the IDs in the link cache.
3222 * WARNING: do not use this function on arbitrary user-supplied titles!
3223 * On heavily-used templates it will max out the memory.
3225 * @param array $options Query option to Database::select()
3226 * @param string $table Table name
3227 * @param string $prefix Fields prefix
3228 * @return array Array of Title objects linking here
3230 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3231 $id = $this->getArticleID();
3233 # If the page doesn't exist; there can't be any link from this page
3238 $db = wfGetDB( DB_REPLICA
);
3240 $blNamespace = "{$prefix}_namespace";
3241 $blTitle = "{$prefix}_title";
3243 $pageQuery = WikiPage
::getQueryInfo();
3245 [ $table, 'nestpage' => $pageQuery['tables'] ],
3247 [ $blNamespace, $blTitle ],
3248 $pageQuery['fields']
3250 [ "{$prefix}_from" => $id ],
3255 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3256 ] ] +
$pageQuery['joins']
3260 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3261 foreach ( $res as $row ) {
3262 if ( $row->page_id
) {
3263 $titleObj = self
::newFromRow( $row );
3265 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3266 $linkCache->addBadLinkObj( $titleObj );
3268 $retVal[] = $titleObj;
3275 * Get an array of Title objects used on this Title as a template
3276 * Also stores the IDs in the link cache.
3278 * WARNING: do not use this function on arbitrary user-supplied titles!
3279 * On heavily-used templates it will max out the memory.
3281 * @param array $options May be FOR UPDATE
3282 * @return Title[] Array of Title the Title objects used here
3284 public function getTemplateLinksFrom( $options = [] ) {
3285 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3289 * Get an array of Title objects referring to non-existent articles linked
3292 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3293 * should use redirect table in this case).
3294 * @return Title[] Array of Title the Title objects
3296 public function getBrokenLinksFrom() {
3297 if ( $this->getArticleID() == 0 ) {
3298 # All links from article ID 0 are false positives
3302 $dbr = wfGetDB( DB_REPLICA
);
3303 $res = $dbr->select(
3304 [ 'page', 'pagelinks' ],
3305 [ 'pl_namespace', 'pl_title' ],
3307 'pl_from' => $this->getArticleID(),
3308 'page_namespace IS NULL'
3314 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3320 foreach ( $res as $row ) {
3321 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3327 * Get a list of URLs to purge from the CDN cache when this
3330 * @return string[] Array of String the URLs
3332 public function getCdnUrls() {
3334 $this->getInternalURL(),
3335 $this->getInternalURL( 'action=history' )
3338 $pageLang = $this->getPageLanguage();
3339 if ( $pageLang->hasVariants() ) {
3340 $variants = $pageLang->getVariants();
3341 foreach ( $variants as $vCode ) {
3342 $urls[] = $this->getInternalURL( $vCode );
3346 // If we are looking at a css/js user subpage, purge the action=raw.
3347 if ( $this->isUserJsConfigPage() ) {
3348 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3349 } elseif ( $this->isUserJsonConfigPage() ) {
3350 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3351 } elseif ( $this->isUserCssConfigPage() ) {
3352 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3355 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3360 * Purge all applicable CDN URLs
3362 public function purgeSquid() {
3363 DeferredUpdates
::addUpdate(
3364 new CdnCacheUpdate( $this->getCdnUrls() ),
3365 DeferredUpdates
::PRESEND
3370 * Check whether a given move operation would be valid.
3371 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3373 * @deprecated since 1.25, use MovePage's methods instead
3374 * @param Title &$nt The new title
3375 * @param bool $auth Whether to check user permissions (uses $wgUser)
3376 * @param string $reason Is the log summary of the move, used for spam checking
3377 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3379 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3382 if ( !( $nt instanceof Title
) ) {
3383 // Normally we'd add this to $errors, but we'll get
3384 // lots of syntax errors if $nt is not an object
3385 return [ [ 'badtitletext' ] ];
3388 $mp = new MovePage( $this, $nt );
3389 $errors = $mp->isValidMove()->getErrorsArray();
3391 $errors = wfMergeErrorArrays(
3393 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3397 return $errors ?
: true;
3401 * Move a title to a new location
3403 * @deprecated since 1.25, use the MovePage class instead
3404 * @param Title &$nt The new title
3405 * @param bool $auth Indicates whether $wgUser's permissions
3407 * @param string $reason The reason for the move
3408 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3409 * Ignored if the user doesn't have the suppressredirect right.
3410 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3411 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3413 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3414 array $changeTags = []
3417 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3418 if ( is_array( $err ) ) {
3419 // Auto-block user's IP if the account was "hard" blocked
3420 $wgUser->spreadAnyEditBlock();
3423 // Check suppressredirect permission
3424 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3425 $createRedirect = true;
3428 $mp = new MovePage( $this, $nt );
3429 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3430 if ( $status->isOK() ) {
3433 return $status->getErrorsArray();
3438 * Move this page's subpages to be subpages of $nt
3440 * @param Title $nt Move target
3441 * @param bool $auth Whether $wgUser's permissions should be checked
3442 * @param string $reason The reason for the move
3443 * @param bool $createRedirect Whether to create redirects from the old subpages to
3444 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3445 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3446 * @return array Array with old page titles as keys, and strings (new page titles) or
3447 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3448 * getUserPermissionsErrors()-like error array with numeric indices if
3449 * no pages were moved
3451 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3452 array $changeTags = []
3454 global $wgMaximumMovedPages;
3455 // Check permissions
3456 if ( !$this->userCan( 'move-subpages' ) ) {
3458 [ 'cant-move-subpages' ],
3461 // Do the source and target namespaces support subpages?
3462 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3464 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
3467 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3469 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3473 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3476 foreach ( $subpages as $oldSubpage ) {
3478 if ( $count > $wgMaximumMovedPages ) {
3479 $retval[$oldSubpage->getPrefixedText()] = [
3480 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3485 // We don't know whether this function was called before
3486 // or after moving the root page, so check both
3488 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3489 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3491 // When moving a page to a subpage of itself,
3492 // don't move it twice
3495 $newPageName = preg_replace(
3496 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
3497 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3498 $oldSubpage->getDBkey() );
3499 if ( $oldSubpage->isTalkPage() ) {
3500 $newNs = $nt->getTalkPage()->getNamespace();
3502 $newNs = $nt->getSubjectPage()->getNamespace();
3504 # T16385: we need makeTitleSafe because the new page names may
3505 # be longer than 255 characters.
3506 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3508 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3509 if ( $success === true ) {
3510 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3512 $retval[$oldSubpage->getPrefixedText()] = $success;
3519 * Checks if this page is just a one-rev redirect.
3520 * Adds lock, so don't use just for light purposes.
3524 public function isSingleRevRedirect() {
3525 global $wgContentHandlerUseDB;
3527 $dbw = wfGetDB( DB_MASTER
);
3530 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3531 if ( $wgContentHandlerUseDB ) {
3532 $fields[] = 'page_content_model';
3535 $row = $dbw->selectRow( 'page',
3541 # Cache some fields we may want
3542 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3543 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3544 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3545 $this->mContentModel
= $row && isset( $row->page_content_model
)
3546 ?
strval( $row->page_content_model
)
3549 if ( !$this->mRedirect
) {
3552 # Does the article have a history?
3553 $row = $dbw->selectField( [ 'page', 'revision' ],
3555 [ 'page_namespace' => $this->mNamespace
,
3556 'page_title' => $this->mDbkeyform
,
3558 'page_latest != rev_id'
3563 # Return true if there was no history
3564 return ( $row === false );
3568 * Checks if $this can be moved to a given Title
3569 * - Selects for update, so don't call it unless you mean business
3571 * @deprecated since 1.25, use MovePage's methods instead
3572 * @param Title $nt The new title to check
3575 public function isValidMoveTarget( $nt ) {
3576 # Is it an existing file?
3577 if ( $nt->getNamespace() == NS_FILE
) {
3578 $file = wfLocalFile( $nt );
3579 $file->load( File
::READ_LATEST
);
3580 if ( $file->exists() ) {
3581 wfDebug( __METHOD__
. ": file exists\n" );
3585 # Is it a redirect with no history?
3586 if ( !$nt->isSingleRevRedirect() ) {
3587 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3590 # Get the article text
3591 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3592 if ( !is_object( $rev ) ) {
3595 $content = $rev->getContent();
3596 # Does the redirect point to the source?
3597 # Or is it a broken self-redirect, usually caused by namespace collisions?
3598 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3600 if ( $redirTitle ) {
3601 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3602 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3603 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3609 # Fail safe (not a redirect after all. strange.)
3610 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3611 " is a redirect, but it doesn't contain a valid redirect.\n" );
3617 * Get categories to which this Title belongs and return an array of
3618 * categories' names.
3620 * @return array Array of parents in the form:
3621 * $parent => $currentarticle
3623 public function getParentCategories() {
3626 $titleKey = $this->getArticleID();
3628 if ( $titleKey === 0 ) {
3632 $dbr = wfGetDB( DB_REPLICA
);
3634 $res = $dbr->select(
3637 [ 'cl_from' => $titleKey ],
3641 if ( $res->numRows() > 0 ) {
3642 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3643 foreach ( $res as $row ) {
3644 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3645 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3646 $this->getFullText();
3653 * Get a tree of parent categories
3655 * @param array $children Array with the children in the keys, to check for circular refs
3656 * @return array Tree of parent categories
3658 public function getParentCategoryTree( $children = [] ) {
3660 $parents = $this->getParentCategories();
3663 foreach ( $parents as $parent => $current ) {
3664 if ( array_key_exists( $parent, $children ) ) {
3665 # Circular reference
3666 $stack[$parent] = [];
3668 $nt = self
::newFromText( $parent );
3670 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3680 * Get an associative array for selecting this title from
3683 * @return array Array suitable for the $where parameter of DB::select()
3685 public function pageCond() {
3686 if ( $this->mArticleID
> 0 ) {
3687 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3688 return [ 'page_id' => $this->mArticleID
];
3690 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3695 * Get next/previous revision ID relative to another revision ID
3696 * @param int $revId Revision ID. Get the revision that was before this one.
3697 * @param int $flags Title::GAID_FOR_UPDATE
3698 * @param string $dir 'next' or 'prev'
3699 * @return int|bool New revision ID, or false if none exists
3701 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3702 $revId = (int)$revId;
3703 if ( $dir === 'next' ) {
3706 } elseif ( $dir === 'prev' ) {
3710 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
3713 if ( $flags & self
::GAID_FOR_UPDATE
) {
3714 $db = wfGetDB( DB_MASTER
);
3716 $db = wfGetDB( DB_REPLICA
, 'contributions' );
3719 // Intentionally not caring if the specified revision belongs to this
3720 // page. We only care about the timestamp.
3721 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
3722 if ( $ts === false ) {
3723 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
3724 if ( $ts === false ) {
3725 // Or should this throw an InvalidArgumentException or something?
3729 $ts = $db->addQuotes( $ts );
3731 $revId = $db->selectField( 'revision', 'rev_id',
3733 'rev_page' => $this->getArticleID( $flags ),
3734 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
3738 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
3739 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
3743 if ( $revId === false ) {
3746 return intval( $revId );
3751 * Get the revision ID of the previous revision
3753 * @param int $revId Revision ID. Get the revision that was before this one.
3754 * @param int $flags Title::GAID_FOR_UPDATE
3755 * @return int|bool Old revision ID, or false if none exists
3757 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3758 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3762 * Get the revision ID of the next revision
3764 * @param int $revId Revision ID. Get the revision that was after this one.
3765 * @param int $flags Title::GAID_FOR_UPDATE
3766 * @return int|bool Next revision ID, or false if none exists
3768 public function getNextRevisionID( $revId, $flags = 0 ) {
3769 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3773 * Get the first revision of the page
3775 * @param int $flags Title::GAID_FOR_UPDATE
3776 * @return Revision|null If page doesn't exist
3778 public function getFirstRevision( $flags = 0 ) {
3779 $pageId = $this->getArticleID( $flags );
3781 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3782 $revQuery = Revision
::getQueryInfo();
3783 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3784 [ 'rev_page' => $pageId ],
3787 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3788 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3793 return new Revision( $row, 0, $this );
3800 * Get the oldest revision timestamp of this page
3802 * @param int $flags Title::GAID_FOR_UPDATE
3803 * @return string|null MW timestamp
3805 public function getEarliestRevTime( $flags = 0 ) {
3806 $rev = $this->getFirstRevision( $flags );
3807 return $rev ?
$rev->getTimestamp() : null;
3811 * Check if this is a new page
3815 public function isNewPage() {
3816 $dbr = wfGetDB( DB_REPLICA
);
3817 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3821 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3825 public function isBigDeletion() {
3826 global $wgDeleteRevisionsLimit;
3828 if ( !$wgDeleteRevisionsLimit ) {
3832 if ( $this->mIsBigDeletion
=== null ) {
3833 $dbr = wfGetDB( DB_REPLICA
);
3835 $revCount = $dbr->selectRowCount(
3838 [ 'rev_page' => $this->getArticleID() ],
3840 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3843 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3846 return $this->mIsBigDeletion
;
3850 * Get the approximate revision count of this page.
3854 public function estimateRevisionCount() {
3855 if ( !$this->exists() ) {
3859 if ( $this->mEstimateRevisions
=== null ) {
3860 $dbr = wfGetDB( DB_REPLICA
);
3861 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3862 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3865 return $this->mEstimateRevisions
;
3869 * Get the number of revisions between the given revision.
3870 * Used for diffs and other things that really need it.
3872 * @param int|Revision $old Old revision or rev ID (first before range)
3873 * @param int|Revision $new New revision or rev ID (first after range)
3874 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3875 * @return int Number of revisions between these revisions.
3877 public function countRevisionsBetween( $old, $new, $max = null ) {
3878 if ( !( $old instanceof Revision
) ) {
3879 $old = Revision
::newFromTitle( $this, (int)$old );
3881 if ( !( $new instanceof Revision
) ) {
3882 $new = Revision
::newFromTitle( $this, (int)$new );
3884 if ( !$old ||
!$new ) {
3885 return 0; // nothing to compare
3887 $dbr = wfGetDB( DB_REPLICA
);
3889 'rev_page' => $this->getArticleID(),
3890 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3891 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3893 if ( $max !== null ) {
3894 return $dbr->selectRowCount( 'revision', '1',
3897 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3900 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3905 * Get the authors between the given revisions or revision IDs.
3906 * Used for diffs and other things that really need it.
3910 * @param int|Revision $old Old revision or rev ID (first before range by default)
3911 * @param int|Revision $new New revision or rev ID (first after range by default)
3912 * @param int $limit Maximum number of authors
3913 * @param string|array $options (Optional): Single option, or an array of options:
3914 * 'include_old' Include $old in the range; $new is excluded.
3915 * 'include_new' Include $new in the range; $old is excluded.
3916 * 'include_both' Include both $old and $new in the range.
3917 * Unknown option values are ignored.
3918 * @return array|null Names of revision authors in the range; null if not both revisions exist
3920 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3921 if ( !( $old instanceof Revision
) ) {
3922 $old = Revision
::newFromTitle( $this, (int)$old );
3924 if ( !( $new instanceof Revision
) ) {
3925 $new = Revision
::newFromTitle( $this, (int)$new );
3927 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3928 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3929 // in the sanity check below?
3930 if ( !$old ||
!$new ) {
3931 return null; // nothing to compare
3936 $options = (array)$options;
3937 if ( in_array( 'include_old', $options ) ) {
3940 if ( in_array( 'include_new', $options ) ) {
3943 if ( in_array( 'include_both', $options ) ) {
3947 // No DB query needed if $old and $new are the same or successive revisions:
3948 if ( $old->getId() === $new->getId() ) {
3949 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3951 [ $old->getUserText( Revision
::RAW
) ];
3952 } elseif ( $old->getId() === $new->getParentId() ) {
3953 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3954 $authors[] = $old->getUserText( Revision
::RAW
);
3955 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3956 $authors[] = $new->getUserText( Revision
::RAW
);
3958 } elseif ( $old_cmp === '>=' ) {
3959 $authors[] = $old->getUserText( Revision
::RAW
);
3960 } elseif ( $new_cmp === '<=' ) {
3961 $authors[] = $new->getUserText( Revision
::RAW
);
3965 $dbr = wfGetDB( DB_REPLICA
);
3966 $revQuery = Revision
::getQueryInfo();
3967 $authors = $dbr->selectFieldValues(
3968 $revQuery['tables'],
3969 $revQuery['fields']['rev_user_text'],
3971 'rev_page' => $this->getArticleID(),
3972 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3973 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3975 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3982 * Get the number of authors between the given revisions or revision IDs.
3983 * Used for diffs and other things that really need it.
3985 * @param int|Revision $old Old revision or rev ID (first before range by default)
3986 * @param int|Revision $new New revision or rev ID (first after range by default)
3987 * @param int $limit Maximum number of authors
3988 * @param string|array $options (Optional): Single option, or an array of options:
3989 * 'include_old' Include $old in the range; $new is excluded.
3990 * 'include_new' Include $new in the range; $old is excluded.
3991 * 'include_both' Include both $old and $new in the range.
3992 * Unknown option values are ignored.
3993 * @return int Number of revision authors in the range; zero if not both revisions exist
3995 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3996 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3997 return $authors ?
count( $authors ) : 0;
4001 * Compare with another title.
4003 * @param Title $title
4006 public function equals( Title
$title ) {
4007 // Note: === is necessary for proper matching of number-like titles.
4008 return $this->mInterwiki
=== $title->mInterwiki
4009 && $this->mNamespace
== $title->mNamespace
4010 && $this->mDbkeyform
=== $title->mDbkeyform
;
4014 * Check if this title is a subpage of another title
4016 * @param Title $title
4019 public function isSubpageOf( Title
$title ) {
4020 return $this->mInterwiki
=== $title->mInterwiki
4021 && $this->mNamespace
== $title->mNamespace
4022 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4026 * Check if page exists. For historical reasons, this function simply
4027 * checks for the existence of the title in the page table, and will
4028 * thus return false for interwiki links, special pages and the like.
4029 * If you want to know if a title can be meaningfully viewed, you should
4030 * probably call the isKnown() method instead.
4032 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4033 * from master/for update
4036 public function exists( $flags = 0 ) {
4037 $exists = $this->getArticleID( $flags ) != 0;
4038 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4043 * Should links to this title be shown as potentially viewable (i.e. as
4044 * "bluelinks"), even if there's no record by this title in the page
4047 * This function is semi-deprecated for public use, as well as somewhat
4048 * misleadingly named. You probably just want to call isKnown(), which
4049 * calls this function internally.
4051 * (ISSUE: Most of these checks are cheap, but the file existence check
4052 * can potentially be quite expensive. Including it here fixes a lot of
4053 * existing code, but we might want to add an optional parameter to skip
4054 * it and any other expensive checks.)
4058 public function isAlwaysKnown() {
4062 * Allows overriding default behavior for determining if a page exists.
4063 * If $isKnown is kept as null, regular checks happen. If it's
4064 * a boolean, this value is returned by the isKnown method.
4068 * @param Title $title
4069 * @param bool|null $isKnown
4071 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4073 if ( !is_null( $isKnown ) ) {
4077 if ( $this->isExternal() ) {
4078 return true; // any interwiki link might be viewable, for all we know
4081 switch ( $this->mNamespace
) {
4084 // file exists, possibly in a foreign repo
4085 return (bool)wfFindFile( $this );
4087 // valid special page
4088 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4089 exists( $this->mDbkeyform
);
4091 // selflink, possibly with fragment
4092 return $this->mDbkeyform
== '';
4094 // known system message
4095 return $this->hasSourceText() !== false;
4102 * Does this title refer to a page that can (or might) be meaningfully
4103 * viewed? In particular, this function may be used to determine if
4104 * links to the title should be rendered as "bluelinks" (as opposed to
4105 * "redlinks" to non-existent pages).
4106 * Adding something else to this function will cause inconsistency
4107 * since LinkHolderArray calls isAlwaysKnown() and does its own
4108 * page existence check.
4112 public function isKnown() {
4113 return $this->isAlwaysKnown() ||
$this->exists();
4117 * Does this page have source text?
4121 public function hasSourceText() {
4122 if ( $this->exists() ) {
4126 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4127 // If the page doesn't exist but is a known system message, default
4128 // message content will be displayed, same for language subpages-
4129 // Use always content language to avoid loading hundreds of languages
4130 // to get the link color.
4131 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4132 list( $name, ) = MessageCache
::singleton()->figureMessage(
4133 $contLang->lcfirst( $this->getText() )
4135 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4136 return $message->exists();
4143 * Get the default (plain) message contents for an page that overrides an
4144 * interface message key.
4146 * Primary use cases:
4149 * - Show default when viewing the page. The Article::getSubstituteContent
4150 * method displays the default message content, instead of the
4151 * 'noarticletext' placeholder message normally used.
4154 * - Title of edit page. When creating an interface message override,
4155 * the editor is told they are "Editing the page", instead of
4156 * "Creating the page". (EditPage::setHeaders)
4157 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4158 * or editing a an interface message override. (EditPage::showIntro)
4159 * - Opening the editor. The contents of the localisation message are used
4160 * as contents of the editor when creating a new page in the MediaWiki
4161 * namespace. This simplifies the process for editors when "changing"
4162 * an interface message by creating an override. (EditPage::getContentObject)
4163 * - Showing a diff. The left-hand side of a diff when an editor is
4164 * previewing their changes before saving the creation of a page in the
4165 * MediaWiki namespace. (EditPage::showDiff)
4166 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4167 * page with the proposed content matching the interface message default,
4168 * the save is rejected, the same way we disallow blank pages from being
4169 * created. (EditPage::internalAttemptSave)
4172 * - Default content, when using the 'prepend' or 'append' feature.
4175 * - Label the create action as "Edit", if the page can be an override.
4177 * @return string|bool
4179 public function getDefaultMessageText() {
4180 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4184 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4185 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4187 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4189 if ( $message->exists() ) {
4190 return $message->plain();
4197 * Updates page_touched for this page; called from LinksUpdate.php
4199 * @param string|null $purgeTime [optional] TS_MW timestamp
4200 * @return bool True if the update succeeded
4202 public function invalidateCache( $purgeTime = null ) {
4203 if ( wfReadOnly() ) {
4205 } elseif ( $this->mArticleID
=== 0 ) {
4206 return true; // avoid gap locking if we know it's not there
4209 $dbw = wfGetDB( DB_MASTER
);
4210 $dbw->onTransactionPreCommitOrIdle(
4211 function () use ( $dbw ) {
4212 ResourceLoaderWikiModule
::invalidateModuleCache(
4213 $this, null, null, $dbw->getDomainID() );
4218 $conds = $this->pageCond();
4219 DeferredUpdates
::addUpdate(
4220 new AutoCommitUpdate(
4223 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4224 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4227 [ 'page_touched' => $dbTimestamp ],
4228 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4231 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4234 DeferredUpdates
::PRESEND
4241 * Update page_touched timestamps and send CDN purge messages for
4242 * pages linking to this title. May be sent to the job queue depending
4243 * on the number of links. Typically called on create and delete.
4245 public function touchLinks() {
4246 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4247 if ( $this->mNamespace
== NS_CATEGORY
) {
4248 DeferredUpdates
::addUpdate(
4249 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4255 * Get the last touched timestamp
4257 * @param IDatabase|null $db
4258 * @return string|false Last-touched timestamp
4260 public function getTouched( $db = null ) {
4261 if ( $db === null ) {
4262 $db = wfGetDB( DB_REPLICA
);
4264 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4269 * Get the timestamp when this page was updated since the user last saw it.
4271 * @param User|null $user
4272 * @return string|null
4274 public function getNotificationTimestamp( $user = null ) {
4277 // Assume current user if none given
4281 // Check cache first
4282 $uid = $user->getId();
4286 // avoid isset here, as it'll return false for null entries
4287 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4288 return $this->mNotificationTimestamp
[$uid];
4290 // Don't cache too much!
4291 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4292 $this->mNotificationTimestamp
= [];
4295 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4296 $watchedItem = $store->getWatchedItem( $user, $this );
4297 if ( $watchedItem ) {
4298 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4300 $this->mNotificationTimestamp
[$uid] = false;
4303 return $this->mNotificationTimestamp
[$uid];
4307 * Generate strings used for xml 'id' names in monobook tabs
4309 * @param string $prepend Defaults to 'nstab-'
4310 * @return string XML 'id' name
4312 public function getNamespaceKey( $prepend = 'nstab-' ) {
4313 // Gets the subject namespace of this title
4314 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4315 // Prefer canonical namespace name for HTML IDs
4316 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4317 if ( $namespaceKey === false ) {
4318 // Fallback to localised text
4319 $namespaceKey = $this->getSubjectNsText();
4321 // Makes namespace key lowercase
4322 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4324 if ( $namespaceKey == '' ) {
4325 $namespaceKey = 'main';
4327 // Changes file to image for backwards compatibility
4328 if ( $namespaceKey == 'file' ) {
4329 $namespaceKey = 'image';
4331 return $prepend . $namespaceKey;
4335 * Get all extant redirects to this Title
4337 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4338 * @return Title[] Array of Title redirects to this title
4340 public function getRedirectsHere( $ns = null ) {
4343 $dbr = wfGetDB( DB_REPLICA
);
4345 'rd_namespace' => $this->mNamespace
,
4346 'rd_title' => $this->mDbkeyform
,
4349 if ( $this->isExternal() ) {
4350 $where['rd_interwiki'] = $this->mInterwiki
;
4352 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4354 if ( !is_null( $ns ) ) {
4355 $where['page_namespace'] = $ns;
4358 $res = $dbr->select(
4359 [ 'redirect', 'page' ],
4360 [ 'page_namespace', 'page_title' ],
4365 foreach ( $res as $row ) {
4366 $redirs[] = self
::newFromRow( $row );
4372 * Check if this Title is a valid redirect target
4376 public function isValidRedirectTarget() {
4377 global $wgInvalidRedirectTargets;
4379 if ( $this->isSpecialPage() ) {
4380 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4381 if ( $this->isSpecial( 'Userlogout' ) ) {
4385 foreach ( $wgInvalidRedirectTargets as $target ) {
4386 if ( $this->isSpecial( $target ) ) {
4396 * Get a backlink cache object
4398 * @return BacklinkCache
4400 public function getBacklinkCache() {
4401 return BacklinkCache
::get( $this );
4405 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4409 public function canUseNoindex() {
4410 global $wgExemptFromUserRobotsControl;
4412 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
4414 return !in_array( $this->mNamespace
, $bannedNamespaces );
4418 * Returns the raw sort key to be used for categories, with the specified
4419 * prefix. This will be fed to Collation::getSortKey() to get a
4420 * binary sortkey that can be used for actual sorting.
4422 * @param string $prefix The prefix to be used, specified using
4423 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4427 public function getCategorySortkey( $prefix = '' ) {
4428 $unprefixed = $this->getText();
4430 // Anything that uses this hook should only depend
4431 // on the Title object passed in, and should probably
4432 // tell the users to run updateCollations.php --force
4433 // in order to re-sort existing category relations.
4434 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4435 if ( $prefix !== '' ) {
4436 # Separate with a line feed, so the unprefixed part is only used as
4437 # a tiebreaker when two pages have the exact same prefix.
4438 # In UCA, tab is the only character that can sort above LF
4439 # so we strip both of them from the original prefix.
4440 $prefix = strtr( $prefix, "\n\t", ' ' );
4441 return "$prefix\n$unprefixed";
4447 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4448 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4449 * the db, it will return NULL.
4451 * @return string|null|bool
4453 private function getDbPageLanguageCode() {
4454 global $wgPageLanguageUseDB;
4456 // check, if the page language could be saved in the database, and if so and
4457 // the value is not requested already, lookup the page language using LinkCache
4458 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4459 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4460 $linkCache->addLinkObj( $this );
4461 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4464 return $this->mDbPageLanguage
;
4468 * Get the language in which the content of this page is written in
4469 * wikitext. Defaults to content language, but in certain cases it can be
4470 * e.g. $wgLang (such as special pages, which are in the user language).
4475 public function getPageLanguage() {
4476 global $wgLang, $wgLanguageCode;
4477 if ( $this->isSpecialPage() ) {
4478 // special pages are in the user language
4482 // Checking if DB language is set
4483 $dbPageLanguage = $this->getDbPageLanguageCode();
4484 if ( $dbPageLanguage ) {
4485 return wfGetLangObj( $dbPageLanguage );
4488 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4489 // Note that this may depend on user settings, so the cache should
4490 // be only per-request.
4491 // NOTE: ContentHandler::getPageLanguage() may need to load the
4492 // content to determine the page language!
4493 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4495 $contentHandler = ContentHandler
::getForTitle( $this );
4496 $langObj = $contentHandler->getPageLanguage( $this );
4497 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4499 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4506 * Get the language in which the content of this page is written when
4507 * viewed by user. Defaults to content language, but in certain cases it can be
4508 * e.g. $wgLang (such as special pages, which are in the user language).
4513 public function getPageViewLanguage() {
4516 if ( $this->isSpecialPage() ) {
4517 // If the user chooses a variant, the content is actually
4518 // in a language whose code is the variant code.
4519 $variant = $wgLang->getPreferredVariant();
4520 if ( $wgLang->getCode() !== $variant ) {
4521 return Language
::factory( $variant );
4527 // Checking if DB language is set
4528 $dbPageLanguage = $this->getDbPageLanguageCode();
4529 if ( $dbPageLanguage ) {
4530 $pageLang = wfGetLangObj( $dbPageLanguage );
4531 $variant = $pageLang->getPreferredVariant();
4532 if ( $pageLang->getCode() !== $variant ) {
4533 $pageLang = Language
::factory( $variant );
4539 // @note Can't be cached persistently, depends on user settings.
4540 // @note ContentHandler::getPageViewLanguage() may need to load the
4541 // content to determine the page language!
4542 $contentHandler = ContentHandler
::getForTitle( $this );
4543 $pageLang = $contentHandler->getPageViewLanguage( $this );
4548 * Get a list of rendered edit notices for this page.
4550 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4551 * they will already be wrapped in paragraphs.
4554 * @param int $oldid Revision ID that's being edited
4557 public function getEditNotices( $oldid = 0 ) {
4560 // Optional notice for the entire namespace
4561 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4562 $msg = wfMessage( $editnotice_ns );
4563 if ( $msg->exists() ) {
4564 $html = $msg->parseAsBlock();
4565 // Edit notices may have complex logic, but output nothing (T91715)
4566 if ( trim( $html ) !== '' ) {
4567 $notices[$editnotice_ns] = Html
::rawElement(
4571 'mw-editnotice-namespace',
4572 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4579 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4580 // Optional notice for page itself and any parent page
4581 $editnotice_base = $editnotice_ns;
4582 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4583 $editnotice_base .= '-' . $part;
4584 $msg = wfMessage( $editnotice_base );
4585 if ( $msg->exists() ) {
4586 $html = $msg->parseAsBlock();
4587 if ( trim( $html ) !== '' ) {
4588 $notices[$editnotice_base] = Html
::rawElement(
4592 'mw-editnotice-base',
4593 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4601 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4602 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4603 $msg = wfMessage( $editnoticeText );
4604 if ( $msg->exists() ) {
4605 $html = $msg->parseAsBlock();
4606 if ( trim( $html ) !== '' ) {
4607 $notices[$editnoticeText] = Html
::rawElement(
4611 'mw-editnotice-page',
4612 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4620 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4627 public function __sleep() {
4635 'mDefaultNamespace',
4639 public function __wakeup() {
4640 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4641 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4642 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );