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 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
251 * @param TitleValue $titleValue Assumed to be safe.
252 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
256 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
257 return self
::newFromLinkTarget( $titleValue, $forceClone );
261 * Returns a Title given a LinkTarget.
262 * If the given LinkTarget is already a Title instance, that instance is returned,
263 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
264 * is already a Title instance, that instance is copied using the clone operator.
266 * @param LinkTarget $linkTarget Assumed to be safe.
267 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
271 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
272 if ( $linkTarget instanceof Title
) {
273 // Special case if it's already a Title object
274 if ( $forceClone === self
::NEW_CLONE
) {
275 return clone $linkTarget;
280 return self
::makeTitle(
281 $linkTarget->getNamespace(),
282 $linkTarget->getText(),
283 $linkTarget->getFragment(),
284 $linkTarget->getInterwiki()
289 * Same as newFromLinkTarget, but if passed null, returns null.
291 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
295 public static function castFromLinkTarget( $linkTarget ) {
296 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
300 * Create a new Title from text, such as what one would find in a link. De-
301 * codes any HTML entities in the text.
303 * Title objects returned by this method are guaranteed to be valid, and
304 * thus return true from the isValid() method.
306 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
307 * It may instead be a cached instance created previously, with references to it remaining
310 * @param string|int|null $text The link text; spaces, prefixes, and an
311 * initial ':' indicating the main namespace are accepted.
312 * @param int $defaultNamespace The namespace to use if none is specified
313 * by a prefix. If you want to force a specific namespace even if
314 * $text might begin with a namespace prefix, use makeTitle() or
316 * @throws InvalidArgumentException
317 * @return Title|null Title or null on an error.
319 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
320 // DWIM: Integers can be passed in here when page titles are used as array keys.
321 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
322 throw new InvalidArgumentException( '$text must be a string.' );
324 if ( $text === null ) {
329 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
330 } catch ( MalformedTitleException
$ex ) {
336 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
337 * rather than returning null.
339 * The exception subclasses encode detailed information about why the title is invalid.
341 * Title objects returned by this method are guaranteed to be valid, and
342 * thus return true from the isValid() method.
344 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
345 * It may instead be a cached instance created previously, with references to it remaining
348 * @see Title::newFromText
351 * @param string $text Title text to check
352 * @param int $defaultNamespace
353 * @throws MalformedTitleException If the title is invalid
356 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
357 if ( is_object( $text ) ) {
358 throw new MWException( '$text must be a string, given an object' );
359 } elseif ( $text === null ) {
360 // Legacy code relies on MalformedTitleException being thrown in this case
361 // (happens when URL with no title in it is parsed). TODO fix
362 throw new MalformedTitleException( 'title-invalid-empty' );
365 $titleCache = self
::getTitleCache();
367 // Wiki pages often contain multiple links to the same page.
368 // Title normalization and parsing can become expensive on pages with many
369 // links, so we can save a little time by caching them.
370 // In theory these are value objects and won't get changed...
371 if ( $defaultNamespace == NS_MAIN
) {
372 $t = $titleCache->get( $text );
378 // Convert things like é ā or 〗 into normalized (T16952) text
379 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
382 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
383 $t->mDefaultNamespace
= (int)$defaultNamespace;
385 $t->secureAndSplit();
386 if ( $defaultNamespace == NS_MAIN
) {
387 $titleCache->set( $text, $t );
393 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
395 * Example of wrong and broken code:
396 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
398 * Example of right code:
399 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
401 * Create a new Title from URL-encoded text. Ensures that
402 * the given title's length does not exceed the maximum.
404 * @param string $url The title, as might be taken from a URL
405 * @return Title|null The new object, or null on an error
407 public static function newFromURL( $url ) {
410 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
411 # but some URLs used it as a space replacement and they still come
412 # from some external search tools.
413 if ( strpos( self
::legalChars(), '+' ) === false ) {
414 $url = strtr( $url, '+', ' ' );
417 $t->mDbkeyform
= strtr( $url, ' ', '_' );
420 $t->secureAndSplit();
422 } catch ( MalformedTitleException
$ex ) {
428 * @return MapCacheLRU
430 private static function getTitleCache() {
431 if ( self
::$titleCache === null ) {
432 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
434 return self
::$titleCache;
438 * Returns a list of fields that are to be selected for initializing Title
439 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
440 * whether to include page_content_model.
444 protected static function getSelectFields() {
445 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
448 'page_namespace', 'page_title', 'page_id',
449 'page_len', 'page_is_redirect', 'page_latest',
452 if ( $wgContentHandlerUseDB ) {
453 $fields[] = 'page_content_model';
456 if ( $wgPageLanguageUseDB ) {
457 $fields[] = 'page_lang';
464 * Create a new Title from an article ID
466 * @param int $id The page_id corresponding to the Title to create
467 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
468 * @return Title|null The new object, or null on an error
470 public static function newFromID( $id, $flags = 0 ) {
471 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
472 $row = $db->selectRow(
474 self
::getSelectFields(),
475 [ 'page_id' => $id ],
478 if ( $row !== false ) {
479 $title = self
::newFromRow( $row );
488 * Make an array of titles from an array of IDs
490 * @param int[] $ids Array of IDs
491 * @return Title[] Array of Titles
493 public static function newFromIDs( $ids ) {
494 if ( !count( $ids ) ) {
497 $dbr = wfGetDB( DB_REPLICA
);
501 self
::getSelectFields(),
502 [ 'page_id' => $ids ],
507 foreach ( $res as $row ) {
508 $titles[] = self
::newFromRow( $row );
514 * Make a Title object from a DB row
516 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
517 * @return Title Corresponding Title
519 public static function newFromRow( $row ) {
520 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
521 $t->loadFromRow( $row );
526 * Load Title object fields from a DB row.
527 * If false is given, the title will be treated as non-existing.
529 * @param stdClass|bool $row Database row
531 public function loadFromRow( $row ) {
532 if ( $row ) { // page found
533 if ( isset( $row->page_id
) ) {
534 $this->mArticleID
= (int)$row->page_id
;
536 if ( isset( $row->page_len
) ) {
537 $this->mLength
= (int)$row->page_len
;
539 if ( isset( $row->page_is_redirect
) ) {
540 $this->mRedirect
= (bool)$row->page_is_redirect
;
542 if ( isset( $row->page_latest
) ) {
543 $this->mLatestID
= (int)$row->page_latest
;
545 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
546 $this->mContentModel
= (string)$row->page_content_model
;
547 } elseif ( !$this->mForcedContentModel
) {
548 $this->mContentModel
= false; # initialized lazily in getContentModel()
550 if ( isset( $row->page_lang
) ) {
551 $this->mDbPageLanguage
= (string)$row->page_lang
;
553 if ( isset( $row->page_restrictions
) ) {
554 $this->mOldRestrictions
= $row->page_restrictions
;
556 } else { // page not found
557 $this->mArticleID
= 0;
559 $this->mRedirect
= false;
560 $this->mLatestID
= 0;
561 if ( !$this->mForcedContentModel
) {
562 $this->mContentModel
= false; # initialized lazily in getContentModel()
568 * Create a new Title from a namespace index and a DB key.
570 * It's assumed that $ns and $title are safe, for instance when
571 * they came directly from the database or a special page name,
572 * not from user input.
574 * No validation is applied. For convenience, spaces are normalized
575 * to underscores, so that e.g. user_text fields can be used directly.
577 * @note This method may return Title objects that are "invalid"
578 * according to the isValid() method. This is usually caused by
579 * configuration changes: e.g. a namespace that was once defined is
580 * no longer configured, or a character that was once allowed in
581 * titles is now forbidden.
583 * @param int $ns The namespace of the article
584 * @param string $title The unprefixed database key form
585 * @param string $fragment The link fragment (after the "#")
586 * @param string $interwiki The interwiki prefix
587 * @return Title The new object
589 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
591 $t->mInterwiki
= $interwiki;
592 $t->mFragment
= $fragment;
593 $t->mNamespace
= $ns = (int)$ns;
594 $t->mDbkeyform
= strtr( $title, ' ', '_' );
595 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
596 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
597 $t->mTextform
= strtr( $title, '_', ' ' );
598 $t->mContentModel
= false; # initialized lazily in getContentModel()
603 * Create a new Title from a namespace index and a DB key.
604 * The parameters will be checked for validity, which is a bit slower
605 * than makeTitle() but safer for user-provided data.
607 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
608 * that is, they return true from the isValid() method. If no valid Title
609 * can be constructed from the input, this method returns null.
611 * @param int $ns The namespace of the article
612 * @param string $title Database key form
613 * @param string $fragment The link fragment (after the "#")
614 * @param string $interwiki Interwiki prefix
615 * @return Title|null The new object, or null on an error
617 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
618 // NOTE: ideally, this would just call makeTitle() and then isValid(),
619 // but presently, that means more overhead on a potential performance hotspot.
621 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
626 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
629 $t->secureAndSplit();
631 } catch ( MalformedTitleException
$ex ) {
637 * Create a new Title for the Main Page
639 * This uses the 'mainpage' interface message, which could be specified in
640 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
641 * will use the user language, which would involve initialising the session
642 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
643 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
644 * or ResourceloaderContext) to prevent an error.
646 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
647 * It may instead be a cached instance created previously, with references to it remaining
650 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
653 public static function newMainPage( MessageLocalizer
$localizer = null ) {
655 $msg = $localizer->msg( 'mainpage' );
657 $msg = wfMessage( 'mainpage' );
660 $title = self
::newFromText( $msg->inContentLanguage()->text() );
662 // Every page renders at least one link to the Main Page (e.g. sidebar).
663 // If the localised value is invalid, don't produce fatal errors that
664 // would make the wiki inaccessible (and hard to fix the invalid message).
665 // Gracefully fallback...
667 $title = self
::newFromText( 'Main Page' );
673 * Get the prefixed DB key associated with an ID
675 * @param int $id The page_id of the article
676 * @return Title|null An object representing the article, or null if no such article was found
678 public static function nameOf( $id ) {
679 $dbr = wfGetDB( DB_REPLICA
);
681 $s = $dbr->selectRow(
683 [ 'page_namespace', 'page_title' ],
684 [ 'page_id' => $id ],
687 if ( $s === false ) {
691 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
696 * Get a regex character class describing the legal characters in a link
698 * @return string The list of characters, not delimited
700 public static function legalChars() {
701 global $wgLegalTitleChars;
702 return $wgLegalTitleChars;
706 * Utility method for converting a character sequence from bytes to Unicode.
708 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
709 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
711 * @param string $byteClass
714 public static function convertByteClassToUnicodeClass( $byteClass ) {
715 $length = strlen( $byteClass );
717 $x0 = $x1 = $x2 = '';
719 $d0 = $d1 = $d2 = '';
720 // Decoded integer codepoints
721 $ord0 = $ord1 = $ord2 = 0;
723 $r0 = $r1 = $r2 = '';
727 $allowUnicode = false;
728 for ( $pos = 0; $pos < $length; $pos++
) {
729 // Shift the queues down
738 // Load the current input token and decoded values
739 $inChar = $byteClass[$pos];
740 if ( $inChar == '\\' ) {
741 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
742 $x0 = $inChar . $m[0];
743 $d0 = chr( hexdec( $m[1] ) );
744 $pos +
= strlen( $m[0] );
745 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
746 $x0 = $inChar . $m[0];
747 $d0 = chr( octdec( $m[0] ) );
748 $pos +
= strlen( $m[0] );
749 } elseif ( $pos +
1 >= $length ) {
752 $d0 = $byteClass[$pos +
1];
760 // Load the current re-encoded value
761 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
762 $r0 = sprintf( '\x%02x', $ord0 );
763 } elseif ( $ord0 >= 0x80 ) {
764 // Allow unicode if a single high-bit character appears
765 $r0 = sprintf( '\x%02x', $ord0 );
766 $allowUnicode = true;
767 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
768 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
774 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
776 if ( $ord2 > $ord0 ) {
778 } elseif ( $ord0 >= 0x80 ) {
780 $allowUnicode = true;
781 if ( $ord2 < 0x80 ) {
782 // Keep the non-unicode section of the range
789 // Reset state to the initial value
790 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
791 } elseif ( $ord2 < 0x80 ) {
796 if ( $ord1 < 0x80 ) {
799 if ( $ord0 < 0x80 ) {
802 if ( $allowUnicode ) {
803 $out .= '\u0080-\uFFFF';
809 * Make a prefixed DB key from a DB key and a namespace index
811 * @param int $ns Numerical representation of the namespace
812 * @param string $title The DB key form the title
813 * @param string $fragment The link fragment (after the "#")
814 * @param string $interwiki The interwiki prefix
815 * @param bool $canonicalNamespace If true, use the canonical name for
816 * $ns instead of the localized version.
817 * @return string The prefixed form of the title
819 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
820 $canonicalNamespace = false
822 if ( $canonicalNamespace ) {
823 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
824 getCanonicalName( $ns );
826 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
828 $name = $namespace == '' ?
$title : "$namespace:$title";
829 if ( strval( $interwiki ) != '' ) {
830 $name = "$interwiki:$name";
832 if ( strval( $fragment ) != '' ) {
833 $name .= '#' . $fragment;
839 * Callback for usort() to do title sorts by (namespace, title)
841 * @param LinkTarget $a
842 * @param LinkTarget $b
844 * @return int Result of string comparison, or namespace comparison
846 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
847 return $a->getNamespace() <=> $b->getNamespace()
848 ?
: strcmp( $a->getText(), $b->getText() );
852 * Returns true if the title is valid, false if it is invalid.
854 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
855 * Invalid titles may get returned from makeTitle(), and it may be useful to
856 * allow them to exist, e.g. in order to process log entries about pages in
857 * namespaces that belong to extensions that are no longer installed.
859 * @note This method is relatively expensive. When constructing Title
860 * objects that need to be valid, use an instantiator method that is guaranteed
861 * to return valid titles, such as makeTitleSafe() or newFromText().
865 public function isValid() {
866 $services = MediaWikiServices
::getInstance();
867 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
872 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
874 } catch ( MalformedTitleException
$ex ) {
880 * Determine whether the object refers to a page within
881 * this project (either this wiki or a wiki with a local
882 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
884 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
886 public function isLocal() {
887 if ( $this->isExternal() ) {
888 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
890 return $iw->isLocal();
897 * Is this Title interwiki?
901 public function isExternal() {
902 return $this->mInterwiki
!== '';
906 * Get the interwiki prefix
908 * Use Title::isExternal to check if a interwiki is set
910 * @return string Interwiki prefix
912 public function getInterwiki() {
913 return $this->mInterwiki
;
917 * Was this a local interwiki link?
921 public function wasLocalInterwiki() {
922 return $this->mLocalInterwiki
;
926 * Determine whether the object refers to a page within
927 * this project and is transcludable.
929 * @return bool True if this is transcludable
931 public function isTrans() {
932 if ( !$this->isExternal() ) {
936 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
940 * Returns the DB name of the distant wiki which owns the object.
942 * @return string|false The DB name
944 public function getTransWikiID() {
945 if ( !$this->isExternal() ) {
949 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
953 * Get a TitleValue object representing this Title.
955 * @note Not all valid Titles have a corresponding valid TitleValue
956 * (e.g. TitleValues cannot represent page-local links that have a
957 * fragment but no title text).
959 * @return TitleValue|null
961 public function getTitleValue() {
962 if ( $this->mTitleValue
=== null ) {
964 $this->mTitleValue
= new TitleValue(
970 } catch ( InvalidArgumentException
$ex ) {
971 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
972 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
976 return $this->mTitleValue
;
980 * Get the text form (spaces not underscores) of the main part
982 * @return string Main part of the title
984 public function getText() {
985 return $this->mTextform
;
989 * Get the URL-encoded form of the main part
991 * @return string Main part of the title, URL-encoded
993 public function getPartialURL() {
994 return $this->mUrlform
;
998 * Get the main part with underscores
1000 * @return string Main part of the title, with underscores
1002 public function getDBkey() {
1003 return $this->mDbkeyform
;
1007 * Get the DB key with the initial letter case as specified by the user
1008 * @deprecated since 1.33; please use Title::getDBKey() instead
1010 * @return string DB key
1012 function getUserCaseDBKey() {
1013 if ( !is_null( $this->mUserCaseDBKey
) ) {
1014 return $this->mUserCaseDBKey
;
1016 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1017 return $this->mDbkeyform
;
1022 * Get the namespace index, i.e. one of the NS_xxxx constants.
1024 * @return int Namespace index
1026 public function getNamespace() {
1027 return $this->mNamespace
;
1031 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1033 * @todo Deprecate this in favor of SlotRecord::getModel()
1035 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1036 * @return string Content model id
1038 public function getContentModel( $flags = 0 ) {
1039 if ( !$this->mForcedContentModel
1040 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1041 && $this->getArticleID( $flags )
1043 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1044 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1045 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1048 if ( !$this->mContentModel
) {
1049 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1052 return $this->mContentModel
;
1056 * Convenience method for checking a title's content model name
1058 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1059 * @return bool True if $this->getContentModel() == $id
1061 public function hasContentModel( $id ) {
1062 return $this->getContentModel() == $id;
1066 * Set a proposed content model for the page for permissions
1067 * checking. This does not actually change the content model
1070 * Additionally, you should make sure you've checked
1071 * ContentHandler::canBeUsedOn() first.
1074 * @param string $model CONTENT_MODEL_XXX constant
1076 public function setContentModel( $model ) {
1077 $this->mContentModel
= $model;
1078 $this->mForcedContentModel
= true;
1082 * Get the namespace text
1084 * @return string|false Namespace text
1086 public function getNsText() {
1087 if ( $this->isExternal() ) {
1088 // This probably shouldn't even happen, except for interwiki transclusion.
1089 // If possible, use the canonical name for the foreign namespace.
1090 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1091 getCanonicalName( $this->mNamespace
);
1092 if ( $nsText !== false ) {
1098 $formatter = self
::getTitleFormatter();
1099 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1100 } catch ( InvalidArgumentException
$ex ) {
1101 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1107 * Get the namespace text of the subject (rather than talk) page
1109 * @return string Namespace text
1111 public function getSubjectNsText() {
1112 $services = MediaWikiServices
::getInstance();
1113 return $services->getContentLanguage()->
1114 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1118 * Get the namespace text of the talk page
1120 * @return string Namespace text
1122 public function getTalkNsText() {
1123 $services = MediaWikiServices
::getInstance();
1124 return $services->getContentLanguage()->
1125 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1129 * Can this title have a corresponding talk page?
1131 * @see NamespaceInfo::hasTalkNamespace
1134 * @return bool True if this title either is a talk page or can have a talk page associated.
1136 public function canHaveTalkPage() {
1137 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1138 hasTalkNamespace( $this->mNamespace
);
1142 * Is this in a namespace that allows actual pages?
1146 public function canExist() {
1147 return $this->mNamespace
>= NS_MAIN
;
1151 * Can this title be added to a user's watchlist?
1155 public function isWatchable() {
1156 return !$this->isExternal() && MediaWikiServices
::getInstance()->getNamespaceInfo()->
1157 isWatchable( $this->mNamespace
);
1161 * Returns true if this is a special page.
1165 public function isSpecialPage() {
1166 return $this->mNamespace
== NS_SPECIAL
;
1170 * Returns true if this title resolves to the named special page
1172 * @param string $name The special page name
1175 public function isSpecial( $name ) {
1176 if ( $this->isSpecialPage() ) {
1177 list( $thisName, /* $subpage */ ) =
1178 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1179 resolveAlias( $this->mDbkeyform
);
1180 if ( $name == $thisName ) {
1188 * If the Title refers to a special page alias which is not the local default, resolve
1189 * the alias, and localise the name as necessary. Otherwise, return $this
1193 public function fixSpecialName() {
1194 if ( $this->isSpecialPage() ) {
1195 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1196 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1197 if ( $canonicalName ) {
1198 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1199 if ( $localName != $this->mDbkeyform
) {
1200 return self
::makeTitle( NS_SPECIAL
, $localName );
1208 * Returns true if the title is inside the specified namespace.
1210 * Please make use of this instead of comparing to getNamespace()
1211 * This function is much more resistant to changes we may make
1212 * to namespaces than code that makes direct comparisons.
1213 * @param int $ns The namespace
1217 public function inNamespace( $ns ) {
1218 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1219 equals( $this->mNamespace
, $ns );
1223 * Returns true if the title is inside one of the specified namespaces.
1225 * @param int|int[] $namespaces,... The namespaces to check for
1229 public function inNamespaces( /* ... */ ) {
1230 $namespaces = func_get_args();
1231 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1232 $namespaces = $namespaces[0];
1235 foreach ( $namespaces as $ns ) {
1236 if ( $this->inNamespace( $ns ) ) {
1245 * Returns true if the title has the same subject namespace as the
1246 * namespace specified.
1247 * For example this method will take NS_USER and return true if namespace
1248 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1249 * as their subject namespace.
1251 * This is MUCH simpler than individually testing for equivalence
1252 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1257 public function hasSubjectNamespace( $ns ) {
1258 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1259 subjectEquals( $this->mNamespace
, $ns );
1263 * Is this Title in a namespace which contains content?
1264 * In other words, is this a content page, for the purposes of calculating
1269 public function isContentPage() {
1270 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1271 isContent( $this->mNamespace
);
1275 * Would anybody with sufficient privileges be able to move this page?
1276 * Some pages just aren't movable.
1280 public function isMovable() {
1282 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1283 isMovable( $this->mNamespace
) ||
$this->isExternal()
1285 // Interwiki title or immovable namespace. Hooks don't get to override here
1290 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1295 * Is this the mainpage?
1296 * @note Title::newFromText seems to be sufficiently optimized by the title
1297 * cache that we don't need to over-optimize by doing direct comparisons and
1298 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1299 * ends up reporting something differently than $title->isMainPage();
1304 public function isMainPage() {
1305 return $this->equals( self
::newMainPage() );
1309 * Is this a subpage?
1313 public function isSubpage() {
1314 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1315 hasSubpages( $this->mNamespace
)
1316 ?
strpos( $this->getText(), '/' ) !== false
1321 * Is this a conversion table for the LanguageConverter?
1325 public function isConversionTable() {
1326 // @todo ConversionTable should become a separate content model.
1328 return $this->mNamespace
== NS_MEDIAWIKI
&&
1329 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1333 * Does that page contain wikitext, or it is JS, CSS or whatever?
1337 public function isWikitextPage() {
1338 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1342 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1343 * global UI. This is generally true for pages in the MediaWiki namespace having
1344 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1346 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1349 * Note that this method should not return true for pages that contain and show
1350 * "inactive" CSS, JSON, or JS.
1355 public function isSiteConfigPage() {
1357 $this->isSiteCssConfigPage()
1358 ||
$this->isSiteJsonConfigPage()
1359 ||
$this->isSiteJsConfigPage()
1364 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1369 public function isUserConfigPage() {
1371 $this->isUserCssConfigPage()
1372 ||
$this->isUserJsonConfigPage()
1373 ||
$this->isUserJsConfigPage()
1378 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1380 * @return string Containing skin name from .css, .json, or .js subpage title
1383 public function getSkinFromConfigSubpage() {
1384 $subpage = explode( '/', $this->mTextform
);
1385 $subpage = $subpage[count( $subpage ) - 1];
1386 $lastdot = strrpos( $subpage, '.' );
1387 if ( $lastdot === false ) {
1388 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1390 return substr( $subpage, 0, $lastdot );
1394 * Is this a CSS "config" sub-page of a user page?
1399 public function isUserCssConfigPage() {
1401 NS_USER
== $this->mNamespace
1402 && $this->isSubpage()
1403 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1408 * Is this a JSON "config" sub-page of a user page?
1413 public function isUserJsonConfigPage() {
1415 NS_USER
== $this->mNamespace
1416 && $this->isSubpage()
1417 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1422 * Is this a JS "config" sub-page of a user page?
1427 public function isUserJsConfigPage() {
1429 NS_USER
== $this->mNamespace
1430 && $this->isSubpage()
1431 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1436 * Is this a sitewide CSS "config" page?
1441 public function isSiteCssConfigPage() {
1443 NS_MEDIAWIKI
== $this->mNamespace
1445 $this->hasContentModel( CONTENT_MODEL_CSS
)
1446 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1447 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1448 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1454 * Is this a sitewide JSON "config" page?
1459 public function isSiteJsonConfigPage() {
1461 NS_MEDIAWIKI
== $this->mNamespace
1463 $this->hasContentModel( CONTENT_MODEL_JSON
)
1464 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1465 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1466 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1472 * Is this a sitewide JS "config" page?
1477 public function isSiteJsConfigPage() {
1479 NS_MEDIAWIKI
== $this->mNamespace
1481 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1482 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1483 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1484 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1490 * Is this a message which can contain raw HTML?
1495 public function isRawHtmlMessage() {
1496 global $wgRawHtmlMessages;
1498 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1501 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1502 return in_array( $message, $wgRawHtmlMessages, true );
1506 * Is this a talk page of some sort?
1510 public function isTalkPage() {
1511 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1512 isTalk( $this->mNamespace
);
1516 * Get a Title object associated with the talk page of this article
1518 * @deprecated since 1.34, use NamespaceInfo::getTalkPage
1519 * @return Title The object for the talk page
1521 public function getTalkPage() {
1522 return self
::castFromLinkTarget(
1523 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1527 * Get a Title object associated with the talk page of this article,
1528 * if such a talk page can exist.
1532 * @return Title|null The object for the talk page,
1533 * or null if no associated talk page can exist, according to canHaveTalkPage().
1535 public function getTalkPageIfDefined() {
1536 if ( !$this->canHaveTalkPage() ) {
1540 return $this->getTalkPage();
1544 * Get a title object associated with the subject page of this
1547 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1548 * @return Title The object for the subject page
1550 public function getSubjectPage() {
1551 return self
::castFromLinkTarget(
1552 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1556 * Get the other title for this page, if this is a subject page
1557 * get the talk page, if it is a subject page get the talk page
1559 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1561 * @throws MWException If the page doesn't have an other page
1564 public function getOtherPage() {
1565 return self
::castFromLinkTarget(
1566 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1570 * Get the default namespace index, for when there is no namespace
1572 * @return int Default namespace index
1574 public function getDefaultNamespace() {
1575 return $this->mDefaultNamespace
;
1579 * Get the Title fragment (i.e.\ the bit after the #) in text form
1581 * Use Title::hasFragment to check for a fragment
1583 * @return string Title fragment
1585 public function getFragment() {
1586 return $this->mFragment
;
1590 * Check if a Title fragment is set
1595 public function hasFragment() {
1596 return $this->mFragment
!== '';
1600 * Get the fragment in URL form, including the "#" character if there is one
1602 * @return string Fragment in URL form
1604 public function getFragmentForURL() {
1605 if ( !$this->hasFragment() ) {
1607 } elseif ( $this->isExternal() ) {
1608 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1609 // so we treat it like a local interwiki.
1610 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1611 if ( $interwiki && !$interwiki->isLocal() ) {
1612 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1616 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1620 * Set the fragment for this title. Removes the first character from the
1621 * specified fragment before setting, so it assumes you're passing it with
1624 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1625 * or Title::createFragmentTarget().
1626 * Still in active use privately.
1629 * @param string $fragment Text
1631 public function setFragment( $fragment ) {
1632 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1636 * Creates a new Title for a different fragment of the same page.
1639 * @param string $fragment
1642 public function createFragmentTarget( $fragment ) {
1643 return self
::makeTitle(
1652 * Prefix some arbitrary text with the namespace or interwiki prefix
1655 * @param string $name The text
1656 * @return string The prefixed text
1658 private function prefix( $name ) {
1660 if ( $this->isExternal() ) {
1661 $p = $this->mInterwiki
. ':';
1664 if ( $this->mNamespace
!= 0 ) {
1665 $nsText = $this->getNsText();
1667 if ( $nsText === false ) {
1668 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1669 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1670 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1673 $p .= $nsText . ':';
1679 * Get the prefixed database key form
1681 * @return string The prefixed title, with underscores and
1682 * any interwiki and namespace prefixes
1684 public function getPrefixedDBkey() {
1685 $s = $this->prefix( $this->mDbkeyform
);
1686 $s = strtr( $s, ' ', '_' );
1691 * Get the prefixed title with spaces.
1692 * This is the form usually used for display
1694 * @return string The prefixed title, with spaces
1696 public function getPrefixedText() {
1697 if ( $this->prefixedText
=== null ) {
1698 $s = $this->prefix( $this->mTextform
);
1699 $s = strtr( $s, '_', ' ' );
1700 $this->prefixedText
= $s;
1702 return $this->prefixedText
;
1706 * Return a string representation of this title
1708 * @return string Representation of this title
1710 public function __toString() {
1711 return $this->getPrefixedText();
1715 * Get the prefixed title with spaces, plus any fragment
1716 * (part beginning with '#')
1718 * @return string The prefixed title, with spaces and the fragment, including '#'
1720 public function getFullText() {
1721 $text = $this->getPrefixedText();
1722 if ( $this->hasFragment() ) {
1723 $text .= '#' . $this->mFragment
;
1729 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1733 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1737 * @return string Root name
1740 public function getRootText() {
1742 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1743 hasSubpages( $this->mNamespace
)
1745 return $this->getText();
1748 return strtok( $this->getText(), '/' );
1752 * Get the root page name title, i.e. the leftmost part before any slashes
1756 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1757 * # returns: Title{User:Foo}
1760 * @return Title Root title
1763 public function getRootTitle() {
1764 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1768 * Get the base page name without a namespace, i.e. the part before the subpage name
1772 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1773 * # returns: 'Foo/Bar'
1776 * @return string Base name
1778 public function getBaseText() {
1779 $text = $this->getText();
1781 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1782 hasSubpages( $this->mNamespace
)
1787 $lastSlashPos = strrpos( $text, '/' );
1788 // Don't discard the real title if there's no subpage involved
1789 if ( $lastSlashPos === false ) {
1793 return substr( $text, 0, $lastSlashPos );
1797 * Get the base page name title, i.e. the part before the subpage name
1801 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1802 * # returns: Title{User:Foo/Bar}
1805 * @return Title Base title
1808 public function getBaseTitle() {
1809 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1813 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1817 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1821 * @return string Subpage name
1823 public function getSubpageText() {
1825 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1826 hasSubpages( $this->mNamespace
)
1828 return $this->mTextform
;
1830 $parts = explode( '/', $this->mTextform
);
1831 return $parts[count( $parts ) - 1];
1835 * Get the title for a subpage of the current page
1839 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1840 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1843 * @param string $text The subpage name to add to the title
1844 * @return Title|null Subpage title, or null on an error
1847 public function getSubpage( $text ) {
1848 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1852 * Get a URL-encoded form of the subpage text
1854 * @return string URL-encoded subpage name
1856 public function getSubpageUrlForm() {
1857 $text = $this->getSubpageText();
1858 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1863 * Get a URL-encoded title (not an actual URL) including interwiki
1865 * @return string The URL-encoded form
1867 public function getPrefixedURL() {
1868 $s = $this->prefix( $this->mDbkeyform
);
1869 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1874 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1875 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1876 * second argument named variant. This was deprecated in favor
1877 * of passing an array of option with a "variant" key
1878 * Once $query2 is removed for good, this helper can be dropped
1879 * and the wfArrayToCgi moved to getLocalURL();
1881 * @since 1.19 (r105919)
1882 * @param array|string $query
1883 * @param string|string[]|bool $query2
1886 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1887 if ( $query2 !== false ) {
1888 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1889 "method called with a second parameter is deprecated. Add your " .
1890 "parameter to an array passed as the first parameter.", "1.19" );
1892 if ( is_array( $query ) ) {
1893 $query = wfArrayToCgi( $query );
1896 if ( is_string( $query2 ) ) {
1897 // $query2 is a string, we will consider this to be
1898 // a deprecated $variant argument and add it to the query
1899 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1901 $query2 = wfArrayToCgi( $query2 );
1903 // If we have $query content add a & to it first
1907 // Now append the queries together
1914 * Get a real URL referring to this title, with interwiki link and
1917 * @see self::getLocalURL for the arguments.
1919 * @param string|string[] $query
1920 * @param string|string[]|bool $query2
1921 * @param string|int|null $proto Protocol type to use in URL
1922 * @return string The URL
1924 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1925 $query = self
::fixUrlQueryArgs( $query, $query2 );
1927 # Hand off all the decisions on urls to getLocalURL
1928 $url = $this->getLocalURL( $query );
1930 # Expand the url to make it a full url. Note that getLocalURL has the
1931 # potential to output full urls for a variety of reasons, so we use
1932 # wfExpandUrl instead of simply prepending $wgServer
1933 $url = wfExpandUrl( $url, $proto );
1935 # Finally, add the fragment.
1936 $url .= $this->getFragmentForURL();
1937 // Avoid PHP 7.1 warning from passing $this by reference
1939 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1944 * Get a url appropriate for making redirects based on an untrusted url arg
1946 * This is basically the same as getFullUrl(), but in the case of external
1947 * interwikis, we send the user to a landing page, to prevent possible
1948 * phishing attacks and the like.
1950 * @note Uses current protocol by default, since technically relative urls
1951 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1952 * places where the url gets cached, as might pollute between
1953 * https and non-https users.
1954 * @see self::getLocalURL for the arguments.
1955 * @param array|string $query
1956 * @param string $proto Protocol type to use in URL
1957 * @return string A url suitable to use in an HTTP location header.
1959 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1961 if ( $this->isExternal() ) {
1962 $target = SpecialPage
::getTitleFor(
1964 $this->getPrefixedDBkey()
1967 return $target->getFullURL( $query, false, $proto );
1971 * Get a URL with no fragment or server name (relative URL) from a Title object.
1972 * If this page is generated with action=render, however,
1973 * $wgServer is prepended to make an absolute URL.
1975 * @see self::getFullURL to always get an absolute URL.
1976 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1977 * valid to link, locally, to the current Title.
1978 * @see self::newFromText to produce a Title object.
1980 * @param string|string[] $query An optional query string,
1981 * not used for interwiki links. Can be specified as an associative array as well,
1982 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
1983 * Some query patterns will trigger various shorturl path replacements.
1984 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1985 * be an array. If a string is passed it will be interpreted as a deprecated
1986 * variant argument and urlencoded into a variant= argument.
1987 * This second query argument will be added to the $query
1988 * The second parameter is deprecated since 1.19. Pass it as a key,value
1989 * pair in the first parameter array instead.
1991 * @return string String of the URL.
1993 public function getLocalURL( $query = '', $query2 = false ) {
1994 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1996 $query = self
::fixUrlQueryArgs( $query, $query2 );
1998 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2000 $namespace = $this->getNsText();
2001 if ( $namespace != '' ) {
2002 # Can this actually happen? Interwikis shouldn't be parsed.
2003 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2006 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2007 $url = wfAppendQuery( $url, $query );
2009 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2010 if ( $query == '' ) {
2011 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2012 // Avoid PHP 7.1 warning from passing $this by reference
2014 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2016 global $wgVariantArticlePath, $wgActionPaths;
2020 if ( !empty( $wgActionPaths )
2021 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2023 $action = urldecode( $matches[2] );
2024 if ( isset( $wgActionPaths[$action] ) ) {
2025 $query = $matches[1];
2026 if ( isset( $matches[4] ) ) {
2027 $query .= $matches[4];
2029 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2030 if ( $query != '' ) {
2031 $url = wfAppendQuery( $url, $query );
2037 && $wgVariantArticlePath
2038 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2039 && $this->getPageLanguage()->equals(
2040 MediaWikiServices
::getInstance()->getContentLanguage() )
2041 && $this->getPageLanguage()->hasVariants()
2043 $variant = urldecode( $matches[1] );
2044 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2045 // Only do the variant replacement if the given variant is a valid
2046 // variant for the page's language.
2047 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2048 $url = str_replace( '$1', $dbkey, $url );
2052 if ( $url === false ) {
2053 if ( $query == '-' ) {
2056 $url = "{$wgScript}?title={$dbkey}&{$query}";
2059 // Avoid PHP 7.1 warning from passing $this by reference
2061 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2063 // @todo FIXME: This causes breakage in various places when we
2064 // actually expected a local URL and end up with dupe prefixes.
2065 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2066 $url = $wgServer . $url;
2069 // Avoid PHP 7.1 warning from passing $this by reference
2071 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2076 * Get a URL that's the simplest URL that will be valid to link, locally,
2077 * to the current Title. It includes the fragment, but does not include
2078 * the server unless action=render is used (or the link is external). If
2079 * there's a fragment but the prefixed text is empty, we just return a link
2082 * The result obviously should not be URL-escaped, but does need to be
2083 * HTML-escaped if it's being output in HTML.
2085 * @param string|string[] $query
2086 * @param bool $query2
2087 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2088 * or false (default) for no expansion
2089 * @see self::getLocalURL for the arguments.
2090 * @return string The URL
2092 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2093 if ( $this->isExternal() ||
$proto !== false ) {
2094 $ret = $this->getFullURL( $query, $query2, $proto );
2095 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2096 $ret = $this->getFragmentForURL();
2098 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2104 * Get the URL form for an internal link.
2105 * - Used in various CDN-related code, in case we have a different
2106 * internal hostname for the server from the exposed one.
2108 * This uses $wgInternalServer to qualify the path, or $wgServer
2109 * if $wgInternalServer is not set. If the server variable used is
2110 * protocol-relative, the URL will be expanded to http://
2112 * @see self::getLocalURL for the arguments.
2113 * @param string|string[] $query
2114 * @param string|bool $query2 Deprecated
2115 * @return string The URL
2117 public function getInternalURL( $query = '', $query2 = false ) {
2118 global $wgInternalServer, $wgServer;
2119 $query = self
::fixUrlQueryArgs( $query, $query2 );
2120 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2121 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2122 // Avoid PHP 7.1 warning from passing $this by reference
2124 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2129 * Get the URL for a canonical link, for use in things like IRC and
2130 * e-mail notifications. Uses $wgCanonicalServer and the
2131 * GetCanonicalURL hook.
2133 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2135 * @see self::getLocalURL for the arguments.
2136 * @param string|string[] $query
2137 * @param string|bool $query2 Deprecated
2138 * @return string The URL
2141 public function getCanonicalURL( $query = '', $query2 = false ) {
2142 $query = self
::fixUrlQueryArgs( $query, $query2 );
2143 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2144 // Avoid PHP 7.1 warning from passing $this by reference
2146 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2151 * Get the edit URL for this Title
2153 * @return string The URL, or a null string if this is an interwiki link
2155 public function getEditURL() {
2156 if ( $this->isExternal() ) {
2159 $s = $this->getLocalURL( 'action=edit' );
2165 * Can $user perform $action on this page?
2166 * This skips potentially expensive cascading permission checks
2167 * as well as avoids expensive error formatting
2169 * Suitable for use for nonessential UI controls in common cases, but
2170 * _not_ for functional access control.
2172 * May provide false positives, but should never provide a false negative.
2174 * @param string $action Action that permission needs to be checked for
2175 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2180 * @deprecated since 1.33,
2181 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2184 public function quickUserCan( $action, $user = null ) {
2185 return $this->userCan( $action, $user, false );
2189 * Can $user perform $action on this page?
2191 * @param string $action Action that permission needs to be checked for
2192 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2194 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2199 * @deprecated since 1.33,
2200 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2203 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2204 if ( !$user instanceof User
) {
2209 // TODO: this is for b/c, eventually will be removed
2210 if ( $rigor === true ) {
2211 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2212 } elseif ( $rigor === false ) {
2213 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2216 return MediaWikiServices
::getInstance()->getPermissionManager()
2217 ->userCan( $action, $user, $this, $rigor );
2221 * Can $user perform $action on this page?
2223 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2225 * @param string $action Action that permission needs to be checked for
2226 * @param User $user User to check
2227 * @param string $rigor One of (quick,full,secure)
2228 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2229 * - full : does cheap and expensive checks possibly from a replica DB
2230 * - secure : does cheap and expensive checks, using the master as needed
2231 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2232 * whose corresponding errors may be ignored.
2234 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2237 * @deprecated since 1.33,
2238 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2241 public function getUserPermissionsErrors(
2242 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2244 // TODO: this is for b/c, eventually will be removed
2245 if ( $rigor === true ) {
2246 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2247 } elseif ( $rigor === false ) {
2248 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2251 return MediaWikiServices
::getInstance()->getPermissionManager()
2252 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2256 * Add the resulting error code to the errors array
2258 * @param array $errors List of current errors
2259 * @param array $result Result of errors
2261 * @return array List of errors
2263 private function resultToError( $errors, $result ) {
2264 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2265 // A single array representing an error
2266 $errors[] = $result;
2267 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2268 // A nested array representing multiple errors
2269 $errors = array_merge( $errors, $result );
2270 } elseif ( $result !== '' && is_string( $result ) ) {
2271 // A string representing a message-id
2272 $errors[] = [ $result ];
2273 } elseif ( $result instanceof MessageSpecifier
) {
2274 // A message specifier representing an error
2275 $errors[] = [ $result ];
2276 } elseif ( $result === false ) {
2277 // a generic "We don't want them to do that"
2278 $errors[] = [ 'badaccess-group0' ];
2284 * Get a filtered list of all restriction types supported by this wiki.
2285 * @param bool $exists True to get all restriction types that apply to
2286 * titles that do exist, False for all restriction types that apply to
2287 * titles that do not exist
2290 public static function getFilteredRestrictionTypes( $exists = true ) {
2291 global $wgRestrictionTypes;
2292 $types = $wgRestrictionTypes;
2294 # Remove the create restriction for existing titles
2295 $types = array_diff( $types, [ 'create' ] );
2297 # Only the create and upload restrictions apply to non-existing titles
2298 $types = array_intersect( $types, [ 'create', 'upload' ] );
2304 * Returns restriction types for the current Title
2306 * @return array Applicable restriction types
2308 public function getRestrictionTypes() {
2309 if ( $this->isSpecialPage() ) {
2313 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2315 if ( $this->mNamespace
!= NS_FILE
) {
2316 # Remove the upload restriction for non-file titles
2317 $types = array_diff( $types, [ 'upload' ] );
2320 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2322 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2323 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2329 * Is this title subject to title protection?
2330 * Title protection is the one applied against creation of such title.
2332 * @return array|bool An associative array representing any existent title
2333 * protection, or false if there's none.
2335 public function getTitleProtection() {
2336 $protection = $this->getTitleProtectionInternal();
2337 if ( $protection ) {
2338 if ( $protection['permission'] == 'sysop' ) {
2339 $protection['permission'] = 'editprotected'; // B/C
2341 if ( $protection['permission'] == 'autoconfirmed' ) {
2342 $protection['permission'] = 'editsemiprotected'; // B/C
2349 * Fetch title protection settings
2351 * To work correctly, $this->loadRestrictions() needs to have access to the
2352 * actual protections in the database without munging 'sysop' =>
2353 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2354 * callers probably want $this->getTitleProtection() instead.
2356 * @return array|bool
2358 protected function getTitleProtectionInternal() {
2359 // Can't protect pages in special namespaces
2360 if ( $this->mNamespace
< 0 ) {
2364 // Can't protect pages that exist.
2365 if ( $this->exists() ) {
2369 if ( $this->mTitleProtection
=== null ) {
2370 $dbr = wfGetDB( DB_REPLICA
);
2371 $commentStore = CommentStore
::getStore();
2372 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2373 $res = $dbr->select(
2374 [ 'protected_titles' ] +
$commentQuery['tables'],
2376 'user' => 'pt_user',
2377 'expiry' => 'pt_expiry',
2378 'permission' => 'pt_create_perm'
2379 ] +
$commentQuery['fields'],
2380 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2383 $commentQuery['joins']
2386 // fetchRow returns false if there are no rows.
2387 $row = $dbr->fetchRow( $res );
2389 $this->mTitleProtection
= [
2390 'user' => $row['user'],
2391 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2392 'permission' => $row['permission'],
2393 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2396 $this->mTitleProtection
= false;
2399 return $this->mTitleProtection
;
2403 * Remove any title protection due to page existing
2405 public function deleteTitleProtection() {
2406 $dbw = wfGetDB( DB_MASTER
);
2410 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2413 $this->mTitleProtection
= false;
2417 * Is this page "semi-protected" - the *only* protection levels are listed
2418 * in $wgSemiprotectedRestrictionLevels?
2420 * @param string $action Action to check (default: edit)
2423 public function isSemiProtected( $action = 'edit' ) {
2424 global $wgSemiprotectedRestrictionLevels;
2426 $restrictions = $this->getRestrictions( $action );
2427 $semi = $wgSemiprotectedRestrictionLevels;
2428 if ( !$restrictions ||
!$semi ) {
2429 // Not protected, or all protection is full protection
2433 // Remap autoconfirmed to editsemiprotected for BC
2434 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2435 $semi[$key] = 'editsemiprotected';
2437 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2438 $restrictions[$key] = 'editsemiprotected';
2441 return !array_diff( $restrictions, $semi );
2445 * Does the title correspond to a protected article?
2447 * @param string $action The action the page is protected from,
2448 * by default checks all actions.
2451 public function isProtected( $action = '' ) {
2452 global $wgRestrictionLevels;
2454 $restrictionTypes = $this->getRestrictionTypes();
2456 # Special pages have inherent protection
2457 if ( $this->isSpecialPage() ) {
2461 # Check regular protection levels
2462 foreach ( $restrictionTypes as $type ) {
2463 if ( $action == $type ||
$action == '' ) {
2464 $r = $this->getRestrictions( $type );
2465 foreach ( $wgRestrictionLevels as $level ) {
2466 if ( in_array( $level, $r ) && $level != '' ) {
2477 * Determines if $user is unable to edit this page because it has been protected
2478 * by $wgNamespaceProtection.
2480 * @param User $user User object to check permissions
2483 public function isNamespaceProtected( User
$user ) {
2484 global $wgNamespaceProtection;
2486 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2487 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2488 if ( $right != '' && !$user->isAllowed( $right ) ) {
2497 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2499 * @return bool If the page is subject to cascading restrictions.
2501 public function isCascadeProtected() {
2502 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2503 return ( $sources > 0 );
2507 * Determines whether cascading protection sources have already been loaded from
2510 * @param bool $getPages True to check if the pages are loaded, or false to check
2511 * if the status is loaded.
2512 * @return bool Whether or not the specified information has been loaded
2515 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2516 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2520 * Cascading protection: Get the source of any cascading restrictions on this page.
2522 * @param bool $getPages Whether or not to retrieve the actual pages
2523 * that the restrictions have come from and the actual restrictions
2525 * @return array Two elements: First is an array of Title objects of the
2526 * pages from which cascading restrictions have come, false for
2527 * none, or true if such restrictions exist but $getPages was not
2528 * set. Second is an array like that returned by
2529 * Title::getAllRestrictions(), or an empty array if $getPages is
2532 public function getCascadeProtectionSources( $getPages = true ) {
2533 $pagerestrictions = [];
2535 if ( $this->mCascadeSources
!== null && $getPages ) {
2536 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2537 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2538 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2541 $dbr = wfGetDB( DB_REPLICA
);
2543 if ( $this->mNamespace
== NS_FILE
) {
2544 $tables = [ 'imagelinks', 'page_restrictions' ];
2546 'il_to' => $this->mDbkeyform
,
2551 $tables = [ 'templatelinks', 'page_restrictions' ];
2553 'tl_namespace' => $this->mNamespace
,
2554 'tl_title' => $this->mDbkeyform
,
2561 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2562 'pr_expiry', 'pr_type', 'pr_level' ];
2563 $where_clauses[] = 'page_id=pr_page';
2566 $cols = [ 'pr_expiry' ];
2569 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2571 $sources = $getPages ?
[] : false;
2572 $now = wfTimestampNow();
2574 foreach ( $res as $row ) {
2575 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2576 if ( $expiry > $now ) {
2578 $page_id = $row->pr_page
;
2579 $page_ns = $row->page_namespace
;
2580 $page_title = $row->page_title
;
2581 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2582 # Add groups needed for each restriction type if its not already there
2583 # Make sure this restriction type still exists
2585 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2586 $pagerestrictions[$row->pr_type
] = [];
2590 isset( $pagerestrictions[$row->pr_type
] )
2591 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2593 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2602 $this->mCascadeSources
= $sources;
2603 $this->mCascadingRestrictions
= $pagerestrictions;
2605 $this->mHasCascadingRestrictions
= $sources;
2608 return [ $sources, $pagerestrictions ];
2612 * Accessor for mRestrictionsLoaded
2614 * @return bool Whether or not the page's restrictions have already been
2615 * loaded from the database
2618 public function areRestrictionsLoaded() {
2619 return $this->mRestrictionsLoaded
;
2623 * Accessor/initialisation for mRestrictions
2625 * @param string $action Action that permission needs to be checked for
2626 * @return array Restriction levels needed to take the action. All levels are
2627 * required. Note that restriction levels are normally user rights, but 'sysop'
2628 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2629 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2631 public function getRestrictions( $action ) {
2632 if ( !$this->mRestrictionsLoaded
) {
2633 $this->loadRestrictions();
2635 return $this->mRestrictions
[$action] ??
[];
2639 * Accessor/initialisation for mRestrictions
2641 * @return array Keys are actions, values are arrays as returned by
2642 * Title::getRestrictions()
2645 public function getAllRestrictions() {
2646 if ( !$this->mRestrictionsLoaded
) {
2647 $this->loadRestrictions();
2649 return $this->mRestrictions
;
2653 * Get the expiry time for the restriction against a given action
2655 * @param string $action
2656 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2657 * or not protected at all, or false if the action is not recognised.
2659 public function getRestrictionExpiry( $action ) {
2660 if ( !$this->mRestrictionsLoaded
) {
2661 $this->loadRestrictions();
2663 return $this->mRestrictionsExpiry
[$action] ??
false;
2667 * Returns cascading restrictions for the current article
2671 function areRestrictionsCascading() {
2672 if ( !$this->mRestrictionsLoaded
) {
2673 $this->loadRestrictions();
2676 return $this->mCascadeRestriction
;
2680 * Compiles list of active page restrictions from both page table (pre 1.10)
2681 * and page_restrictions table for this existing page.
2682 * Public for usage by LiquidThreads.
2684 * @param array $rows Array of db result objects
2685 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2686 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2687 * Edit and move sections are separated by a colon
2688 * Example: "edit=autoconfirmed,sysop:move=sysop"
2690 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2691 // This function will only read rows from a table that we migrated away
2692 // from before adding READ_LATEST support to loadRestrictions, so we
2693 // don't need to support reading from DB_MASTER here.
2694 $dbr = wfGetDB( DB_REPLICA
);
2696 $restrictionTypes = $this->getRestrictionTypes();
2698 foreach ( $restrictionTypes as $type ) {
2699 $this->mRestrictions
[$type] = [];
2700 $this->mRestrictionsExpiry
[$type] = 'infinity';
2703 $this->mCascadeRestriction
= false;
2705 # Backwards-compatibility: also load the restrictions from the page record (old format).
2706 if ( $oldFashionedRestrictions !== null ) {
2707 $this->mOldRestrictions
= $oldFashionedRestrictions;
2710 if ( $this->mOldRestrictions
=== false ) {
2711 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2712 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2713 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2716 if ( $this->mOldRestrictions
!= '' ) {
2717 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2718 $temp = explode( '=', trim( $restrict ) );
2719 if ( count( $temp ) == 1 ) {
2720 // old old format should be treated as edit/move restriction
2721 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2722 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2724 $restriction = trim( $temp[1] );
2725 if ( $restriction != '' ) { // some old entries are empty
2726 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2732 if ( count( $rows ) ) {
2733 # Current system - load second to make them override.
2734 $now = wfTimestampNow();
2736 # Cycle through all the restrictions.
2737 foreach ( $rows as $row ) {
2738 // Don't take care of restrictions types that aren't allowed
2739 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2743 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2745 // Only apply the restrictions if they haven't expired!
2746 if ( !$expiry ||
$expiry > $now ) {
2747 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2748 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2750 $this->mCascadeRestriction |
= $row->pr_cascade
;
2755 $this->mRestrictionsLoaded
= true;
2759 * Load restrictions from the page_restrictions table
2761 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2762 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2763 * Edit and move sections are separated by a colon
2764 * Example: "edit=autoconfirmed,sysop:move=sysop"
2765 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2766 * from the master DB.
2768 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2769 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2770 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2774 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2775 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2776 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2777 $id = $this->getArticleID();
2779 $fname = __METHOD__
;
2780 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2781 return iterator_to_array(
2783 'page_restrictions',
2784 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2785 [ 'pr_page' => $id ],
2791 if ( $readLatest ) {
2792 $dbr = wfGetDB( DB_MASTER
);
2793 $rows = $loadRestrictionsFromDb( $dbr );
2795 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2796 $rows = $cache->getWithSetCallback(
2797 // Page protections always leave a new null revision
2798 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2800 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2801 $dbr = wfGetDB( DB_REPLICA
);
2803 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2804 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2805 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2806 // @TODO: cleanup Title cache and caller assumption mess in general
2807 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2810 return $loadRestrictionsFromDb( $dbr );
2815 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2817 $title_protection = $this->getTitleProtectionInternal();
2819 if ( $title_protection ) {
2820 $now = wfTimestampNow();
2821 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2823 if ( !$expiry ||
$expiry > $now ) {
2824 // Apply the restrictions
2825 $this->mRestrictionsExpiry
['create'] = $expiry;
2826 $this->mRestrictions
['create'] =
2827 explode( ',', trim( $title_protection['permission'] ) );
2828 } else { // Get rid of the old restrictions
2829 $this->mTitleProtection
= false;
2832 $this->mRestrictionsExpiry
['create'] = 'infinity';
2834 $this->mRestrictionsLoaded
= true;
2839 * Flush the protection cache in this object and force reload from the database.
2840 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2842 public function flushRestrictions() {
2843 $this->mRestrictionsLoaded
= false;
2844 $this->mTitleProtection
= null;
2848 * Purge expired restrictions from the page_restrictions table
2850 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2852 static function purgeExpiredRestrictions() {
2853 if ( wfReadOnly() ) {
2857 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2858 wfGetDB( DB_MASTER
),
2860 function ( IDatabase
$dbw, $fname ) {
2861 $config = MediaWikiServices
::getInstance()->getMainConfig();
2862 $ids = $dbw->selectFieldValues(
2863 'page_restrictions',
2865 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2867 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2870 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2875 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2876 wfGetDB( DB_MASTER
),
2878 function ( IDatabase
$dbw, $fname ) {
2881 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2889 * Does this have subpages? (Warning, usually requires an extra DB query.)
2893 public function hasSubpages() {
2895 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2896 hasSubpages( $this->mNamespace
)
2902 # We dynamically add a member variable for the purpose of this method
2903 # alone to cache the result. There's no point in having it hanging
2904 # around uninitialized in every Title object; therefore we only add it
2905 # if needed and don't declare it statically.
2906 if ( $this->mHasSubpages
=== null ) {
2907 $this->mHasSubpages
= false;
2908 $subpages = $this->getSubpages( 1 );
2909 if ( $subpages instanceof TitleArray
) {
2910 $this->mHasSubpages
= (bool)$subpages->count();
2914 return $this->mHasSubpages
;
2918 * Get all subpages of this page.
2920 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2921 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2922 * doesn't allow subpages
2924 public function getSubpages( $limit = -1 ) {
2926 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2927 hasSubpages( $this->mNamespace
)
2932 $dbr = wfGetDB( DB_REPLICA
);
2933 $conds['page_namespace'] = $this->mNamespace
;
2934 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2936 if ( $limit > -1 ) {
2937 $options['LIMIT'] = $limit;
2939 return TitleArray
::newFromResult(
2940 $dbr->select( 'page',
2941 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2950 * Is there a version of this page in the deletion archive?
2952 * @return int The number of archived revisions
2954 public function isDeleted() {
2955 if ( $this->mNamespace
< 0 ) {
2958 $dbr = wfGetDB( DB_REPLICA
);
2960 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2961 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2964 if ( $this->mNamespace
== NS_FILE
) {
2965 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2966 [ 'fa_name' => $this->mDbkeyform
],
2975 * Is there a version of this page in the deletion archive?
2979 public function isDeletedQuick() {
2980 if ( $this->mNamespace
< 0 ) {
2983 $dbr = wfGetDB( DB_REPLICA
);
2984 $deleted = (bool)$dbr->selectField( 'archive', '1',
2985 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2988 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
2989 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2990 [ 'fa_name' => $this->mDbkeyform
],
2998 * Get the article ID for this Title from the link cache,
2999 * adding it if necessary
3001 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3003 * @return int The ID
3005 public function getArticleID( $flags = 0 ) {
3006 if ( $this->mNamespace
< 0 ) {
3007 $this->mArticleID
= 0;
3008 return $this->mArticleID
;
3010 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3011 if ( $flags & self
::GAID_FOR_UPDATE
) {
3012 $oldUpdate = $linkCache->forUpdate( true );
3013 $linkCache->clearLink( $this );
3014 $this->mArticleID
= $linkCache->addLinkObj( $this );
3015 $linkCache->forUpdate( $oldUpdate );
3016 } elseif ( $this->mArticleID
== -1 ) {
3017 $this->mArticleID
= $linkCache->addLinkObj( $this );
3019 return $this->mArticleID
;
3023 * Is this an article that is a redirect page?
3024 * Uses link cache, adding it if necessary
3026 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3029 public function isRedirect( $flags = 0 ) {
3030 if ( !is_null( $this->mRedirect
) ) {
3031 return $this->mRedirect
;
3033 if ( !$this->getArticleID( $flags ) ) {
3034 $this->mRedirect
= false;
3035 return $this->mRedirect
;
3038 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3039 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3040 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3041 if ( $cached === null ) {
3042 # Trust LinkCache's state over our own
3043 # LinkCache is telling us that the page doesn't exist, despite there being cached
3044 # data relating to an existing page in $this->mArticleID. Updaters should clear
3045 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3046 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3047 # LinkCache to refresh its data from the master.
3048 $this->mRedirect
= false;
3049 return $this->mRedirect
;
3052 $this->mRedirect
= (bool)$cached;
3054 return $this->mRedirect
;
3058 * What is the length of this page?
3059 * Uses link cache, adding it if necessary
3061 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3064 public function getLength( $flags = 0 ) {
3065 if ( $this->mLength
!= -1 ) {
3066 return $this->mLength
;
3068 if ( !$this->getArticleID( $flags ) ) {
3070 return $this->mLength
;
3072 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3073 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3074 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3075 if ( $cached === null ) {
3076 # Trust LinkCache's state over our own, as for isRedirect()
3078 return $this->mLength
;
3081 $this->mLength
= intval( $cached );
3083 return $this->mLength
;
3087 * What is the page_latest field for this page?
3089 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3090 * @return int Int or 0 if the page doesn't exist
3092 public function getLatestRevID( $flags = 0 ) {
3093 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3094 return intval( $this->mLatestID
);
3096 if ( !$this->getArticleID( $flags ) ) {
3097 $this->mLatestID
= 0;
3098 return $this->mLatestID
;
3100 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3101 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3102 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3103 if ( $cached === null ) {
3104 # Trust LinkCache's state over our own, as for isRedirect()
3105 $this->mLatestID
= 0;
3106 return $this->mLatestID
;
3109 $this->mLatestID
= intval( $cached );
3111 return $this->mLatestID
;
3115 * This clears some fields in this object, and clears any associated
3116 * keys in the "bad links" section of the link cache.
3118 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3119 * loading of the new page_id. It's also called from
3120 * WikiPage::doDeleteArticleReal()
3122 * @param int $newid The new Article ID
3124 public function resetArticleID( $newid ) {
3125 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3126 $linkCache->clearLink( $this );
3128 if ( $newid === false ) {
3129 $this->mArticleID
= -1;
3131 $this->mArticleID
= intval( $newid );
3133 $this->mRestrictionsLoaded
= false;
3134 $this->mRestrictions
= [];
3135 $this->mOldRestrictions
= false;
3136 $this->mRedirect
= null;
3137 $this->mLength
= -1;
3138 $this->mLatestID
= false;
3139 $this->mContentModel
= false;
3140 $this->mEstimateRevisions
= null;
3141 $this->mPageLanguage
= false;
3142 $this->mDbPageLanguage
= false;
3143 $this->mIsBigDeletion
= null;
3146 public static function clearCaches() {
3147 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3148 $linkCache->clear();
3150 $titleCache = self
::getTitleCache();
3151 $titleCache->clear();
3155 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3157 * @param string $text Containing title to capitalize
3158 * @param int $ns Namespace index, defaults to NS_MAIN
3159 * @return string Containing capitalized title
3161 public static function capitalize( $text, $ns = NS_MAIN
) {
3162 $services = MediaWikiServices
::getInstance();
3163 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3164 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3171 * Secure and split - main initialisation function for this object
3173 * Assumes that mDbkeyform has been set, and is urldecoded
3174 * and uses underscores, but not otherwise munged. This function
3175 * removes illegal characters, splits off the interwiki and
3176 * namespace prefixes, sets the other forms, and canonicalizes
3179 * @throws MalformedTitleException On invalid titles
3180 * @return bool True on success
3182 private function secureAndSplit() {
3183 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3184 // the parsing code with Title, while avoiding massive refactoring.
3185 // @todo: get rid of secureAndSplit, refactor parsing code.
3186 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3187 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3188 /** @var MediaWikiTitleCodec $titleCodec */
3189 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3190 // MalformedTitleException can be thrown here
3191 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3194 $this->setFragment( '#' . $parts['fragment'] );
3195 $this->mInterwiki
= $parts['interwiki'];
3196 $this->mLocalInterwiki
= $parts['local_interwiki'];
3197 $this->mNamespace
= $parts['namespace'];
3198 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3200 $this->mDbkeyform
= $parts['dbkey'];
3201 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3202 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3204 # We already know that some pages won't be in the database!
3205 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3206 $this->mArticleID
= 0;
3213 * Get an array of Title objects linking to this Title
3214 * Also stores the IDs in the link cache.
3216 * WARNING: do not use this function on arbitrary user-supplied titles!
3217 * On heavily-used templates it will max out the memory.
3219 * @param array $options May be FOR UPDATE
3220 * @param string $table Table name
3221 * @param string $prefix Fields prefix
3222 * @return Title[] Array of Title objects linking here
3224 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3225 if ( count( $options ) > 0 ) {
3226 $db = wfGetDB( DB_MASTER
);
3228 $db = wfGetDB( DB_REPLICA
);
3233 self
::getSelectFields(),
3235 "{$prefix}_from=page_id",
3236 "{$prefix}_namespace" => $this->mNamespace
,
3237 "{$prefix}_title" => $this->mDbkeyform
],
3243 if ( $res->numRows() ) {
3244 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3245 foreach ( $res as $row ) {
3246 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3248 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3249 $retVal[] = $titleObj;
3257 * Get an array of Title objects using this Title as a template
3258 * Also stores the IDs in the link cache.
3260 * WARNING: do not use this function on arbitrary user-supplied titles!
3261 * On heavily-used templates it will max out the memory.
3263 * @param array $options Query option to Database::select()
3264 * @return Title[] Array of Title the Title objects linking here
3266 public function getTemplateLinksTo( $options = [] ) {
3267 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3271 * Get an array of Title objects linked from this Title
3272 * Also stores the IDs in the link cache.
3274 * WARNING: do not use this function on arbitrary user-supplied titles!
3275 * On heavily-used templates it will max out the memory.
3277 * @param array $options Query option to Database::select()
3278 * @param string $table Table name
3279 * @param string $prefix Fields prefix
3280 * @return array Array of Title objects linking here
3282 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3283 $id = $this->getArticleID();
3285 # If the page doesn't exist; there can't be any link from this page
3290 $db = wfGetDB( DB_REPLICA
);
3292 $blNamespace = "{$prefix}_namespace";
3293 $blTitle = "{$prefix}_title";
3295 $pageQuery = WikiPage
::getQueryInfo();
3297 [ $table, 'nestpage' => $pageQuery['tables'] ],
3299 [ $blNamespace, $blTitle ],
3300 $pageQuery['fields']
3302 [ "{$prefix}_from" => $id ],
3307 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3308 ] ] +
$pageQuery['joins']
3312 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3313 foreach ( $res as $row ) {
3314 if ( $row->page_id
) {
3315 $titleObj = self
::newFromRow( $row );
3317 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3318 $linkCache->addBadLinkObj( $titleObj );
3320 $retVal[] = $titleObj;
3327 * Get an array of Title objects used on this Title as a template
3328 * Also stores the IDs in the link cache.
3330 * WARNING: do not use this function on arbitrary user-supplied titles!
3331 * On heavily-used templates it will max out the memory.
3333 * @param array $options May be FOR UPDATE
3334 * @return Title[] Array of Title the Title objects used here
3336 public function getTemplateLinksFrom( $options = [] ) {
3337 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3341 * Get an array of Title objects referring to non-existent articles linked
3344 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3345 * should use redirect table in this case).
3346 * @return Title[] Array of Title the Title objects
3348 public function getBrokenLinksFrom() {
3349 if ( $this->getArticleID() == 0 ) {
3350 # All links from article ID 0 are false positives
3354 $dbr = wfGetDB( DB_REPLICA
);
3355 $res = $dbr->select(
3356 [ 'page', 'pagelinks' ],
3357 [ 'pl_namespace', 'pl_title' ],
3359 'pl_from' => $this->getArticleID(),
3360 'page_namespace IS NULL'
3366 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3372 foreach ( $res as $row ) {
3373 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3379 * Get a list of URLs to purge from the CDN cache when this
3382 * @return string[] Array of String the URLs
3384 public function getCdnUrls() {
3386 $this->getInternalURL(),
3387 $this->getInternalURL( 'action=history' )
3390 $pageLang = $this->getPageLanguage();
3391 if ( $pageLang->hasVariants() ) {
3392 $variants = $pageLang->getVariants();
3393 foreach ( $variants as $vCode ) {
3394 $urls[] = $this->getInternalURL( $vCode );
3398 // If we are looking at a css/js user subpage, purge the action=raw.
3399 if ( $this->isUserJsConfigPage() ) {
3400 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3401 } elseif ( $this->isUserJsonConfigPage() ) {
3402 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3403 } elseif ( $this->isUserCssConfigPage() ) {
3404 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3407 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3412 * Purge all applicable CDN URLs
3414 public function purgeSquid() {
3415 DeferredUpdates
::addUpdate(
3416 new CdnCacheUpdate( $this->getCdnUrls() ),
3417 DeferredUpdates
::PRESEND
3422 * Check whether a given move operation would be valid.
3423 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3425 * @deprecated since 1.25, use MovePage's methods instead
3426 * @param Title &$nt The new title
3427 * @param bool $auth Whether to check user permissions (uses $wgUser)
3428 * @param string $reason Is the log summary of the move, used for spam checking
3429 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3431 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3432 wfDeprecated( __METHOD__
, '1.25' );
3436 if ( !( $nt instanceof Title
) ) {
3437 // Normally we'd add this to $errors, but we'll get
3438 // lots of syntax errors if $nt is not an object
3439 return [ [ 'badtitletext' ] ];
3442 $mp = new MovePage( $this, $nt );
3443 $errors = $mp->isValidMove()->getErrorsArray();
3445 $errors = wfMergeErrorArrays(
3447 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3451 return $errors ?
: true;
3455 * Move a title to a new location
3457 * @deprecated since 1.25, use the MovePage class instead
3458 * @param Title &$nt The new title
3459 * @param bool $auth Indicates whether $wgUser's permissions
3461 * @param string $reason The reason for the move
3462 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3463 * Ignored if the user doesn't have the suppressredirect right.
3464 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3465 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3467 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3468 array $changeTags = []
3470 wfDeprecated( __METHOD__
, '1.25' );
3474 $mp = new MovePage( $this, $nt );
3475 $method = $auth ?
'moveIfAllowed' : 'move';
3476 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3477 if ( $status->isOK() ) {
3480 return $status->getErrorsArray();
3485 * Move this page's subpages to be subpages of $nt
3487 * @deprecated since 1.34, use MovePage instead
3488 * @param Title $nt Move target
3489 * @param bool $auth Whether $wgUser's permissions should be checked
3490 * @param string $reason The reason for the move
3491 * @param bool $createRedirect Whether to create redirects from the old subpages to
3492 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3493 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3494 * @return array Array with old page titles as keys, and strings (new page titles) or
3495 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3496 * getUserPermissionsErrors()-like error array with numeric indices if
3497 * no pages were moved
3499 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3500 array $changeTags = []
3502 wfDeprecated( __METHOD__
, '1.34' );
3506 $mp = new MovePage( $this, $nt );
3507 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3508 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3510 if ( !$result->isOk() ) {
3511 return $result->getErrorsArray();
3515 foreach ( $result->getValue() as $key => $status ) {
3516 if ( $status->isOK() ) {
3517 $retval[$key] = $status->getValue();
3519 $retval[$key] = $status->getErrorsArray();
3526 * Checks if this page is just a one-rev redirect.
3527 * Adds lock, so don't use just for light purposes.
3531 public function isSingleRevRedirect() {
3532 global $wgContentHandlerUseDB;
3534 $dbw = wfGetDB( DB_MASTER
);
3537 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3538 if ( $wgContentHandlerUseDB ) {
3539 $fields[] = 'page_content_model';
3542 $row = $dbw->selectRow( 'page',
3548 # Cache some fields we may want
3549 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3550 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3551 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3552 $this->mContentModel
= $row && isset( $row->page_content_model
)
3553 ?
strval( $row->page_content_model
)
3556 if ( !$this->mRedirect
) {
3559 # Does the article have a history?
3560 $row = $dbw->selectField( [ 'page', 'revision' ],
3562 [ 'page_namespace' => $this->mNamespace
,
3563 'page_title' => $this->mDbkeyform
,
3565 'page_latest != rev_id'
3570 # Return true if there was no history
3571 return ( $row === false );
3575 * Checks if $this can be moved to a given Title
3576 * - Selects for update, so don't call it unless you mean business
3578 * @deprecated since 1.25, use MovePage's methods instead
3579 * @param Title $nt The new title to check
3582 public function isValidMoveTarget( $nt ) {
3583 wfDeprecated( __METHOD__
, '1.25' );
3585 # Is it an existing file?
3586 if ( $nt->getNamespace() == NS_FILE
) {
3587 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3589 $file->load( File
::READ_LATEST
);
3590 if ( $file->exists() ) {
3591 wfDebug( __METHOD__
. ": file exists\n" );
3595 # Is it a redirect with no history?
3596 if ( !$nt->isSingleRevRedirect() ) {
3597 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3600 # Get the article text
3601 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3602 if ( !is_object( $rev ) ) {
3605 $content = $rev->getContent();
3606 # Does the redirect point to the source?
3607 # Or is it a broken self-redirect, usually caused by namespace collisions?
3608 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3610 if ( $redirTitle ) {
3611 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3612 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3613 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3619 # Fail safe (not a redirect after all. strange.)
3620 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3621 " is a redirect, but it doesn't contain a valid redirect.\n" );
3627 * Get categories to which this Title belongs and return an array of
3628 * categories' names.
3630 * @return array Array of parents in the form:
3631 * $parent => $currentarticle
3633 public function getParentCategories() {
3636 $titleKey = $this->getArticleID();
3638 if ( $titleKey === 0 ) {
3642 $dbr = wfGetDB( DB_REPLICA
);
3644 $res = $dbr->select(
3647 [ 'cl_from' => $titleKey ],
3651 if ( $res->numRows() > 0 ) {
3652 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3653 foreach ( $res as $row ) {
3654 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3655 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3656 $this->getFullText();
3663 * Get a tree of parent categories
3665 * @param array $children Array with the children in the keys, to check for circular refs
3666 * @return array Tree of parent categories
3668 public function getParentCategoryTree( $children = [] ) {
3670 $parents = $this->getParentCategories();
3673 foreach ( $parents as $parent => $current ) {
3674 if ( array_key_exists( $parent, $children ) ) {
3675 # Circular reference
3676 $stack[$parent] = [];
3678 $nt = self
::newFromText( $parent );
3680 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3690 * Get an associative array for selecting this title from
3693 * @return array Array suitable for the $where parameter of DB::select()
3695 public function pageCond() {
3696 if ( $this->mArticleID
> 0 ) {
3697 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3698 return [ 'page_id' => $this->mArticleID
];
3700 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3705 * Get next/previous revision ID relative to another revision ID
3706 * @param int $revId Revision ID. Get the revision that was before this one.
3707 * @param int $flags Title::GAID_FOR_UPDATE
3708 * @param string $dir 'next' or 'prev'
3709 * @return int|bool New revision ID, or false if none exists
3711 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3712 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3713 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3714 $rev = $rl->getRevisionById( $revId, $rlFlags );
3718 $oldRev = $dir === 'next'
3719 ?
$rl->getNextRevision( $rev, $rlFlags )
3720 : $rl->getPreviousRevision( $rev, $rlFlags );
3724 return $oldRev->getId();
3728 * Get the revision ID of the previous revision
3730 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3731 * @param int $revId Revision ID. Get the revision that was before this one.
3732 * @param int $flags Title::GAID_FOR_UPDATE
3733 * @return int|bool Old revision ID, or false if none exists
3735 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3736 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3740 * Get the revision ID of the next revision
3742 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3743 * @param int $revId Revision ID. Get the revision that was after this one.
3744 * @param int $flags Title::GAID_FOR_UPDATE
3745 * @return int|bool Next revision ID, or false if none exists
3747 public function getNextRevisionID( $revId, $flags = 0 ) {
3748 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3752 * Get the first revision of the page
3754 * @param int $flags Title::GAID_FOR_UPDATE
3755 * @return Revision|null If page doesn't exist
3757 public function getFirstRevision( $flags = 0 ) {
3758 $pageId = $this->getArticleID( $flags );
3760 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3761 $revQuery = Revision
::getQueryInfo();
3762 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3763 [ 'rev_page' => $pageId ],
3766 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3767 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3772 return new Revision( $row, 0, $this );
3779 * Get the oldest revision timestamp of this page
3781 * @param int $flags Title::GAID_FOR_UPDATE
3782 * @return string|null MW timestamp
3784 public function getEarliestRevTime( $flags = 0 ) {
3785 $rev = $this->getFirstRevision( $flags );
3786 return $rev ?
$rev->getTimestamp() : null;
3790 * Check if this is a new page
3794 public function isNewPage() {
3795 $dbr = wfGetDB( DB_REPLICA
);
3796 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3800 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3804 public function isBigDeletion() {
3805 global $wgDeleteRevisionsLimit;
3807 if ( !$wgDeleteRevisionsLimit ) {
3811 if ( $this->mIsBigDeletion
=== null ) {
3812 $dbr = wfGetDB( DB_REPLICA
);
3814 $revCount = $dbr->selectRowCount(
3817 [ 'rev_page' => $this->getArticleID() ],
3819 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3822 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3825 return $this->mIsBigDeletion
;
3829 * Get the approximate revision count of this page.
3833 public function estimateRevisionCount() {
3834 if ( !$this->exists() ) {
3838 if ( $this->mEstimateRevisions
=== null ) {
3839 $dbr = wfGetDB( DB_REPLICA
);
3840 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3841 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3844 return $this->mEstimateRevisions
;
3848 * Get the number of revisions between the given revision.
3849 * Used for diffs and other things that really need it.
3851 * @param int|Revision $old Old revision or rev ID (first before range)
3852 * @param int|Revision $new New revision or rev ID (first after range)
3853 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3854 * @return int Number of revisions between these revisions.
3856 public function countRevisionsBetween( $old, $new, $max = null ) {
3857 if ( !( $old instanceof Revision
) ) {
3858 $old = Revision
::newFromTitle( $this, (int)$old );
3860 if ( !( $new instanceof Revision
) ) {
3861 $new = Revision
::newFromTitle( $this, (int)$new );
3863 if ( !$old ||
!$new ) {
3864 return 0; // nothing to compare
3866 $dbr = wfGetDB( DB_REPLICA
);
3868 'rev_page' => $this->getArticleID(),
3869 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3870 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3872 if ( $max !== null ) {
3873 return $dbr->selectRowCount( 'revision', '1',
3876 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3879 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3884 * Get the authors between the given revisions or revision IDs.
3885 * Used for diffs and other things that really need it.
3889 * @param int|Revision $old Old revision or rev ID (first before range by default)
3890 * @param int|Revision $new New revision or rev ID (first after range by default)
3891 * @param int $limit Maximum number of authors
3892 * @param string|array $options (Optional): Single option, or an array of options:
3893 * 'include_old' Include $old in the range; $new is excluded.
3894 * 'include_new' Include $new in the range; $old is excluded.
3895 * 'include_both' Include both $old and $new in the range.
3896 * Unknown option values are ignored.
3897 * @return array|null Names of revision authors in the range; null if not both revisions exist
3899 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3900 if ( !( $old instanceof Revision
) ) {
3901 $old = Revision
::newFromTitle( $this, (int)$old );
3903 if ( !( $new instanceof Revision
) ) {
3904 $new = Revision
::newFromTitle( $this, (int)$new );
3906 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3907 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3908 // in the sanity check below?
3909 if ( !$old ||
!$new ) {
3910 return null; // nothing to compare
3915 $options = (array)$options;
3916 if ( in_array( 'include_old', $options ) ) {
3919 if ( in_array( 'include_new', $options ) ) {
3922 if ( in_array( 'include_both', $options ) ) {
3926 // No DB query needed if $old and $new are the same or successive revisions:
3927 if ( $old->getId() === $new->getId() ) {
3928 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3930 [ $old->getUserText( Revision
::RAW
) ];
3931 } elseif ( $old->getId() === $new->getParentId() ) {
3932 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3933 $authors[] = $old->getUserText( Revision
::RAW
);
3934 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3935 $authors[] = $new->getUserText( Revision
::RAW
);
3937 } elseif ( $old_cmp === '>=' ) {
3938 $authors[] = $old->getUserText( Revision
::RAW
);
3939 } elseif ( $new_cmp === '<=' ) {
3940 $authors[] = $new->getUserText( Revision
::RAW
);
3944 $dbr = wfGetDB( DB_REPLICA
);
3945 $revQuery = Revision
::getQueryInfo();
3946 $authors = $dbr->selectFieldValues(
3947 $revQuery['tables'],
3948 $revQuery['fields']['rev_user_text'],
3950 'rev_page' => $this->getArticleID(),
3951 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3952 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3954 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3961 * Get the number of authors between the given revisions or revision IDs.
3962 * Used for diffs and other things that really need it.
3964 * @param int|Revision $old Old revision or rev ID (first before range by default)
3965 * @param int|Revision $new New revision or rev ID (first after range by default)
3966 * @param int $limit Maximum number of authors
3967 * @param string|array $options (Optional): Single option, or an array of options:
3968 * 'include_old' Include $old in the range; $new is excluded.
3969 * 'include_new' Include $new in the range; $old is excluded.
3970 * 'include_both' Include both $old and $new in the range.
3971 * Unknown option values are ignored.
3972 * @return int Number of revision authors in the range; zero if not both revisions exist
3974 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3975 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3976 return $authors ?
count( $authors ) : 0;
3980 * Compare with another title.
3982 * @param LinkTarget $title
3985 public function equals( LinkTarget
$title ) {
3986 // Note: === is necessary for proper matching of number-like titles.
3987 return $this->mInterwiki
=== $title->getInterwiki()
3988 && $this->mNamespace
== $title->getNamespace()
3989 && $this->mDbkeyform
=== $title->getDBkey();
3993 * Check if this title is a subpage of another title
3995 * @param Title $title
3998 public function isSubpageOf( Title
$title ) {
3999 return $this->mInterwiki
=== $title->mInterwiki
4000 && $this->mNamespace
== $title->mNamespace
4001 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4005 * Check if page exists. For historical reasons, this function simply
4006 * checks for the existence of the title in the page table, and will
4007 * thus return false for interwiki links, special pages and the like.
4008 * If you want to know if a title can be meaningfully viewed, you should
4009 * probably call the isKnown() method instead.
4011 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4012 * from master/for update
4015 public function exists( $flags = 0 ) {
4016 $exists = $this->getArticleID( $flags ) != 0;
4017 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4022 * Should links to this title be shown as potentially viewable (i.e. as
4023 * "bluelinks"), even if there's no record by this title in the page
4026 * This function is semi-deprecated for public use, as well as somewhat
4027 * misleadingly named. You probably just want to call isKnown(), which
4028 * calls this function internally.
4030 * (ISSUE: Most of these checks are cheap, but the file existence check
4031 * can potentially be quite expensive. Including it here fixes a lot of
4032 * existing code, but we might want to add an optional parameter to skip
4033 * it and any other expensive checks.)
4037 public function isAlwaysKnown() {
4041 * Allows overriding default behavior for determining if a page exists.
4042 * If $isKnown is kept as null, regular checks happen. If it's
4043 * a boolean, this value is returned by the isKnown method.
4047 * @param Title $title
4048 * @param bool|null $isKnown
4050 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4052 if ( !is_null( $isKnown ) ) {
4056 if ( $this->isExternal() ) {
4057 return true; // any interwiki link might be viewable, for all we know
4060 $services = MediaWikiServices
::getInstance();
4061 switch ( $this->mNamespace
) {
4064 // file exists, possibly in a foreign repo
4065 return (bool)$services->getRepoGroup()->findFile( $this );
4067 // valid special page
4068 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4070 // selflink, possibly with fragment
4071 return $this->mDbkeyform
== '';
4073 // known system message
4074 return $this->hasSourceText() !== false;
4081 * Does this title refer to a page that can (or might) be meaningfully
4082 * viewed? In particular, this function may be used to determine if
4083 * links to the title should be rendered as "bluelinks" (as opposed to
4084 * "redlinks" to non-existent pages).
4085 * Adding something else to this function will cause inconsistency
4086 * since LinkHolderArray calls isAlwaysKnown() and does its own
4087 * page existence check.
4091 public function isKnown() {
4092 return $this->isAlwaysKnown() ||
$this->exists();
4096 * Does this page have source text?
4100 public function hasSourceText() {
4101 if ( $this->exists() ) {
4105 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4106 // If the page doesn't exist but is a known system message, default
4107 // message content will be displayed, same for language subpages-
4108 // Use always content language to avoid loading hundreds of languages
4109 // to get the link color.
4110 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4111 list( $name, ) = MessageCache
::singleton()->figureMessage(
4112 $contLang->lcfirst( $this->getText() )
4114 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4115 return $message->exists();
4122 * Get the default (plain) message contents for an page that overrides an
4123 * interface message key.
4125 * Primary use cases:
4128 * - Show default when viewing the page. The Article::getSubstituteContent
4129 * method displays the default message content, instead of the
4130 * 'noarticletext' placeholder message normally used.
4133 * - Title of edit page. When creating an interface message override,
4134 * the editor is told they are "Editing the page", instead of
4135 * "Creating the page". (EditPage::setHeaders)
4136 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4137 * or editing a an interface message override. (EditPage::showIntro)
4138 * - Opening the editor. The contents of the localisation message are used
4139 * as contents of the editor when creating a new page in the MediaWiki
4140 * namespace. This simplifies the process for editors when "changing"
4141 * an interface message by creating an override. (EditPage::getContentObject)
4142 * - Showing a diff. The left-hand side of a diff when an editor is
4143 * previewing their changes before saving the creation of a page in the
4144 * MediaWiki namespace. (EditPage::showDiff)
4145 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4146 * page with the proposed content matching the interface message default,
4147 * the save is rejected, the same way we disallow blank pages from being
4148 * created. (EditPage::internalAttemptSave)
4151 * - Default content, when using the 'prepend' or 'append' feature.
4154 * - Label the create action as "Edit", if the page can be an override.
4156 * @return string|bool
4158 public function getDefaultMessageText() {
4159 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4163 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4164 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4166 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4168 if ( $message->exists() ) {
4169 return $message->plain();
4176 * Updates page_touched for this page; called from LinksUpdate.php
4178 * @param string|null $purgeTime [optional] TS_MW timestamp
4179 * @return bool True if the update succeeded
4181 public function invalidateCache( $purgeTime = null ) {
4182 if ( wfReadOnly() ) {
4184 } elseif ( $this->mArticleID
=== 0 ) {
4185 return true; // avoid gap locking if we know it's not there
4188 $dbw = wfGetDB( DB_MASTER
);
4189 $dbw->onTransactionPreCommitOrIdle(
4190 function () use ( $dbw ) {
4191 ResourceLoaderWikiModule
::invalidateModuleCache(
4192 $this, null, null, $dbw->getDomainID() );
4197 $conds = $this->pageCond();
4198 DeferredUpdates
::addUpdate(
4199 new AutoCommitUpdate(
4202 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4203 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4206 [ 'page_touched' => $dbTimestamp ],
4207 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4210 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4213 DeferredUpdates
::PRESEND
4220 * Update page_touched timestamps and send CDN purge messages for
4221 * pages linking to this title. May be sent to the job queue depending
4222 * on the number of links. Typically called on create and delete.
4224 public function touchLinks() {
4225 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4226 if ( $this->mNamespace
== NS_CATEGORY
) {
4227 DeferredUpdates
::addUpdate(
4228 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4234 * Get the last touched timestamp
4236 * @param IDatabase|null $db
4237 * @return string|false Last-touched timestamp
4239 public function getTouched( $db = null ) {
4240 if ( $db === null ) {
4241 $db = wfGetDB( DB_REPLICA
);
4243 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4248 * Get the timestamp when this page was updated since the user last saw it.
4250 * @param User|null $user
4251 * @return string|null
4253 public function getNotificationTimestamp( $user = null ) {
4256 // Assume current user if none given
4260 // Check cache first
4261 $uid = $user->getId();
4265 // avoid isset here, as it'll return false for null entries
4266 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4267 return $this->mNotificationTimestamp
[$uid];
4269 // Don't cache too much!
4270 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4271 $this->mNotificationTimestamp
= [];
4274 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4275 $watchedItem = $store->getWatchedItem( $user, $this );
4276 if ( $watchedItem ) {
4277 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4279 $this->mNotificationTimestamp
[$uid] = false;
4282 return $this->mNotificationTimestamp
[$uid];
4286 * Generate strings used for xml 'id' names in monobook tabs
4288 * @param string $prepend Defaults to 'nstab-'
4289 * @return string XML 'id' name
4291 public function getNamespaceKey( $prepend = 'nstab-' ) {
4292 // Gets the subject namespace of this title
4293 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4294 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4295 // Prefer canonical namespace name for HTML IDs
4296 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4297 if ( $namespaceKey === false ) {
4298 // Fallback to localised text
4299 $namespaceKey = $this->getSubjectNsText();
4301 // Makes namespace key lowercase
4302 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4304 if ( $namespaceKey == '' ) {
4305 $namespaceKey = 'main';
4307 // Changes file to image for backwards compatibility
4308 if ( $namespaceKey == 'file' ) {
4309 $namespaceKey = 'image';
4311 return $prepend . $namespaceKey;
4315 * Get all extant redirects to this Title
4317 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4318 * @return Title[] Array of Title redirects to this title
4320 public function getRedirectsHere( $ns = null ) {
4323 $dbr = wfGetDB( DB_REPLICA
);
4325 'rd_namespace' => $this->mNamespace
,
4326 'rd_title' => $this->mDbkeyform
,
4329 if ( $this->isExternal() ) {
4330 $where['rd_interwiki'] = $this->mInterwiki
;
4332 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4334 if ( !is_null( $ns ) ) {
4335 $where['page_namespace'] = $ns;
4338 $res = $dbr->select(
4339 [ 'redirect', 'page' ],
4340 [ 'page_namespace', 'page_title' ],
4345 foreach ( $res as $row ) {
4346 $redirs[] = self
::newFromRow( $row );
4352 * Check if this Title is a valid redirect target
4356 public function isValidRedirectTarget() {
4357 global $wgInvalidRedirectTargets;
4359 if ( $this->isSpecialPage() ) {
4360 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4361 if ( $this->isSpecial( 'Userlogout' ) ) {
4365 foreach ( $wgInvalidRedirectTargets as $target ) {
4366 if ( $this->isSpecial( $target ) ) {
4376 * Get a backlink cache object
4378 * @return BacklinkCache
4380 public function getBacklinkCache() {
4381 return BacklinkCache
::get( $this );
4385 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4389 public function canUseNoindex() {
4390 global $wgExemptFromUserRobotsControl;
4392 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4393 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4395 return !in_array( $this->mNamespace
, $bannedNamespaces );
4399 * Returns the raw sort key to be used for categories, with the specified
4400 * prefix. This will be fed to Collation::getSortKey() to get a
4401 * binary sortkey that can be used for actual sorting.
4403 * @param string $prefix The prefix to be used, specified using
4404 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4408 public function getCategorySortkey( $prefix = '' ) {
4409 $unprefixed = $this->getText();
4411 // Anything that uses this hook should only depend
4412 // on the Title object passed in, and should probably
4413 // tell the users to run updateCollations.php --force
4414 // in order to re-sort existing category relations.
4415 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4416 if ( $prefix !== '' ) {
4417 # Separate with a line feed, so the unprefixed part is only used as
4418 # a tiebreaker when two pages have the exact same prefix.
4419 # In UCA, tab is the only character that can sort above LF
4420 # so we strip both of them from the original prefix.
4421 $prefix = strtr( $prefix, "\n\t", ' ' );
4422 return "$prefix\n$unprefixed";
4428 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4429 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4430 * the db, it will return NULL.
4432 * @return string|null|bool
4434 private function getDbPageLanguageCode() {
4435 global $wgPageLanguageUseDB;
4437 // check, if the page language could be saved in the database, and if so and
4438 // the value is not requested already, lookup the page language using LinkCache
4439 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4440 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4441 $linkCache->addLinkObj( $this );
4442 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4445 return $this->mDbPageLanguage
;
4449 * Get the language in which the content of this page is written in
4450 * wikitext. Defaults to content language, but in certain cases it can be
4451 * e.g. $wgLang (such as special pages, which are in the user language).
4456 public function getPageLanguage() {
4457 global $wgLang, $wgLanguageCode;
4458 if ( $this->isSpecialPage() ) {
4459 // special pages are in the user language
4463 // Checking if DB language is set
4464 $dbPageLanguage = $this->getDbPageLanguageCode();
4465 if ( $dbPageLanguage ) {
4466 return wfGetLangObj( $dbPageLanguage );
4469 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4470 // Note that this may depend on user settings, so the cache should
4471 // be only per-request.
4472 // NOTE: ContentHandler::getPageLanguage() may need to load the
4473 // content to determine the page language!
4474 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4476 $contentHandler = ContentHandler
::getForTitle( $this );
4477 $langObj = $contentHandler->getPageLanguage( $this );
4478 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4480 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4487 * Get the language in which the content of this page is written when
4488 * viewed by user. Defaults to content language, but in certain cases it can be
4489 * e.g. $wgLang (such as special pages, which are in the user language).
4494 public function getPageViewLanguage() {
4497 if ( $this->isSpecialPage() ) {
4498 // If the user chooses a variant, the content is actually
4499 // in a language whose code is the variant code.
4500 $variant = $wgLang->getPreferredVariant();
4501 if ( $wgLang->getCode() !== $variant ) {
4502 return Language
::factory( $variant );
4508 // Checking if DB language is set
4509 $dbPageLanguage = $this->getDbPageLanguageCode();
4510 if ( $dbPageLanguage ) {
4511 $pageLang = wfGetLangObj( $dbPageLanguage );
4512 $variant = $pageLang->getPreferredVariant();
4513 if ( $pageLang->getCode() !== $variant ) {
4514 $pageLang = Language
::factory( $variant );
4520 // @note Can't be cached persistently, depends on user settings.
4521 // @note ContentHandler::getPageViewLanguage() may need to load the
4522 // content to determine the page language!
4523 $contentHandler = ContentHandler
::getForTitle( $this );
4524 $pageLang = $contentHandler->getPageViewLanguage( $this );
4529 * Get a list of rendered edit notices for this page.
4531 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4532 * they will already be wrapped in paragraphs.
4535 * @param int $oldid Revision ID that's being edited
4538 public function getEditNotices( $oldid = 0 ) {
4541 // Optional notice for the entire namespace
4542 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4543 $msg = wfMessage( $editnotice_ns );
4544 if ( $msg->exists() ) {
4545 $html = $msg->parseAsBlock();
4546 // Edit notices may have complex logic, but output nothing (T91715)
4547 if ( trim( $html ) !== '' ) {
4548 $notices[$editnotice_ns] = Html
::rawElement(
4552 'mw-editnotice-namespace',
4553 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4561 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4562 hasSubpages( $this->mNamespace
)
4564 // Optional notice for page itself and any parent page
4565 $editnotice_base = $editnotice_ns;
4566 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4567 $editnotice_base .= '-' . $part;
4568 $msg = wfMessage( $editnotice_base );
4569 if ( $msg->exists() ) {
4570 $html = $msg->parseAsBlock();
4571 if ( trim( $html ) !== '' ) {
4572 $notices[$editnotice_base] = Html
::rawElement(
4576 'mw-editnotice-base',
4577 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4585 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4586 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4587 $msg = wfMessage( $editnoticeText );
4588 if ( $msg->exists() ) {
4589 $html = $msg->parseAsBlock();
4590 if ( trim( $html ) !== '' ) {
4591 $notices[$editnoticeText] = Html
::rawElement(
4595 'mw-editnotice-page',
4596 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4604 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4611 public function __sleep() {
4619 'mDefaultNamespace',
4623 public function __wakeup() {
4624 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4625 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4626 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );