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 MediaWiki\Storage\RevisionRecord
;
27 use Wikimedia\Assert\Assert
;
28 use Wikimedia\Rdbms\Database
;
29 use Wikimedia\Rdbms\IDatabase
;
30 use MediaWiki\Linker\LinkTarget
;
31 use MediaWiki\Interwiki\InterwikiLookup
;
32 use MediaWiki\MediaWikiServices
;
35 * Represents a title within MediaWiki.
36 * Optionally may contain an interwiki designation or namespace.
37 * @note This class can fetch various kinds of data from the database;
38 * however, it does so inefficiently.
39 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
40 * and does not rely on global state or the database.
42 class Title
implements LinkTarget
, IDBAccessObject
{
43 /** @var MapCacheLRU|null */
44 private static $titleCache = null;
47 * Title::newFromText maintains a cache to avoid expensive re-normalization of
48 * commonly used titles. On a batch operation this can become a memory leak
49 * if not bounded. After hitting this many titles reset the cache.
51 const CACHE_MAX
= 1000;
54 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
55 * to use the master DB
57 const GAID_FOR_UPDATE
= 1;
60 * Flag for use with factory methods like newFromLinkTarget() that have
61 * a $forceClone parameter. If set, the method must return a new instance.
62 * Without this flag, some factory methods may return existing instances.
66 const NEW_CLONE
= 'clone';
69 * @name Private member variables
70 * Please use the accessor functions instead.
75 /** @var string Text form (spaces not underscores) of the main part */
76 public $mTextform = '';
78 /** @var string URL-encoded form of the main part */
79 public $mUrlform = '';
81 /** @var string Main part with underscores */
82 public $mDbkeyform = '';
84 /** @var string Database key with the initial letter in the case specified by the user */
85 protected $mUserCaseDBKey;
87 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
88 public $mNamespace = NS_MAIN
;
90 /** @var string Interwiki prefix */
91 public $mInterwiki = '';
93 /** @var bool Was this Title created from a string with a local interwiki prefix? */
94 private $mLocalInterwiki = false;
96 /** @var string Title fragment (i.e. the bit after the #) */
97 public $mFragment = '';
99 /** @var int Article ID, fetched from the link cache on demand */
100 public $mArticleID = -1;
102 /** @var bool|int ID of most recent revision */
103 protected $mLatestID = false;
106 * @var bool|string ID of the page's content model, i.e. one of the
107 * CONTENT_MODEL_XXX constants
109 private $mContentModel = false;
112 * @var bool If a content model was forced via setContentModel()
113 * this will be true to avoid having other code paths reset it
115 private $mForcedContentModel = false;
117 /** @var int Estimated number of revisions; null of not loaded */
118 private $mEstimateRevisions;
120 /** @var array Array of groups allowed to edit this article */
121 public $mRestrictions = [];
124 * @var string|bool Comma-separated set of permission keys
125 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
126 * Edit and move sections are separated by a colon
127 * Example: "edit=autoconfirmed,sysop:move=sysop"
129 protected $mOldRestrictions = false;
131 /** @var bool Cascade restrictions on this page to included templates and images? */
132 public $mCascadeRestriction;
134 /** Caching the results of getCascadeProtectionSources */
135 public $mCascadingRestrictions;
137 /** @var array When do the restrictions on this page expire? */
138 protected $mRestrictionsExpiry = [];
140 /** @var bool Are cascading restrictions in effect on this page? */
141 protected $mHasCascadingRestrictions;
143 /** @var array Where are the cascading restrictions coming from on this page? */
144 public $mCascadeSources;
146 /** @var bool Boolean for initialisation on demand */
147 public $mRestrictionsLoaded = false;
150 * Text form including namespace/interwiki, initialised on demand
152 * Only public to share cache with TitleFormatter
157 public $prefixedText = null;
159 /** @var mixed Cached value for getTitleProtection (create protection) */
160 public $mTitleProtection;
163 * @var int Namespace index when there is no namespace. Don't change the
164 * following default, NS_MAIN is hardcoded in several places. See T2696.
165 * Zero except in {{transclusion}} tags.
167 public $mDefaultNamespace = NS_MAIN
;
169 /** @var int The page length, 0 for special pages */
170 protected $mLength = -1;
172 /** @var null Is the article at this title a redirect? */
173 public $mRedirect = null;
175 /** @var array Associative array of user ID -> timestamp/false */
176 private $mNotificationTimestamp = [];
178 /** @var bool Whether a page has any subpages */
179 private $mHasSubpages;
181 /** @var bool The (string) language code of the page's language and content code. */
182 private $mPageLanguage = false;
184 /** @var string|bool|null The page language code from the database, null if not saved in
185 * the database or false if not loaded, yet.
187 private $mDbPageLanguage = false;
189 /** @var TitleValue|null A corresponding TitleValue object */
190 private $mTitleValue = null;
192 /** @var bool|null Would deleting this page be a big deletion? */
193 private $mIsBigDeletion = null;
197 * B/C kludge: provide a TitleParser for use by Title.
198 * Ideally, Title would have no methods that need this.
199 * Avoid usage of this singleton by using TitleValue
200 * and the associated services when possible.
202 * @return TitleFormatter
204 private static function getTitleFormatter() {
205 return MediaWikiServices
::getInstance()->getTitleFormatter();
209 * B/C kludge: provide an InterwikiLookup for use by Title.
210 * Ideally, Title would have no methods that need this.
211 * Avoid usage of this singleton by using TitleValue
212 * and the associated services when possible.
214 * @return InterwikiLookup
216 private static function getInterwikiLookup() {
217 return MediaWikiServices
::getInstance()->getInterwikiLookup();
223 function __construct() {
227 * Create a new Title from a prefixed DB key
229 * @param string $key The database key, which has underscores
230 * instead of spaces, possibly including namespace and
232 * @return Title|null Title, or null on an error
234 public static function newFromDBkey( $key ) {
236 $t->mDbkeyform
= $key;
239 $t->secureAndSplit();
241 } catch ( MalformedTitleException
$ex ) {
247 * Returns a Title given a TitleValue.
248 * If the given TitleValue is already a Title instance, that instance is returned,
249 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
250 * is already a Title instance, that instance is copied using the clone operator.
252 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
254 * @param TitleValue $titleValue Assumed to be safe.
255 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
259 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
260 return self
::newFromLinkTarget( $titleValue, $forceClone );
264 * Returns a Title given a LinkTarget.
265 * If the given LinkTarget is already a Title instance, that instance is returned,
266 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
267 * is already a Title instance, that instance is copied using the clone operator.
269 * @param LinkTarget $linkTarget Assumed to be safe.
270 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
274 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
275 if ( $linkTarget instanceof Title
) {
276 // Special case if it's already a Title object
277 if ( $forceClone === self
::NEW_CLONE
) {
278 return clone $linkTarget;
283 return self
::makeTitle(
284 $linkTarget->getNamespace(),
285 $linkTarget->getText(),
286 $linkTarget->getFragment(),
287 $linkTarget->getInterwiki()
292 * Same as newFromLinkTarget, but if passed null, returns null.
294 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
298 public static function castFromLinkTarget( $linkTarget ) {
299 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
303 * Create a new Title from text, such as what one would find in a link. De-
304 * codes any HTML entities in the text.
306 * Title objects returned by this method are guaranteed to be valid, and
307 * thus return true from the isValid() method.
309 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
310 * It may instead be a cached instance created previously, with references to it remaining
313 * @param string|int|null $text The link text; spaces, prefixes, and an
314 * initial ':' indicating the main namespace are accepted.
315 * @param int $defaultNamespace The namespace to use if none is specified
316 * by a prefix. If you want to force a specific namespace even if
317 * $text might begin with a namespace prefix, use makeTitle() or
319 * @throws InvalidArgumentException
320 * @return Title|null Title or null on an error.
322 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
323 // DWIM: Integers can be passed in here when page titles are used as array keys.
324 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
325 throw new InvalidArgumentException( '$text must be a string.' );
327 if ( $text === null ) {
332 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
333 } catch ( MalformedTitleException
$ex ) {
339 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
340 * rather than returning null.
342 * The exception subclasses encode detailed information about why the title is invalid.
344 * Title objects returned by this method are guaranteed to be valid, and
345 * thus return true from the isValid() method.
347 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
348 * It may instead be a cached instance created previously, with references to it remaining
351 * @see Title::newFromText
354 * @param string $text Title text to check
355 * @param int $defaultNamespace
356 * @throws MalformedTitleException If the title is invalid
359 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
360 if ( is_object( $text ) ) {
361 throw new MWException( '$text must be a string, given an object' );
362 } elseif ( $text === null ) {
363 // Legacy code relies on MalformedTitleException being thrown in this case
364 // (happens when URL with no title in it is parsed). TODO fix
365 throw new MalformedTitleException( 'title-invalid-empty' );
368 $titleCache = self
::getTitleCache();
370 // Wiki pages often contain multiple links to the same page.
371 // Title normalization and parsing can become expensive on pages with many
372 // links, so we can save a little time by caching them.
373 // In theory these are value objects and won't get changed...
374 if ( $defaultNamespace == NS_MAIN
) {
375 $t = $titleCache->get( $text );
381 // Convert things like é ā or 〗 into normalized (T16952) text
382 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
385 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
386 $t->mDefaultNamespace
= (int)$defaultNamespace;
388 $t->secureAndSplit();
389 if ( $defaultNamespace == NS_MAIN
) {
390 $titleCache->set( $text, $t );
396 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
398 * Example of wrong and broken code:
399 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
401 * Example of right code:
402 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
404 * Create a new Title from URL-encoded text. Ensures that
405 * the given title's length does not exceed the maximum.
407 * @param string $url The title, as might be taken from a URL
408 * @return Title|null The new object, or null on an error
410 public static function newFromURL( $url ) {
413 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
414 # but some URLs used it as a space replacement and they still come
415 # from some external search tools.
416 if ( strpos( self
::legalChars(), '+' ) === false ) {
417 $url = strtr( $url, '+', ' ' );
420 $t->mDbkeyform
= strtr( $url, ' ', '_' );
423 $t->secureAndSplit();
425 } catch ( MalformedTitleException
$ex ) {
431 * @return MapCacheLRU
433 private static function getTitleCache() {
434 if ( self
::$titleCache === null ) {
435 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
437 return self
::$titleCache;
441 * Returns a list of fields that are to be selected for initializing Title
442 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
443 * whether to include page_content_model.
447 protected static function getSelectFields() {
448 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
451 'page_namespace', 'page_title', 'page_id',
452 'page_len', 'page_is_redirect', 'page_latest',
455 if ( $wgContentHandlerUseDB ) {
456 $fields[] = 'page_content_model';
459 if ( $wgPageLanguageUseDB ) {
460 $fields[] = 'page_lang';
467 * Create a new Title from an article ID
469 * @param int $id The page_id corresponding to the Title to create
470 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
471 * @return Title|null The new object, or null on an error
473 public static function newFromID( $id, $flags = 0 ) {
474 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
475 $row = $db->selectRow(
477 self
::getSelectFields(),
478 [ 'page_id' => $id ],
481 if ( $row !== false ) {
482 $title = self
::newFromRow( $row );
491 * Make an array of titles from an array of IDs
493 * @param int[] $ids Array of IDs
494 * @return Title[] Array of Titles
496 public static function newFromIDs( $ids ) {
497 if ( !count( $ids ) ) {
500 $dbr = wfGetDB( DB_REPLICA
);
504 self
::getSelectFields(),
505 [ 'page_id' => $ids ],
510 foreach ( $res as $row ) {
511 $titles[] = self
::newFromRow( $row );
517 * Make a Title object from a DB row
519 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
520 * @return Title Corresponding Title
522 public static function newFromRow( $row ) {
523 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
524 $t->loadFromRow( $row );
529 * Load Title object fields from a DB row.
530 * If false is given, the title will be treated as non-existing.
532 * @param stdClass|bool $row Database row
534 public function loadFromRow( $row ) {
535 if ( $row ) { // page found
536 if ( isset( $row->page_id
) ) {
537 $this->mArticleID
= (int)$row->page_id
;
539 if ( isset( $row->page_len
) ) {
540 $this->mLength
= (int)$row->page_len
;
542 if ( isset( $row->page_is_redirect
) ) {
543 $this->mRedirect
= (bool)$row->page_is_redirect
;
545 if ( isset( $row->page_latest
) ) {
546 $this->mLatestID
= (int)$row->page_latest
;
548 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
549 $this->mContentModel
= (string)$row->page_content_model
;
550 } elseif ( !$this->mForcedContentModel
) {
551 $this->mContentModel
= false; # initialized lazily in getContentModel()
553 if ( isset( $row->page_lang
) ) {
554 $this->mDbPageLanguage
= (string)$row->page_lang
;
556 if ( isset( $row->page_restrictions
) ) {
557 $this->mOldRestrictions
= $row->page_restrictions
;
559 } else { // page not found
560 $this->mArticleID
= 0;
562 $this->mRedirect
= false;
563 $this->mLatestID
= 0;
564 if ( !$this->mForcedContentModel
) {
565 $this->mContentModel
= false; # initialized lazily in getContentModel()
571 * Create a new Title from a namespace index and a DB key.
573 * It's assumed that $ns and $title are safe, for instance when
574 * they came directly from the database or a special page name,
575 * not from user input.
577 * No validation is applied. For convenience, spaces are normalized
578 * to underscores, so that e.g. user_text fields can be used directly.
580 * @note This method may return Title objects that are "invalid"
581 * according to the isValid() method. This is usually caused by
582 * configuration changes: e.g. a namespace that was once defined is
583 * no longer configured, or a character that was once allowed in
584 * titles is now forbidden.
586 * @param int $ns The namespace of the article
587 * @param string $title The unprefixed database key form
588 * @param string $fragment The link fragment (after the "#")
589 * @param string $interwiki The interwiki prefix
590 * @return Title The new object
592 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
594 $t->mInterwiki
= $interwiki;
595 $t->mFragment
= $fragment;
596 $t->mNamespace
= $ns = (int)$ns;
597 $t->mDbkeyform
= strtr( $title, ' ', '_' );
598 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
599 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
600 $t->mTextform
= strtr( $title, '_', ' ' );
601 $t->mContentModel
= false; # initialized lazily in getContentModel()
606 * Create a new Title from a namespace index and a DB key.
607 * The parameters will be checked for validity, which is a bit slower
608 * than makeTitle() but safer for user-provided data.
610 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
611 * that is, they return true from the isValid() method. If no valid Title
612 * can be constructed from the input, this method returns null.
614 * @param int $ns The namespace of the article
615 * @param string $title Database key form
616 * @param string $fragment The link fragment (after the "#")
617 * @param string $interwiki Interwiki prefix
618 * @return Title|null The new object, or null on an error
620 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
621 // NOTE: ideally, this would just call makeTitle() and then isValid(),
622 // but presently, that means more overhead on a potential performance hotspot.
624 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
629 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
632 $t->secureAndSplit();
634 } catch ( MalformedTitleException
$ex ) {
640 * Create a new Title for the Main Page
642 * This uses the 'mainpage' interface message, which could be specified in
643 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
644 * will use the user language, which would involve initialising the session
645 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
646 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
647 * or ResourceloaderContext) to prevent an error.
649 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
650 * It may instead be a cached instance created previously, with references to it remaining
653 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
656 public static function newMainPage( MessageLocalizer
$localizer = null ) {
658 $msg = $localizer->msg( 'mainpage' );
660 $msg = wfMessage( 'mainpage' );
663 $title = self
::newFromText( $msg->inContentLanguage()->text() );
665 // Every page renders at least one link to the Main Page (e.g. sidebar).
666 // If the localised value is invalid, don't produce fatal errors that
667 // would make the wiki inaccessible (and hard to fix the invalid message).
668 // Gracefully fallback...
670 $title = self
::newFromText( 'Main Page' );
676 * Get the prefixed DB key associated with an ID
678 * @param int $id The page_id of the article
679 * @return Title|null An object representing the article, or null if no such article was found
681 public static function nameOf( $id ) {
682 $dbr = wfGetDB( DB_REPLICA
);
684 $s = $dbr->selectRow(
686 [ 'page_namespace', 'page_title' ],
687 [ 'page_id' => $id ],
690 if ( $s === false ) {
694 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
699 * Get a regex character class describing the legal characters in a link
701 * @return string The list of characters, not delimited
703 public static function legalChars() {
704 global $wgLegalTitleChars;
705 return $wgLegalTitleChars;
709 * Utility method for converting a character sequence from bytes to Unicode.
711 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
712 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
714 * @param string $byteClass
717 public static function convertByteClassToUnicodeClass( $byteClass ) {
718 $length = strlen( $byteClass );
720 $x0 = $x1 = $x2 = '';
722 $d0 = $d1 = $d2 = '';
723 // Decoded integer codepoints
724 $ord0 = $ord1 = $ord2 = 0;
726 $r0 = $r1 = $r2 = '';
730 $allowUnicode = false;
731 for ( $pos = 0; $pos < $length; $pos++
) {
732 // Shift the queues down
741 // Load the current input token and decoded values
742 $inChar = $byteClass[$pos];
743 if ( $inChar == '\\' ) {
744 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
745 $x0 = $inChar . $m[0];
746 $d0 = chr( hexdec( $m[1] ) );
747 $pos +
= strlen( $m[0] );
748 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
749 $x0 = $inChar . $m[0];
750 $d0 = chr( octdec( $m[0] ) );
751 $pos +
= strlen( $m[0] );
752 } elseif ( $pos +
1 >= $length ) {
755 $d0 = $byteClass[$pos +
1];
763 // Load the current re-encoded value
764 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
765 $r0 = sprintf( '\x%02x', $ord0 );
766 } elseif ( $ord0 >= 0x80 ) {
767 // Allow unicode if a single high-bit character appears
768 $r0 = sprintf( '\x%02x', $ord0 );
769 $allowUnicode = true;
770 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
771 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
777 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
779 if ( $ord2 > $ord0 ) {
781 } elseif ( $ord0 >= 0x80 ) {
783 $allowUnicode = true;
784 if ( $ord2 < 0x80 ) {
785 // Keep the non-unicode section of the range
792 // Reset state to the initial value
793 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
794 } elseif ( $ord2 < 0x80 ) {
799 if ( $ord1 < 0x80 ) {
802 if ( $ord0 < 0x80 ) {
805 if ( $allowUnicode ) {
806 $out .= '\u0080-\uFFFF';
812 * Make a prefixed DB key from a DB key and a namespace index
814 * @param int $ns Numerical representation of the namespace
815 * @param string $title The DB key form the title
816 * @param string $fragment The link fragment (after the "#")
817 * @param string $interwiki The interwiki prefix
818 * @param bool $canonicalNamespace If true, use the canonical name for
819 * $ns instead of the localized version.
820 * @return string The prefixed form of the title
822 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
823 $canonicalNamespace = false
825 if ( $canonicalNamespace ) {
826 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
827 getCanonicalName( $ns );
829 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
831 $name = $namespace == '' ?
$title : "$namespace:$title";
832 if ( strval( $interwiki ) != '' ) {
833 $name = "$interwiki:$name";
835 if ( strval( $fragment ) != '' ) {
836 $name .= '#' . $fragment;
842 * Callback for usort() to do title sorts by (namespace, title)
844 * @param LinkTarget $a
845 * @param LinkTarget $b
847 * @return int Result of string comparison, or namespace comparison
849 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
850 return $a->getNamespace() <=> $b->getNamespace()
851 ?
: strcmp( $a->getText(), $b->getText() );
855 * Returns true if the title is valid, false if it is invalid.
857 * Valid titles can be round-tripped via makeTitle() and newFromText().
858 * Their DB key can be used in the database, though it may not have the correct
861 * Invalid titles may get returned from makeTitle(), and it may be useful to
862 * allow them to exist, e.g. in order to process log entries about pages in
863 * namespaces that belong to extensions that are no longer installed.
865 * @note This method is relatively expensive. When constructing Title
866 * objects that need to be valid, use an instantiator method that is guaranteed
867 * to return valid titles, such as makeTitleSafe() or newFromText().
871 public function isValid() {
872 $services = MediaWikiServices
::getInstance();
873 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
878 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
879 } catch ( MalformedTitleException
$ex ) {
884 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
891 } catch ( InvalidArgumentException
$ex ) {
899 * Determine whether the object refers to a page within
900 * this project (either this wiki or a wiki with a local
901 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
903 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
905 public function isLocal() {
906 if ( $this->isExternal() ) {
907 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
909 return $iw->isLocal();
916 * Is this Title interwiki?
920 public function isExternal() {
921 return $this->mInterwiki
!== '';
925 * Get the interwiki prefix
927 * Use Title::isExternal to check if a interwiki is set
929 * @return string Interwiki prefix
931 public function getInterwiki() {
932 return $this->mInterwiki
;
936 * Was this a local interwiki link?
940 public function wasLocalInterwiki() {
941 return $this->mLocalInterwiki
;
945 * Determine whether the object refers to a page within
946 * this project and is transcludable.
948 * @return bool True if this is transcludable
950 public function isTrans() {
951 if ( !$this->isExternal() ) {
955 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
959 * Returns the DB name of the distant wiki which owns the object.
961 * @return string|false The DB name
963 public function getTransWikiID() {
964 if ( !$this->isExternal() ) {
968 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
972 * Get a TitleValue object representing this Title.
974 * @note Not all valid Titles have a corresponding valid TitleValue
975 * (e.g. TitleValues cannot represent page-local links that have a
976 * fragment but no title text).
978 * @return TitleValue|null
980 public function getTitleValue() {
981 if ( $this->mTitleValue
=== null ) {
983 $this->mTitleValue
= new TitleValue(
989 } catch ( InvalidArgumentException
$ex ) {
990 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
991 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
995 return $this->mTitleValue
;
999 * Get the text form (spaces not underscores) of the main part
1001 * @return string Main part of the title
1003 public function getText() {
1004 return $this->mTextform
;
1008 * Get the URL-encoded form of the main part
1010 * @return string Main part of the title, URL-encoded
1012 public function getPartialURL() {
1013 return $this->mUrlform
;
1017 * Get the main part with underscores
1019 * @return string Main part of the title, with underscores
1021 public function getDBkey() {
1022 return $this->mDbkeyform
;
1026 * Get the DB key with the initial letter case as specified by the user
1027 * @deprecated since 1.33; please use Title::getDBKey() instead
1029 * @return string DB key
1031 function getUserCaseDBKey() {
1032 if ( !is_null( $this->mUserCaseDBKey
) ) {
1033 return $this->mUserCaseDBKey
;
1035 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1036 return $this->mDbkeyform
;
1041 * Get the namespace index, i.e. one of the NS_xxxx constants.
1043 * @return int Namespace index
1045 public function getNamespace() {
1046 return $this->mNamespace
;
1050 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1052 * @todo Deprecate this in favor of SlotRecord::getModel()
1054 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1055 * @return string Content model id
1057 public function getContentModel( $flags = 0 ) {
1058 if ( !$this->mForcedContentModel
1059 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1060 && $this->getArticleID( $flags )
1062 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1063 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1064 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1067 if ( !$this->mContentModel
) {
1068 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1071 return $this->mContentModel
;
1075 * Convenience method for checking a title's content model name
1077 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1078 * @return bool True if $this->getContentModel() == $id
1080 public function hasContentModel( $id ) {
1081 return $this->getContentModel() == $id;
1085 * Set a proposed content model for the page for permissions
1086 * checking. This does not actually change the content model
1089 * Additionally, you should make sure you've checked
1090 * ContentHandler::canBeUsedOn() first.
1093 * @param string $model CONTENT_MODEL_XXX constant
1095 public function setContentModel( $model ) {
1096 $this->mContentModel
= $model;
1097 $this->mForcedContentModel
= true;
1101 * Get the namespace text
1103 * @return string|false Namespace text
1105 public function getNsText() {
1106 if ( $this->isExternal() ) {
1107 // This probably shouldn't even happen, except for interwiki transclusion.
1108 // If possible, use the canonical name for the foreign namespace.
1109 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1110 getCanonicalName( $this->mNamespace
);
1111 if ( $nsText !== false ) {
1117 $formatter = self
::getTitleFormatter();
1118 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1119 } catch ( InvalidArgumentException
$ex ) {
1120 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1126 * Get the namespace text of the subject (rather than talk) page
1128 * @return string Namespace text
1130 public function getSubjectNsText() {
1131 $services = MediaWikiServices
::getInstance();
1132 return $services->getContentLanguage()->
1133 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1137 * Get the namespace text of the talk page
1139 * @return string Namespace text
1141 public function getTalkNsText() {
1142 $services = MediaWikiServices
::getInstance();
1143 return $services->getContentLanguage()->
1144 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1148 * Can this title have a corresponding talk page?
1150 * False for relative section links (with getText() === ''),
1151 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1153 * @see NamespaceInfo::canHaveTalkPage
1156 * @return bool True if this title either is a talk page or can have a talk page associated.
1158 public function canHaveTalkPage() {
1159 return MediaWikiServices
::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1163 * Is this in a namespace that allows actual pages?
1167 public function canExist() {
1168 return $this->mNamespace
>= NS_MAIN
;
1172 * Can this title be added to a user's watchlist?
1174 * False for relative section links (with getText() === ''),
1175 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1179 public function isWatchable() {
1180 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
1181 return $this->getText() !== '' && !$this->isExternal() &&
1182 $nsInfo->isWatchable( $this->mNamespace
);
1186 * Returns true if this is a special page.
1190 public function isSpecialPage() {
1191 return $this->mNamespace
== NS_SPECIAL
;
1195 * Returns true if this title resolves to the named special page
1197 * @param string $name The special page name
1200 public function isSpecial( $name ) {
1201 if ( $this->isSpecialPage() ) {
1202 list( $thisName, /* $subpage */ ) =
1203 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1204 resolveAlias( $this->mDbkeyform
);
1205 if ( $name == $thisName ) {
1213 * If the Title refers to a special page alias which is not the local default, resolve
1214 * the alias, and localise the name as necessary. Otherwise, return $this
1218 public function fixSpecialName() {
1219 if ( $this->isSpecialPage() ) {
1220 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1221 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1222 if ( $canonicalName ) {
1223 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1224 if ( $localName != $this->mDbkeyform
) {
1225 return self
::makeTitle( NS_SPECIAL
, $localName );
1233 * Returns true if the title is inside the specified namespace.
1235 * Please make use of this instead of comparing to getNamespace()
1236 * This function is much more resistant to changes we may make
1237 * to namespaces than code that makes direct comparisons.
1238 * @param int $ns The namespace
1242 public function inNamespace( $ns ) {
1243 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1244 equals( $this->mNamespace
, $ns );
1248 * Returns true if the title is inside one of the specified namespaces.
1250 * @param int|int[] $namespaces,... The namespaces to check for
1254 public function inNamespaces( /* ... */ ) {
1255 $namespaces = func_get_args();
1256 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1257 $namespaces = $namespaces[0];
1260 foreach ( $namespaces as $ns ) {
1261 if ( $this->inNamespace( $ns ) ) {
1270 * Returns true if the title has the same subject namespace as the
1271 * namespace specified.
1272 * For example this method will take NS_USER and return true if namespace
1273 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1274 * as their subject namespace.
1276 * This is MUCH simpler than individually testing for equivalence
1277 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1282 public function hasSubjectNamespace( $ns ) {
1283 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1284 subjectEquals( $this->mNamespace
, $ns );
1288 * Is this Title in a namespace which contains content?
1289 * In other words, is this a content page, for the purposes of calculating
1294 public function isContentPage() {
1295 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1296 isContent( $this->mNamespace
);
1300 * Would anybody with sufficient privileges be able to move this page?
1301 * Some pages just aren't movable.
1305 public function isMovable() {
1307 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1308 isMovable( $this->mNamespace
) ||
$this->isExternal()
1310 // Interwiki title or immovable namespace. Hooks don't get to override here
1315 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1320 * Is this the mainpage?
1321 * @note Title::newFromText seems to be sufficiently optimized by the title
1322 * cache that we don't need to over-optimize by doing direct comparisons and
1323 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1324 * ends up reporting something differently than $title->isMainPage();
1329 public function isMainPage() {
1330 return $this->equals( self
::newMainPage() );
1334 * Is this a subpage?
1338 public function isSubpage() {
1339 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1340 hasSubpages( $this->mNamespace
)
1341 ?
strpos( $this->getText(), '/' ) !== false
1346 * Is this a conversion table for the LanguageConverter?
1350 public function isConversionTable() {
1351 // @todo ConversionTable should become a separate content model.
1353 return $this->mNamespace
== NS_MEDIAWIKI
&&
1354 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1358 * Does that page contain wikitext, or it is JS, CSS or whatever?
1362 public function isWikitextPage() {
1363 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1367 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1368 * global UI. This is generally true for pages in the MediaWiki namespace having
1369 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1371 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1374 * Note that this method should not return true for pages that contain and show
1375 * "inactive" CSS, JSON, or JS.
1380 public function isSiteConfigPage() {
1382 $this->isSiteCssConfigPage()
1383 ||
$this->isSiteJsonConfigPage()
1384 ||
$this->isSiteJsConfigPage()
1389 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1394 public function isUserConfigPage() {
1396 $this->isUserCssConfigPage()
1397 ||
$this->isUserJsonConfigPage()
1398 ||
$this->isUserJsConfigPage()
1403 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1405 * @return string Containing skin name from .css, .json, or .js subpage title
1408 public function getSkinFromConfigSubpage() {
1409 $subpage = explode( '/', $this->mTextform
);
1410 $subpage = $subpage[count( $subpage ) - 1];
1411 $lastdot = strrpos( $subpage, '.' );
1412 if ( $lastdot === false ) {
1413 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1415 return substr( $subpage, 0, $lastdot );
1419 * Is this a CSS "config" sub-page of a user page?
1424 public function isUserCssConfigPage() {
1426 NS_USER
== $this->mNamespace
1427 && $this->isSubpage()
1428 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1433 * Is this a JSON "config" sub-page of a user page?
1438 public function isUserJsonConfigPage() {
1440 NS_USER
== $this->mNamespace
1441 && $this->isSubpage()
1442 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1447 * Is this a JS "config" sub-page of a user page?
1452 public function isUserJsConfigPage() {
1454 NS_USER
== $this->mNamespace
1455 && $this->isSubpage()
1456 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1461 * Is this a sitewide CSS "config" page?
1466 public function isSiteCssConfigPage() {
1468 NS_MEDIAWIKI
== $this->mNamespace
1470 $this->hasContentModel( CONTENT_MODEL_CSS
)
1471 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1472 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1473 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1479 * Is this a sitewide JSON "config" page?
1484 public function isSiteJsonConfigPage() {
1486 NS_MEDIAWIKI
== $this->mNamespace
1488 $this->hasContentModel( CONTENT_MODEL_JSON
)
1489 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1490 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1491 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1497 * Is this a sitewide JS "config" page?
1502 public function isSiteJsConfigPage() {
1504 NS_MEDIAWIKI
== $this->mNamespace
1506 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1507 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1508 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1509 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1515 * Is this a message which can contain raw HTML?
1520 public function isRawHtmlMessage() {
1521 global $wgRawHtmlMessages;
1523 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1526 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1527 return in_array( $message, $wgRawHtmlMessages, true );
1531 * Is this a talk page of some sort?
1535 public function isTalkPage() {
1536 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1537 isTalk( $this->mNamespace
);
1541 * Get a Title object associated with the talk page of this article
1543 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1544 * with NamespaceInfo::canHaveTalkPage().
1545 * @return Title The object for the talk page
1546 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1547 * or because it's a relative link, or an interwiki link.
1549 public function getTalkPage() {
1550 return self
::castFromLinkTarget(
1551 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1555 * Get a Title object associated with the talk page of this article,
1556 * if such a talk page can exist.
1560 * @return Title|null The object for the talk page,
1561 * or null if no associated talk page can exist, according to canHaveTalkPage().
1563 public function getTalkPageIfDefined() {
1564 if ( !$this->canHaveTalkPage() ) {
1568 return $this->getTalkPage();
1572 * Get a title object associated with the subject page of this
1575 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1576 * @return Title The object for the subject page
1578 public function getSubjectPage() {
1579 return self
::castFromLinkTarget(
1580 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1584 * Get the other title for this page, if this is a subject page
1585 * get the talk page, if it is a subject page get the talk page
1587 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1589 * @throws MWException If the page doesn't have an other page
1592 public function getOtherPage() {
1593 return self
::castFromLinkTarget(
1594 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1598 * Get the default namespace index, for when there is no namespace
1600 * @return int Default namespace index
1602 public function getDefaultNamespace() {
1603 return $this->mDefaultNamespace
;
1607 * Get the Title fragment (i.e.\ the bit after the #) in text form
1609 * Use Title::hasFragment to check for a fragment
1611 * @return string Title fragment
1613 public function getFragment() {
1614 return $this->mFragment
;
1618 * Check if a Title fragment is set
1623 public function hasFragment() {
1624 return $this->mFragment
!== '';
1628 * Get the fragment in URL form, including the "#" character if there is one
1630 * @return string Fragment in URL form
1632 public function getFragmentForURL() {
1633 if ( !$this->hasFragment() ) {
1635 } elseif ( $this->isExternal() ) {
1636 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1637 // so we treat it like a local interwiki.
1638 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1639 if ( $interwiki && !$interwiki->isLocal() ) {
1640 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1644 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1648 * Set the fragment for this title. Removes the first character from the
1649 * specified fragment before setting, so it assumes you're passing it with
1652 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1653 * or Title::createFragmentTarget().
1654 * Still in active use privately.
1657 * @param string $fragment Text
1659 public function setFragment( $fragment ) {
1660 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1664 * Creates a new Title for a different fragment of the same page.
1667 * @param string $fragment
1670 public function createFragmentTarget( $fragment ) {
1671 return self
::makeTitle(
1680 * Prefix some arbitrary text with the namespace or interwiki prefix
1683 * @param string $name The text
1684 * @return string The prefixed text
1686 private function prefix( $name ) {
1688 if ( $this->isExternal() ) {
1689 $p = $this->mInterwiki
. ':';
1692 if ( $this->mNamespace
!= 0 ) {
1693 $nsText = $this->getNsText();
1695 if ( $nsText === false ) {
1696 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1697 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1698 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1701 $p .= $nsText . ':';
1707 * Get the prefixed database key form
1709 * @return string The prefixed title, with underscores and
1710 * any interwiki and namespace prefixes
1712 public function getPrefixedDBkey() {
1713 $s = $this->prefix( $this->mDbkeyform
);
1714 $s = strtr( $s, ' ', '_' );
1719 * Get the prefixed title with spaces.
1720 * This is the form usually used for display
1722 * @return string The prefixed title, with spaces
1724 public function getPrefixedText() {
1725 if ( $this->prefixedText
=== null ) {
1726 $s = $this->prefix( $this->mTextform
);
1727 $s = strtr( $s, '_', ' ' );
1728 $this->prefixedText
= $s;
1730 return $this->prefixedText
;
1734 * Return a string representation of this title
1736 * @return string Representation of this title
1738 public function __toString() {
1739 return $this->getPrefixedText();
1743 * Get the prefixed title with spaces, plus any fragment
1744 * (part beginning with '#')
1746 * @return string The prefixed title, with spaces and the fragment, including '#'
1748 public function getFullText() {
1749 $text = $this->getPrefixedText();
1750 if ( $this->hasFragment() ) {
1751 $text .= '#' . $this->mFragment
;
1757 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1759 * @note the return value may contain trailing whitespace and is thus
1760 * not safe for use with makeTitle or TitleValue.
1764 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1768 * @return string Root name
1771 public function getRootText() {
1773 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1774 hasSubpages( $this->mNamespace
)
1775 ||
strtok( $this->getText(), '/' ) === false
1777 return $this->getText();
1780 return strtok( $this->getText(), '/' );
1784 * Get the root page name title, i.e. the leftmost part before any slashes
1788 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1789 * # returns: Title{User:Foo}
1792 * @return Title Root title
1795 public function getRootTitle() {
1796 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getRootText() );
1797 Assert
::postcondition(
1799 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1805 * Get the base page name without a namespace, i.e. the part before the subpage name
1807 * @note the return value may contain trailing whitespace and is thus
1808 * not safe for use with makeTitle or TitleValue.
1812 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1813 * # returns: 'Foo/Bar'
1816 * @return string Base name
1818 public function getBaseText() {
1819 $text = $this->getText();
1821 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1822 hasSubpages( $this->mNamespace
)
1827 $lastSlashPos = strrpos( $text, '/' );
1828 // Don't discard the real title if there's no subpage involved
1829 if ( $lastSlashPos === false ) {
1833 return substr( $text, 0, $lastSlashPos );
1837 * Get the base page name title, i.e. the part before the subpage name.
1841 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1842 * # returns: Title{User:Foo/Bar}
1845 * @return Title Base title
1848 public function getBaseTitle() {
1849 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getBaseText() );
1850 Assert
::postcondition(
1852 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1858 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1862 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1866 * @return string Subpage name
1868 public function getSubpageText() {
1870 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1871 hasSubpages( $this->mNamespace
)
1873 return $this->mTextform
;
1875 $parts = explode( '/', $this->mTextform
);
1876 return $parts[count( $parts ) - 1];
1880 * Get the title for a subpage of the current page
1884 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1885 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1888 * @param string $text The subpage name to add to the title
1889 * @return Title|null Subpage title, or null on an error
1892 public function getSubpage( $text ) {
1893 return self
::makeTitleSafe(
1895 $this->getText() . '/' . $text,
1902 * Get a URL-encoded form of the subpage text
1904 * @return string URL-encoded subpage name
1906 public function getSubpageUrlForm() {
1907 $text = $this->getSubpageText();
1908 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1913 * Get a URL-encoded title (not an actual URL) including interwiki
1915 * @return string The URL-encoded form
1917 public function getPrefixedURL() {
1918 $s = $this->prefix( $this->mDbkeyform
);
1919 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1924 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1925 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1926 * second argument named variant. This was deprecated in favor
1927 * of passing an array of option with a "variant" key
1928 * Once $query2 is removed for good, this helper can be dropped
1929 * and the wfArrayToCgi moved to getLocalURL();
1931 * @since 1.19 (r105919)
1932 * @param array|string $query
1933 * @param string|string[]|bool $query2
1936 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1937 if ( $query2 !== false ) {
1938 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1939 "method called with a second parameter is deprecated. Add your " .
1940 "parameter to an array passed as the first parameter.", "1.19" );
1942 if ( is_array( $query ) ) {
1943 $query = wfArrayToCgi( $query );
1946 if ( is_string( $query2 ) ) {
1947 // $query2 is a string, we will consider this to be
1948 // a deprecated $variant argument and add it to the query
1949 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1951 $query2 = wfArrayToCgi( $query2 );
1953 // If we have $query content add a & to it first
1957 // Now append the queries together
1964 * Get a real URL referring to this title, with interwiki link and
1967 * @see self::getLocalURL for the arguments.
1969 * @param string|string[] $query
1970 * @param string|string[]|bool $query2
1971 * @param string|int|null $proto Protocol type to use in URL
1972 * @return string The URL
1974 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1975 $query = self
::fixUrlQueryArgs( $query, $query2 );
1977 # Hand off all the decisions on urls to getLocalURL
1978 $url = $this->getLocalURL( $query );
1980 # Expand the url to make it a full url. Note that getLocalURL has the
1981 # potential to output full urls for a variety of reasons, so we use
1982 # wfExpandUrl instead of simply prepending $wgServer
1983 $url = wfExpandUrl( $url, $proto );
1985 # Finally, add the fragment.
1986 $url .= $this->getFragmentForURL();
1987 // Avoid PHP 7.1 warning from passing $this by reference
1989 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1994 * Get a url appropriate for making redirects based on an untrusted url arg
1996 * This is basically the same as getFullUrl(), but in the case of external
1997 * interwikis, we send the user to a landing page, to prevent possible
1998 * phishing attacks and the like.
2000 * @note Uses current protocol by default, since technically relative urls
2001 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2002 * places where the url gets cached, as might pollute between
2003 * https and non-https users.
2004 * @see self::getLocalURL for the arguments.
2005 * @param array|string $query
2006 * @param string $proto Protocol type to use in URL
2007 * @return string A url suitable to use in an HTTP location header.
2009 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
2011 if ( $this->isExternal() ) {
2012 $target = SpecialPage
::getTitleFor(
2014 $this->getPrefixedDBkey()
2017 return $target->getFullURL( $query, false, $proto );
2021 * Get a URL with no fragment or server name (relative URL) from a Title object.
2022 * If this page is generated with action=render, however,
2023 * $wgServer is prepended to make an absolute URL.
2025 * @see self::getFullURL to always get an absolute URL.
2026 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2027 * valid to link, locally, to the current Title.
2028 * @see self::newFromText to produce a Title object.
2030 * @param string|string[] $query An optional query string,
2031 * not used for interwiki links. Can be specified as an associative array as well,
2032 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2033 * Some query patterns will trigger various shorturl path replacements.
2034 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2035 * be an array. If a string is passed it will be interpreted as a deprecated
2036 * variant argument and urlencoded into a variant= argument.
2037 * This second query argument will be added to the $query
2038 * The second parameter is deprecated since 1.19. Pass it as a key,value
2039 * pair in the first parameter array instead.
2041 * @return string String of the URL.
2043 public function getLocalURL( $query = '', $query2 = false ) {
2044 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
2046 $query = self
::fixUrlQueryArgs( $query, $query2 );
2048 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2050 $namespace = $this->getNsText();
2051 if ( $namespace != '' ) {
2052 # Can this actually happen? Interwikis shouldn't be parsed.
2053 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2056 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2057 $url = wfAppendQuery( $url, $query );
2059 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2060 if ( $query == '' ) {
2061 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2062 // Avoid PHP 7.1 warning from passing $this by reference
2064 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2066 global $wgVariantArticlePath, $wgActionPaths;
2070 if ( !empty( $wgActionPaths )
2071 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2073 $action = urldecode( $matches[2] );
2074 if ( isset( $wgActionPaths[$action] ) ) {
2075 $query = $matches[1];
2076 if ( isset( $matches[4] ) ) {
2077 $query .= $matches[4];
2079 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2080 if ( $query != '' ) {
2081 $url = wfAppendQuery( $url, $query );
2087 && $wgVariantArticlePath
2088 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2089 && $this->getPageLanguage()->equals(
2090 MediaWikiServices
::getInstance()->getContentLanguage() )
2091 && $this->getPageLanguage()->hasVariants()
2093 $variant = urldecode( $matches[1] );
2094 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2095 // Only do the variant replacement if the given variant is a valid
2096 // variant for the page's language.
2097 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2098 $url = str_replace( '$1', $dbkey, $url );
2102 if ( $url === false ) {
2103 if ( $query == '-' ) {
2106 $url = "{$wgScript}?title={$dbkey}&{$query}";
2109 // Avoid PHP 7.1 warning from passing $this by reference
2111 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2113 // @todo FIXME: This causes breakage in various places when we
2114 // actually expected a local URL and end up with dupe prefixes.
2115 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2116 $url = $wgServer . $url;
2119 // Avoid PHP 7.1 warning from passing $this by reference
2121 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2126 * Get a URL that's the simplest URL that will be valid to link, locally,
2127 * to the current Title. It includes the fragment, but does not include
2128 * the server unless action=render is used (or the link is external). If
2129 * there's a fragment but the prefixed text is empty, we just return a link
2132 * The result obviously should not be URL-escaped, but does need to be
2133 * HTML-escaped if it's being output in HTML.
2135 * @param string|string[] $query
2136 * @param bool $query2
2137 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2138 * or false (default) for no expansion
2139 * @see self::getLocalURL for the arguments.
2140 * @return string The URL
2142 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2143 if ( $this->isExternal() ||
$proto !== false ) {
2144 $ret = $this->getFullURL( $query, $query2, $proto );
2145 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2146 $ret = $this->getFragmentForURL();
2148 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2154 * Get the URL form for an internal link.
2155 * - Used in various CDN-related code, in case we have a different
2156 * internal hostname for the server from the exposed one.
2158 * This uses $wgInternalServer to qualify the path, or $wgServer
2159 * if $wgInternalServer is not set. If the server variable used is
2160 * protocol-relative, the URL will be expanded to http://
2162 * @see self::getLocalURL for the arguments.
2163 * @param string|string[] $query
2164 * @param string|bool $query2 Deprecated
2165 * @return string The URL
2167 public function getInternalURL( $query = '', $query2 = false ) {
2168 global $wgInternalServer, $wgServer;
2169 $query = self
::fixUrlQueryArgs( $query, $query2 );
2170 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2171 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2172 // Avoid PHP 7.1 warning from passing $this by reference
2174 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2179 * Get the URL for a canonical link, for use in things like IRC and
2180 * e-mail notifications. Uses $wgCanonicalServer and the
2181 * GetCanonicalURL hook.
2183 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2185 * @see self::getLocalURL for the arguments.
2186 * @param string|string[] $query
2187 * @param string|bool $query2 Deprecated
2188 * @return string The URL
2191 public function getCanonicalURL( $query = '', $query2 = false ) {
2192 $query = self
::fixUrlQueryArgs( $query, $query2 );
2193 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2194 // Avoid PHP 7.1 warning from passing $this by reference
2196 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2201 * Get the edit URL for this Title
2203 * @return string The URL, or a null string if this is an interwiki link
2205 public function getEditURL() {
2206 if ( $this->isExternal() ) {
2209 $s = $this->getLocalURL( 'action=edit' );
2215 * Can $user perform $action on this page?
2216 * This skips potentially expensive cascading permission checks
2217 * as well as avoids expensive error formatting
2219 * Suitable for use for nonessential UI controls in common cases, but
2220 * _not_ for functional access control.
2222 * May provide false positives, but should never provide a false negative.
2224 * @param string $action Action that permission needs to be checked for
2225 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2230 * @deprecated since 1.33,
2231 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2234 public function quickUserCan( $action, $user = null ) {
2235 return $this->userCan( $action, $user, false );
2239 * Can $user perform $action on this page?
2241 * @param string $action Action that permission needs to be checked for
2242 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2244 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2249 * @deprecated since 1.33,
2250 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2253 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2254 if ( !$user instanceof User
) {
2259 // TODO: this is for b/c, eventually will be removed
2260 if ( $rigor === true ) {
2261 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2262 } elseif ( $rigor === false ) {
2263 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2266 return MediaWikiServices
::getInstance()->getPermissionManager()
2267 ->userCan( $action, $user, $this, $rigor );
2271 * Can $user perform $action on this page?
2273 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2275 * @param string $action Action that permission needs to be checked for
2276 * @param User $user User to check
2277 * @param string $rigor One of (quick,full,secure)
2278 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2279 * - full : does cheap and expensive checks possibly from a replica DB
2280 * - secure : does cheap and expensive checks, using the master as needed
2281 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2282 * whose corresponding errors may be ignored.
2284 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2287 * @deprecated since 1.33,
2288 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2291 public function getUserPermissionsErrors(
2292 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2294 // TODO: this is for b/c, eventually will be removed
2295 if ( $rigor === true ) {
2296 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2297 } elseif ( $rigor === false ) {
2298 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2301 return MediaWikiServices
::getInstance()->getPermissionManager()
2302 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2306 * Get a filtered list of all restriction types supported by this wiki.
2307 * @param bool $exists True to get all restriction types that apply to
2308 * titles that do exist, False for all restriction types that apply to
2309 * titles that do not exist
2312 public static function getFilteredRestrictionTypes( $exists = true ) {
2313 global $wgRestrictionTypes;
2314 $types = $wgRestrictionTypes;
2316 # Remove the create restriction for existing titles
2317 $types = array_diff( $types, [ 'create' ] );
2319 # Only the create and upload restrictions apply to non-existing titles
2320 $types = array_intersect( $types, [ 'create', 'upload' ] );
2326 * Returns restriction types for the current Title
2328 * @return array Applicable restriction types
2330 public function getRestrictionTypes() {
2331 if ( $this->isSpecialPage() ) {
2335 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2337 if ( $this->mNamespace
!= NS_FILE
) {
2338 # Remove the upload restriction for non-file titles
2339 $types = array_diff( $types, [ 'upload' ] );
2342 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2344 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2345 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2351 * Is this title subject to title protection?
2352 * Title protection is the one applied against creation of such title.
2354 * @return array|bool An associative array representing any existent title
2355 * protection, or false if there's none.
2357 public function getTitleProtection() {
2358 $protection = $this->getTitleProtectionInternal();
2359 if ( $protection ) {
2360 if ( $protection['permission'] == 'sysop' ) {
2361 $protection['permission'] = 'editprotected'; // B/C
2363 if ( $protection['permission'] == 'autoconfirmed' ) {
2364 $protection['permission'] = 'editsemiprotected'; // B/C
2371 * Fetch title protection settings
2373 * To work correctly, $this->loadRestrictions() needs to have access to the
2374 * actual protections in the database without munging 'sysop' =>
2375 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2376 * callers probably want $this->getTitleProtection() instead.
2378 * @return array|bool
2380 protected function getTitleProtectionInternal() {
2381 // Can't protect pages in special namespaces
2382 if ( $this->mNamespace
< 0 ) {
2386 // Can't protect pages that exist.
2387 if ( $this->exists() ) {
2391 if ( $this->mTitleProtection
=== null ) {
2392 $dbr = wfGetDB( DB_REPLICA
);
2393 $commentStore = CommentStore
::getStore();
2394 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2395 $res = $dbr->select(
2396 [ 'protected_titles' ] +
$commentQuery['tables'],
2398 'user' => 'pt_user',
2399 'expiry' => 'pt_expiry',
2400 'permission' => 'pt_create_perm'
2401 ] +
$commentQuery['fields'],
2402 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2405 $commentQuery['joins']
2408 // fetchRow returns false if there are no rows.
2409 $row = $dbr->fetchRow( $res );
2411 $this->mTitleProtection
= [
2412 'user' => $row['user'],
2413 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2414 'permission' => $row['permission'],
2415 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2418 $this->mTitleProtection
= false;
2421 return $this->mTitleProtection
;
2425 * Remove any title protection due to page existing
2427 public function deleteTitleProtection() {
2428 $dbw = wfGetDB( DB_MASTER
);
2432 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2435 $this->mTitleProtection
= false;
2439 * Is this page "semi-protected" - the *only* protection levels are listed
2440 * in $wgSemiprotectedRestrictionLevels?
2442 * @param string $action Action to check (default: edit)
2445 public function isSemiProtected( $action = 'edit' ) {
2446 global $wgSemiprotectedRestrictionLevels;
2448 $restrictions = $this->getRestrictions( $action );
2449 $semi = $wgSemiprotectedRestrictionLevels;
2450 if ( !$restrictions ||
!$semi ) {
2451 // Not protected, or all protection is full protection
2455 // Remap autoconfirmed to editsemiprotected for BC
2456 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2457 $semi[$key] = 'editsemiprotected';
2459 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2460 $restrictions[$key] = 'editsemiprotected';
2463 return !array_diff( $restrictions, $semi );
2467 * Does the title correspond to a protected article?
2469 * @param string $action The action the page is protected from,
2470 * by default checks all actions.
2473 public function isProtected( $action = '' ) {
2474 global $wgRestrictionLevels;
2476 $restrictionTypes = $this->getRestrictionTypes();
2478 # Special pages have inherent protection
2479 if ( $this->isSpecialPage() ) {
2483 # Check regular protection levels
2484 foreach ( $restrictionTypes as $type ) {
2485 if ( $action == $type ||
$action == '' ) {
2486 $r = $this->getRestrictions( $type );
2487 foreach ( $wgRestrictionLevels as $level ) {
2488 if ( in_array( $level, $r ) && $level != '' ) {
2499 * Determines if $user is unable to edit this page because it has been protected
2500 * by $wgNamespaceProtection.
2502 * @deprecated since 1.34 Don't use this function in new code.
2503 * @param User $user User object to check permissions
2506 public function isNamespaceProtected( User
$user ) {
2507 global $wgNamespaceProtection;
2509 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2510 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2511 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2512 if ( !$permissionManager->userHasRight( $user, $right ) ) {
2521 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2523 * @return bool If the page is subject to cascading restrictions.
2525 public function isCascadeProtected() {
2526 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2527 return ( $sources > 0 );
2531 * Determines whether cascading protection sources have already been loaded from
2534 * @param bool $getPages True to check if the pages are loaded, or false to check
2535 * if the status is loaded.
2536 * @return bool Whether or not the specified information has been loaded
2539 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2540 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2544 * Cascading protection: Get the source of any cascading restrictions on this page.
2546 * @param bool $getPages Whether or not to retrieve the actual pages
2547 * that the restrictions have come from and the actual restrictions
2549 * @return array Two elements: First is an array of Title objects of the
2550 * pages from which cascading restrictions have come, false for
2551 * none, or true if such restrictions exist but $getPages was not
2552 * set. Second is an array like that returned by
2553 * Title::getAllRestrictions(), or an empty array if $getPages is
2556 public function getCascadeProtectionSources( $getPages = true ) {
2557 $pagerestrictions = [];
2559 if ( $this->mCascadeSources
!== null && $getPages ) {
2560 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2561 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2562 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2565 $dbr = wfGetDB( DB_REPLICA
);
2567 if ( $this->mNamespace
== NS_FILE
) {
2568 $tables = [ 'imagelinks', 'page_restrictions' ];
2570 'il_to' => $this->mDbkeyform
,
2575 $tables = [ 'templatelinks', 'page_restrictions' ];
2577 'tl_namespace' => $this->mNamespace
,
2578 'tl_title' => $this->mDbkeyform
,
2585 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2586 'pr_expiry', 'pr_type', 'pr_level' ];
2587 $where_clauses[] = 'page_id=pr_page';
2590 $cols = [ 'pr_expiry' ];
2593 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2595 $sources = $getPages ?
[] : false;
2596 $now = wfTimestampNow();
2598 foreach ( $res as $row ) {
2599 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2600 if ( $expiry > $now ) {
2602 $page_id = $row->pr_page
;
2603 $page_ns = $row->page_namespace
;
2604 $page_title = $row->page_title
;
2605 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2606 # Add groups needed for each restriction type if its not already there
2607 # Make sure this restriction type still exists
2609 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2610 $pagerestrictions[$row->pr_type
] = [];
2614 isset( $pagerestrictions[$row->pr_type
] )
2615 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2617 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2626 $this->mCascadeSources
= $sources;
2627 $this->mCascadingRestrictions
= $pagerestrictions;
2629 $this->mHasCascadingRestrictions
= $sources;
2632 return [ $sources, $pagerestrictions ];
2636 * Accessor for mRestrictionsLoaded
2638 * @return bool Whether or not the page's restrictions have already been
2639 * loaded from the database
2642 public function areRestrictionsLoaded() {
2643 return $this->mRestrictionsLoaded
;
2647 * Accessor/initialisation for mRestrictions
2649 * @param string $action Action that permission needs to be checked for
2650 * @return array Restriction levels needed to take the action. All levels are
2651 * required. Note that restriction levels are normally user rights, but 'sysop'
2652 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2653 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2655 public function getRestrictions( $action ) {
2656 if ( !$this->mRestrictionsLoaded
) {
2657 $this->loadRestrictions();
2659 return $this->mRestrictions
[$action] ??
[];
2663 * Accessor/initialisation for mRestrictions
2665 * @return array Keys are actions, values are arrays as returned by
2666 * Title::getRestrictions()
2669 public function getAllRestrictions() {
2670 if ( !$this->mRestrictionsLoaded
) {
2671 $this->loadRestrictions();
2673 return $this->mRestrictions
;
2677 * Get the expiry time for the restriction against a given action
2679 * @param string $action
2680 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2681 * or not protected at all, or false if the action is not recognised.
2683 public function getRestrictionExpiry( $action ) {
2684 if ( !$this->mRestrictionsLoaded
) {
2685 $this->loadRestrictions();
2687 return $this->mRestrictionsExpiry
[$action] ??
false;
2691 * Returns cascading restrictions for the current article
2695 function areRestrictionsCascading() {
2696 if ( !$this->mRestrictionsLoaded
) {
2697 $this->loadRestrictions();
2700 return $this->mCascadeRestriction
;
2704 * Compiles list of active page restrictions from both page table (pre 1.10)
2705 * and page_restrictions table for this existing page.
2706 * Public for usage by LiquidThreads.
2708 * @param array $rows Array of db result objects
2709 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2710 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2711 * Edit and move sections are separated by a colon
2712 * Example: "edit=autoconfirmed,sysop:move=sysop"
2714 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2715 // This function will only read rows from a table that we migrated away
2716 // from before adding READ_LATEST support to loadRestrictions, so we
2717 // don't need to support reading from DB_MASTER here.
2718 $dbr = wfGetDB( DB_REPLICA
);
2720 $restrictionTypes = $this->getRestrictionTypes();
2722 foreach ( $restrictionTypes as $type ) {
2723 $this->mRestrictions
[$type] = [];
2724 $this->mRestrictionsExpiry
[$type] = 'infinity';
2727 $this->mCascadeRestriction
= false;
2729 # Backwards-compatibility: also load the restrictions from the page record (old format).
2730 if ( $oldFashionedRestrictions !== null ) {
2731 $this->mOldRestrictions
= $oldFashionedRestrictions;
2734 if ( $this->mOldRestrictions
=== false ) {
2735 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2736 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2737 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2740 if ( $this->mOldRestrictions
!= '' ) {
2741 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2742 $temp = explode( '=', trim( $restrict ) );
2743 if ( count( $temp ) == 1 ) {
2744 // old old format should be treated as edit/move restriction
2745 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2746 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2748 $restriction = trim( $temp[1] );
2749 if ( $restriction != '' ) { // some old entries are empty
2750 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2756 if ( count( $rows ) ) {
2757 # Current system - load second to make them override.
2758 $now = wfTimestampNow();
2760 # Cycle through all the restrictions.
2761 foreach ( $rows as $row ) {
2762 // Don't take care of restrictions types that aren't allowed
2763 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2767 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2769 // Only apply the restrictions if they haven't expired!
2770 if ( !$expiry ||
$expiry > $now ) {
2771 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2772 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2774 $this->mCascadeRestriction |
= $row->pr_cascade
;
2779 $this->mRestrictionsLoaded
= true;
2783 * Load restrictions from the page_restrictions table
2785 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2786 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2787 * Edit and move sections are separated by a colon
2788 * Example: "edit=autoconfirmed,sysop:move=sysop"
2789 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2790 * from the master DB.
2792 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2793 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2794 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2798 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2799 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2800 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2801 $id = $this->getArticleID();
2803 $fname = __METHOD__
;
2804 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2805 return iterator_to_array(
2807 'page_restrictions',
2808 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2809 [ 'pr_page' => $id ],
2815 if ( $readLatest ) {
2816 $dbr = wfGetDB( DB_MASTER
);
2817 $rows = $loadRestrictionsFromDb( $dbr );
2819 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2820 $rows = $cache->getWithSetCallback(
2821 // Page protections always leave a new null revision
2822 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2824 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2825 $dbr = wfGetDB( DB_REPLICA
);
2827 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2828 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2829 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2830 // @TODO: cleanup Title cache and caller assumption mess in general
2831 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2834 return $loadRestrictionsFromDb( $dbr );
2839 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2841 $title_protection = $this->getTitleProtectionInternal();
2843 if ( $title_protection ) {
2844 $now = wfTimestampNow();
2845 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2847 if ( !$expiry ||
$expiry > $now ) {
2848 // Apply the restrictions
2849 $this->mRestrictionsExpiry
['create'] = $expiry;
2850 $this->mRestrictions
['create'] =
2851 explode( ',', trim( $title_protection['permission'] ) );
2852 } else { // Get rid of the old restrictions
2853 $this->mTitleProtection
= false;
2856 $this->mRestrictionsExpiry
['create'] = 'infinity';
2858 $this->mRestrictionsLoaded
= true;
2863 * Flush the protection cache in this object and force reload from the database.
2864 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2866 public function flushRestrictions() {
2867 $this->mRestrictionsLoaded
= false;
2868 $this->mTitleProtection
= null;
2872 * Purge expired restrictions from the page_restrictions table
2874 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2876 static function purgeExpiredRestrictions() {
2877 if ( wfReadOnly() ) {
2881 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2882 wfGetDB( DB_MASTER
),
2884 function ( IDatabase
$dbw, $fname ) {
2885 $config = MediaWikiServices
::getInstance()->getMainConfig();
2886 $ids = $dbw->selectFieldValues(
2887 'page_restrictions',
2889 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2891 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2894 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2899 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2900 wfGetDB( DB_MASTER
),
2902 function ( IDatabase
$dbw, $fname ) {
2905 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2913 * Does this have subpages? (Warning, usually requires an extra DB query.)
2917 public function hasSubpages() {
2919 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2920 hasSubpages( $this->mNamespace
)
2926 # We dynamically add a member variable for the purpose of this method
2927 # alone to cache the result. There's no point in having it hanging
2928 # around uninitialized in every Title object; therefore we only add it
2929 # if needed and don't declare it statically.
2930 if ( $this->mHasSubpages
=== null ) {
2931 $this->mHasSubpages
= false;
2932 $subpages = $this->getSubpages( 1 );
2933 if ( $subpages instanceof TitleArray
) {
2934 $this->mHasSubpages
= (bool)$subpages->current();
2938 return $this->mHasSubpages
;
2942 * Get all subpages of this page.
2944 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2945 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2946 * doesn't allow subpages
2948 public function getSubpages( $limit = -1 ) {
2950 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2951 hasSubpages( $this->mNamespace
)
2956 $dbr = wfGetDB( DB_REPLICA
);
2957 $conds['page_namespace'] = $this->mNamespace
;
2958 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2960 if ( $limit > -1 ) {
2961 $options['LIMIT'] = $limit;
2963 return TitleArray
::newFromResult(
2964 $dbr->select( 'page',
2965 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2974 * Is there a version of this page in the deletion archive?
2976 * @return int The number of archived revisions
2978 public function isDeleted() {
2979 if ( $this->mNamespace
< 0 ) {
2982 $dbr = wfGetDB( DB_REPLICA
);
2984 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2985 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2988 if ( $this->mNamespace
== NS_FILE
) {
2989 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2990 [ 'fa_name' => $this->mDbkeyform
],
2999 * Is there a version of this page in the deletion archive?
3003 public function isDeletedQuick() {
3004 if ( $this->mNamespace
< 0 ) {
3007 $dbr = wfGetDB( DB_REPLICA
);
3008 $deleted = (bool)$dbr->selectField( 'archive', '1',
3009 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3012 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3013 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3014 [ 'fa_name' => $this->mDbkeyform
],
3022 * Get the article ID for this Title from the link cache,
3023 * adding it if necessary
3025 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3027 * @return int The ID
3029 public function getArticleID( $flags = 0 ) {
3030 if ( $this->mNamespace
< 0 ) {
3031 $this->mArticleID
= 0;
3032 return $this->mArticleID
;
3034 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3035 if ( $flags & self
::GAID_FOR_UPDATE
) {
3036 $oldUpdate = $linkCache->forUpdate( true );
3037 $linkCache->clearLink( $this );
3038 $this->mArticleID
= $linkCache->addLinkObj( $this );
3039 $linkCache->forUpdate( $oldUpdate );
3040 } elseif ( $this->mArticleID
== -1 ) {
3041 $this->mArticleID
= $linkCache->addLinkObj( $this );
3043 return $this->mArticleID
;
3047 * Is this an article that is a redirect page?
3048 * Uses link cache, adding it if necessary
3050 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3053 public function isRedirect( $flags = 0 ) {
3054 if ( !is_null( $this->mRedirect
) ) {
3055 return $this->mRedirect
;
3057 if ( !$this->getArticleID( $flags ) ) {
3058 $this->mRedirect
= false;
3059 return $this->mRedirect
;
3062 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3063 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3064 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3065 if ( $cached === null ) {
3066 # Trust LinkCache's state over our own
3067 # LinkCache is telling us that the page doesn't exist, despite there being cached
3068 # data relating to an existing page in $this->mArticleID. Updaters should clear
3069 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3070 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3071 # LinkCache to refresh its data from the master.
3072 $this->mRedirect
= false;
3073 return $this->mRedirect
;
3076 $this->mRedirect
= (bool)$cached;
3078 return $this->mRedirect
;
3082 * What is the length of this page?
3083 * Uses link cache, adding it if necessary
3085 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3088 public function getLength( $flags = 0 ) {
3089 if ( $this->mLength
!= -1 ) {
3090 return $this->mLength
;
3092 if ( !$this->getArticleID( $flags ) ) {
3094 return $this->mLength
;
3096 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3097 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3098 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3099 if ( $cached === null ) {
3100 # Trust LinkCache's state over our own, as for isRedirect()
3102 return $this->mLength
;
3105 $this->mLength
= intval( $cached );
3107 return $this->mLength
;
3111 * What is the page_latest field for this page?
3113 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3114 * @return int Int or 0 if the page doesn't exist
3116 public function getLatestRevID( $flags = 0 ) {
3117 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3118 return intval( $this->mLatestID
);
3120 if ( !$this->getArticleID( $flags ) ) {
3121 $this->mLatestID
= 0;
3122 return $this->mLatestID
;
3124 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3125 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3126 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3127 if ( $cached === null ) {
3128 # Trust LinkCache's state over our own, as for isRedirect()
3129 $this->mLatestID
= 0;
3130 return $this->mLatestID
;
3133 $this->mLatestID
= intval( $cached );
3135 return $this->mLatestID
;
3139 * This clears some fields in this object, and clears any associated
3140 * keys in the "bad links" section of the link cache.
3142 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3143 * loading of the new page_id. It's also called from
3144 * WikiPage::doDeleteArticleReal()
3146 * @param int $newid The new Article ID
3148 public function resetArticleID( $newid ) {
3149 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3150 $linkCache->clearLink( $this );
3152 if ( $newid === false ) {
3153 $this->mArticleID
= -1;
3155 $this->mArticleID
= intval( $newid );
3157 $this->mRestrictionsLoaded
= false;
3158 $this->mRestrictions
= [];
3159 $this->mOldRestrictions
= false;
3160 $this->mRedirect
= null;
3161 $this->mLength
= -1;
3162 $this->mLatestID
= false;
3163 $this->mContentModel
= false;
3164 $this->mEstimateRevisions
= null;
3165 $this->mPageLanguage
= false;
3166 $this->mDbPageLanguage
= false;
3167 $this->mIsBigDeletion
= null;
3170 public static function clearCaches() {
3171 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3172 $linkCache->clear();
3174 $titleCache = self
::getTitleCache();
3175 $titleCache->clear();
3179 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3181 * @param string $text Containing title to capitalize
3182 * @param int $ns Namespace index, defaults to NS_MAIN
3183 * @return string Containing capitalized title
3185 public static function capitalize( $text, $ns = NS_MAIN
) {
3186 $services = MediaWikiServices
::getInstance();
3187 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3188 return $services->getContentLanguage()->ucfirst( $text );
3195 * Secure and split - main initialisation function for this object
3197 * Assumes that mDbkeyform has been set, and is urldecoded
3198 * and uses underscores, but not otherwise munged. This function
3199 * removes illegal characters, splits off the interwiki and
3200 * namespace prefixes, sets the other forms, and canonicalizes
3203 * @throws MalformedTitleException On invalid titles
3204 * @return bool True on success
3206 private function secureAndSplit() {
3207 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3208 // the parsing code with Title, while avoiding massive refactoring.
3209 // @todo: get rid of secureAndSplit, refactor parsing code.
3210 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3211 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3212 /** @var MediaWikiTitleCodec $titleCodec */
3213 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3214 // MalformedTitleException can be thrown here
3215 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3218 $this->setFragment( '#' . $parts['fragment'] );
3219 $this->mInterwiki
= $parts['interwiki'];
3220 $this->mLocalInterwiki
= $parts['local_interwiki'];
3221 $this->mNamespace
= $parts['namespace'];
3222 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3224 $this->mDbkeyform
= $parts['dbkey'];
3225 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3226 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3228 # We already know that some pages won't be in the database!
3229 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3230 $this->mArticleID
= 0;
3237 * Get an array of Title objects linking to this Title
3238 * Also stores the IDs in the link cache.
3240 * WARNING: do not use this function on arbitrary user-supplied titles!
3241 * On heavily-used templates it will max out the memory.
3243 * @param array $options May be FOR UPDATE
3244 * @param string $table Table name
3245 * @param string $prefix Fields prefix
3246 * @return Title[] Array of Title objects linking here
3248 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3249 if ( count( $options ) > 0 ) {
3250 $db = wfGetDB( DB_MASTER
);
3252 $db = wfGetDB( DB_REPLICA
);
3257 self
::getSelectFields(),
3259 "{$prefix}_from=page_id",
3260 "{$prefix}_namespace" => $this->mNamespace
,
3261 "{$prefix}_title" => $this->mDbkeyform
],
3267 if ( $res->numRows() ) {
3268 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3269 foreach ( $res as $row ) {
3270 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3272 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3273 $retVal[] = $titleObj;
3281 * Get an array of Title objects using this Title as a template
3282 * Also stores the IDs in the link cache.
3284 * WARNING: do not use this function on arbitrary user-supplied titles!
3285 * On heavily-used templates it will max out the memory.
3287 * @param array $options Query option to Database::select()
3288 * @return Title[] Array of Title the Title objects linking here
3290 public function getTemplateLinksTo( $options = [] ) {
3291 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3295 * Get an array of Title objects linked from this Title
3296 * Also stores the IDs in the link cache.
3298 * WARNING: do not use this function on arbitrary user-supplied titles!
3299 * On heavily-used templates it will max out the memory.
3301 * @param array $options Query option to Database::select()
3302 * @param string $table Table name
3303 * @param string $prefix Fields prefix
3304 * @return array Array of Title objects linking here
3306 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3307 $id = $this->getArticleID();
3309 # If the page doesn't exist; there can't be any link from this page
3314 $db = wfGetDB( DB_REPLICA
);
3316 $blNamespace = "{$prefix}_namespace";
3317 $blTitle = "{$prefix}_title";
3319 $pageQuery = WikiPage
::getQueryInfo();
3321 [ $table, 'nestpage' => $pageQuery['tables'] ],
3323 [ $blNamespace, $blTitle ],
3324 $pageQuery['fields']
3326 [ "{$prefix}_from" => $id ],
3331 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3332 ] ] +
$pageQuery['joins']
3336 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3337 foreach ( $res as $row ) {
3338 if ( $row->page_id
) {
3339 $titleObj = self
::newFromRow( $row );
3341 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3342 $linkCache->addBadLinkObj( $titleObj );
3344 $retVal[] = $titleObj;
3351 * Get an array of Title objects used on this Title as a template
3352 * Also stores the IDs in the link cache.
3354 * WARNING: do not use this function on arbitrary user-supplied titles!
3355 * On heavily-used templates it will max out the memory.
3357 * @param array $options May be FOR UPDATE
3358 * @return Title[] Array of Title the Title objects used here
3360 public function getTemplateLinksFrom( $options = [] ) {
3361 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3365 * Get an array of Title objects referring to non-existent articles linked
3368 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3369 * should use redirect table in this case).
3370 * @return Title[] Array of Title the Title objects
3372 public function getBrokenLinksFrom() {
3373 if ( $this->getArticleID() == 0 ) {
3374 # All links from article ID 0 are false positives
3378 $dbr = wfGetDB( DB_REPLICA
);
3379 $res = $dbr->select(
3380 [ 'page', 'pagelinks' ],
3381 [ 'pl_namespace', 'pl_title' ],
3383 'pl_from' => $this->getArticleID(),
3384 'page_namespace IS NULL'
3390 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3396 foreach ( $res as $row ) {
3397 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3403 * Get a list of URLs to purge from the CDN cache when this
3406 * @return string[] Array of String the URLs
3408 public function getCdnUrls() {
3410 $this->getInternalURL(),
3411 $this->getInternalURL( 'action=history' )
3414 $pageLang = $this->getPageLanguage();
3415 if ( $pageLang->hasVariants() ) {
3416 $variants = $pageLang->getVariants();
3417 foreach ( $variants as $vCode ) {
3418 $urls[] = $this->getInternalURL( $vCode );
3422 // If we are looking at a css/js user subpage, purge the action=raw.
3423 if ( $this->isUserJsConfigPage() ) {
3424 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3425 } elseif ( $this->isUserJsonConfigPage() ) {
3426 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3427 } elseif ( $this->isUserCssConfigPage() ) {
3428 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3431 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3436 * Purge all applicable CDN URLs
3438 public function purgeSquid() {
3439 DeferredUpdates
::addUpdate(
3440 new CdnCacheUpdate( $this->getCdnUrls() ),
3441 DeferredUpdates
::PRESEND
3446 * Check whether a given move operation would be valid.
3447 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3449 * @deprecated since 1.25, use MovePage's methods instead
3450 * @param Title &$nt The new title
3451 * @param bool $auth Whether to check user permissions (uses $wgUser)
3452 * @param string $reason Is the log summary of the move, used for spam checking
3453 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3455 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3456 wfDeprecated( __METHOD__
, '1.25' );
3460 if ( !( $nt instanceof Title
) ) {
3461 // Normally we'd add this to $errors, but we'll get
3462 // lots of syntax errors if $nt is not an object
3463 return [ [ 'badtitletext' ] ];
3466 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3467 $errors = $mp->isValidMove()->getErrorsArray();
3469 $errors = wfMergeErrorArrays(
3471 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3475 return $errors ?
: true;
3479 * Move a title to a new location
3481 * @deprecated since 1.25, use the MovePage class instead
3482 * @param Title &$nt The new title
3483 * @param bool $auth Indicates whether $wgUser's permissions
3485 * @param string $reason The reason for the move
3486 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3487 * Ignored if the user doesn't have the suppressredirect right.
3488 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3489 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3491 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3492 array $changeTags = []
3494 wfDeprecated( __METHOD__
, '1.25' );
3498 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3499 $method = $auth ?
'moveIfAllowed' : 'move';
3500 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3501 if ( $status->isOK() ) {
3504 return $status->getErrorsArray();
3509 * Move this page's subpages to be subpages of $nt
3511 * @deprecated since 1.34, use MovePage instead
3512 * @param Title $nt Move target
3513 * @param bool $auth Whether $wgUser's permissions should be checked
3514 * @param string $reason The reason for the move
3515 * @param bool $createRedirect Whether to create redirects from the old subpages to
3516 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3517 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3518 * @return array Array with old page titles as keys, and strings (new page titles) or
3519 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3520 * getUserPermissionsErrors()-like error array with numeric indices if
3521 * no pages were moved
3523 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3524 array $changeTags = []
3526 wfDeprecated( __METHOD__
, '1.34' );
3530 $mp = new MovePage( $this, $nt );
3531 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3532 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3534 if ( !$result->isOk() ) {
3535 return $result->getErrorsArray();
3539 foreach ( $result->getValue() as $key => $status ) {
3540 if ( $status->isOK() ) {
3541 $retval[$key] = $status->getValue();
3543 $retval[$key] = $status->getErrorsArray();
3550 * Checks if this page is just a one-rev redirect.
3551 * Adds lock, so don't use just for light purposes.
3555 public function isSingleRevRedirect() {
3556 global $wgContentHandlerUseDB;
3558 $dbw = wfGetDB( DB_MASTER
);
3561 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3562 if ( $wgContentHandlerUseDB ) {
3563 $fields[] = 'page_content_model';
3566 $row = $dbw->selectRow( 'page',
3572 # Cache some fields we may want
3573 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3574 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3575 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3576 $this->mContentModel
= $row && isset( $row->page_content_model
)
3577 ?
strval( $row->page_content_model
)
3580 if ( !$this->mRedirect
) {
3583 # Does the article have a history?
3584 $row = $dbw->selectField( [ 'page', 'revision' ],
3586 [ 'page_namespace' => $this->mNamespace
,
3587 'page_title' => $this->mDbkeyform
,
3589 'page_latest != rev_id'
3594 # Return true if there was no history
3595 return ( $row === false );
3599 * Checks if $this can be moved to a given Title
3600 * - Selects for update, so don't call it unless you mean business
3602 * @deprecated since 1.25, use MovePage's methods instead
3603 * @param Title $nt The new title to check
3606 public function isValidMoveTarget( $nt ) {
3607 wfDeprecated( __METHOD__
, '1.25' );
3609 # Is it an existing file?
3610 if ( $nt->getNamespace() == NS_FILE
) {
3611 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3613 $file->load( File
::READ_LATEST
);
3614 if ( $file->exists() ) {
3615 wfDebug( __METHOD__
. ": file exists\n" );
3619 # Is it a redirect with no history?
3620 if ( !$nt->isSingleRevRedirect() ) {
3621 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3624 # Get the article text
3625 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3626 if ( !is_object( $rev ) ) {
3629 $content = $rev->getContent();
3630 # Does the redirect point to the source?
3631 # Or is it a broken self-redirect, usually caused by namespace collisions?
3632 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3634 if ( $redirTitle ) {
3635 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3636 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3637 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3643 # Fail safe (not a redirect after all. strange.)
3644 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3645 " is a redirect, but it doesn't contain a valid redirect.\n" );
3651 * Get categories to which this Title belongs and return an array of
3652 * categories' names.
3654 * @return array Array of parents in the form:
3655 * $parent => $currentarticle
3657 public function getParentCategories() {
3660 $titleKey = $this->getArticleID();
3662 if ( $titleKey === 0 ) {
3666 $dbr = wfGetDB( DB_REPLICA
);
3668 $res = $dbr->select(
3671 [ 'cl_from' => $titleKey ],
3675 if ( $res->numRows() > 0 ) {
3676 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3677 foreach ( $res as $row ) {
3678 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3679 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3680 $this->getFullText();
3687 * Get a tree of parent categories
3689 * @param array $children Array with the children in the keys, to check for circular refs
3690 * @return array Tree of parent categories
3692 public function getParentCategoryTree( $children = [] ) {
3694 $parents = $this->getParentCategories();
3697 foreach ( $parents as $parent => $current ) {
3698 if ( array_key_exists( $parent, $children ) ) {
3699 # Circular reference
3700 $stack[$parent] = [];
3702 $nt = self
::newFromText( $parent );
3704 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3714 * Get an associative array for selecting this title from
3717 * @return array Array suitable for the $where parameter of DB::select()
3719 public function pageCond() {
3720 if ( $this->mArticleID
> 0 ) {
3721 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3722 return [ 'page_id' => $this->mArticleID
];
3724 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3729 * Get next/previous revision ID relative to another revision ID
3730 * @param int $revId Revision ID. Get the revision that was before this one.
3731 * @param int $flags Title::GAID_FOR_UPDATE
3732 * @param string $dir 'next' or 'prev'
3733 * @return int|bool New revision ID, or false if none exists
3735 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3736 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3737 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3738 $rev = $rl->getRevisionById( $revId, $rlFlags );
3742 $oldRev = $dir === 'next'
3743 ?
$rl->getNextRevision( $rev, $rlFlags )
3744 : $rl->getPreviousRevision( $rev, $rlFlags );
3748 return $oldRev->getId();
3752 * Get the revision ID of the previous revision
3754 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3755 * @param int $revId Revision ID. Get the revision that was before this one.
3756 * @param int $flags Title::GAID_FOR_UPDATE
3757 * @return int|bool Old revision ID, or false if none exists
3759 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3760 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3764 * Get the revision ID of the next revision
3766 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3767 * @param int $revId Revision ID. Get the revision that was after this one.
3768 * @param int $flags Title::GAID_FOR_UPDATE
3769 * @return int|bool Next revision ID, or false if none exists
3771 public function getNextRevisionID( $revId, $flags = 0 ) {
3772 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3776 * Get the first revision of the page
3778 * @param int $flags Title::GAID_FOR_UPDATE
3779 * @return Revision|null If page doesn't exist
3781 public function getFirstRevision( $flags = 0 ) {
3782 $pageId = $this->getArticleID( $flags );
3784 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3785 $revQuery = Revision
::getQueryInfo();
3786 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3787 [ 'rev_page' => $pageId ],
3790 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3791 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3796 return new Revision( $row, 0, $this );
3803 * Get the oldest revision timestamp of this page
3805 * @param int $flags Title::GAID_FOR_UPDATE
3806 * @return string|null MW timestamp
3808 public function getEarliestRevTime( $flags = 0 ) {
3809 $rev = $this->getFirstRevision( $flags );
3810 return $rev ?
$rev->getTimestamp() : null;
3814 * Check if this is a new page
3818 public function isNewPage() {
3819 $dbr = wfGetDB( DB_REPLICA
);
3820 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3824 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3828 public function isBigDeletion() {
3829 global $wgDeleteRevisionsLimit;
3831 if ( !$wgDeleteRevisionsLimit ) {
3835 if ( $this->mIsBigDeletion
=== null ) {
3836 $dbr = wfGetDB( DB_REPLICA
);
3838 $revCount = $dbr->selectRowCount(
3841 [ 'rev_page' => $this->getArticleID() ],
3843 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3846 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3849 return $this->mIsBigDeletion
;
3853 * Get the approximate revision count of this page.
3857 public function estimateRevisionCount() {
3858 if ( !$this->exists() ) {
3862 if ( $this->mEstimateRevisions
=== null ) {
3863 $dbr = wfGetDB( DB_REPLICA
);
3864 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3865 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3868 return $this->mEstimateRevisions
;
3872 * Get the number of revisions between the given revision.
3873 * Used for diffs and other things that really need it.
3875 * @param int|Revision $old Old revision or rev ID (first before range)
3876 * @param int|Revision $new New revision or rev ID (first after range)
3877 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3878 * @return int Number of revisions between these revisions.
3880 public function countRevisionsBetween( $old, $new, $max = null ) {
3881 if ( !( $old instanceof Revision
) ) {
3882 $old = Revision
::newFromTitle( $this, (int)$old );
3884 if ( !( $new instanceof Revision
) ) {
3885 $new = Revision
::newFromTitle( $this, (int)$new );
3887 if ( !$old ||
!$new ) {
3888 return 0; // nothing to compare
3890 $dbr = wfGetDB( DB_REPLICA
);
3892 'rev_page' => $this->getArticleID(),
3893 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3894 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3896 if ( $max !== null ) {
3897 return $dbr->selectRowCount( 'revision', '1',
3900 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3903 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3908 * Get the authors between the given revisions or revision IDs.
3909 * Used for diffs and other things that really need it.
3913 * @param int|Revision $old Old revision or rev ID (first before range by default)
3914 * @param int|Revision $new New revision or rev ID (first after range by default)
3915 * @param int $limit Maximum number of authors
3916 * @param string|array $options (Optional): Single option, or an array of options:
3917 * 'include_old' Include $old in the range; $new is excluded.
3918 * 'include_new' Include $new in the range; $old is excluded.
3919 * 'include_both' Include both $old and $new in the range.
3920 * Unknown option values are ignored.
3921 * @return array|null Names of revision authors in the range; null if not both revisions exist
3923 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3924 if ( !( $old instanceof Revision
) ) {
3925 $old = Revision
::newFromTitle( $this, (int)$old );
3927 if ( !( $new instanceof Revision
) ) {
3928 $new = Revision
::newFromTitle( $this, (int)$new );
3930 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3931 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3932 // in the sanity check below?
3933 if ( !$old ||
!$new ) {
3934 return null; // nothing to compare
3939 $options = (array)$options;
3940 if ( in_array( 'include_old', $options ) ) {
3943 if ( in_array( 'include_new', $options ) ) {
3946 if ( in_array( 'include_both', $options ) ) {
3950 // No DB query needed if $old and $new are the same or successive revisions:
3951 if ( $old->getId() === $new->getId() ) {
3952 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3954 [ $old->getUserText( RevisionRecord
::RAW
) ];
3955 } elseif ( $old->getId() === $new->getParentId() ) {
3956 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3957 $authors[] = $oldUserText = $old->getUserText( RevisionRecord
::RAW
);
3958 $newUserText = $new->getUserText( RevisionRecord
::RAW
);
3959 if ( $oldUserText != $newUserText ) {
3960 $authors[] = $newUserText;
3962 } elseif ( $old_cmp === '>=' ) {
3963 $authors[] = $old->getUserText( RevisionRecord
::RAW
);
3964 } elseif ( $new_cmp === '<=' ) {
3965 $authors[] = $new->getUserText( RevisionRecord
::RAW
);
3969 $dbr = wfGetDB( DB_REPLICA
);
3970 $revQuery = Revision
::getQueryInfo();
3971 $authors = $dbr->selectFieldValues(
3972 $revQuery['tables'],
3973 $revQuery['fields']['rev_user_text'],
3975 'rev_page' => $this->getArticleID(),
3976 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3977 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3979 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3986 * Get the number of authors between the given revisions or revision IDs.
3987 * Used for diffs and other things that really need it.
3989 * @param int|Revision $old Old revision or rev ID (first before range by default)
3990 * @param int|Revision $new New revision or rev ID (first after range by default)
3991 * @param int $limit Maximum number of authors
3992 * @param string|array $options (Optional): Single option, or an array of options:
3993 * 'include_old' Include $old in the range; $new is excluded.
3994 * 'include_new' Include $new in the range; $old is excluded.
3995 * 'include_both' Include both $old and $new in the range.
3996 * Unknown option values are ignored.
3997 * @return int Number of revision authors in the range; zero if not both revisions exist
3999 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4000 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4001 return $authors ?
count( $authors ) : 0;
4005 * Compare with another title.
4007 * @param LinkTarget $title
4010 public function equals( LinkTarget
$title ) {
4011 // Note: === is necessary for proper matching of number-like titles.
4012 return $this->mInterwiki
=== $title->getInterwiki()
4013 && $this->mNamespace
== $title->getNamespace()
4014 && $this->mDbkeyform
=== $title->getDBkey();
4018 * Check if this title is a subpage of another title
4020 * @param Title $title
4023 public function isSubpageOf( Title
$title ) {
4024 return $this->mInterwiki
=== $title->mInterwiki
4025 && $this->mNamespace
== $title->mNamespace
4026 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4030 * Check if page exists. For historical reasons, this function simply
4031 * checks for the existence of the title in the page table, and will
4032 * thus return false for interwiki links, special pages and the like.
4033 * If you want to know if a title can be meaningfully viewed, you should
4034 * probably call the isKnown() method instead.
4036 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4037 * from master/for update
4040 public function exists( $flags = 0 ) {
4041 $exists = $this->getArticleID( $flags ) != 0;
4042 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4047 * Should links to this title be shown as potentially viewable (i.e. as
4048 * "bluelinks"), even if there's no record by this title in the page
4051 * This function is semi-deprecated for public use, as well as somewhat
4052 * misleadingly named. You probably just want to call isKnown(), which
4053 * calls this function internally.
4055 * (ISSUE: Most of these checks are cheap, but the file existence check
4056 * can potentially be quite expensive. Including it here fixes a lot of
4057 * existing code, but we might want to add an optional parameter to skip
4058 * it and any other expensive checks.)
4062 public function isAlwaysKnown() {
4066 * Allows overriding default behavior for determining if a page exists.
4067 * If $isKnown is kept as null, regular checks happen. If it's
4068 * a boolean, this value is returned by the isKnown method.
4072 * @param Title $title
4073 * @param bool|null $isKnown
4075 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4077 if ( !is_null( $isKnown ) ) {
4081 if ( $this->isExternal() ) {
4082 return true; // any interwiki link might be viewable, for all we know
4085 $services = MediaWikiServices
::getInstance();
4086 switch ( $this->mNamespace
) {
4089 // file exists, possibly in a foreign repo
4090 return (bool)$services->getRepoGroup()->findFile( $this );
4092 // valid special page
4093 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4095 // selflink, possibly with fragment
4096 return $this->mDbkeyform
== '';
4098 // known system message
4099 return $this->hasSourceText() !== false;
4106 * Does this title refer to a page that can (or might) be meaningfully
4107 * viewed? In particular, this function may be used to determine if
4108 * links to the title should be rendered as "bluelinks" (as opposed to
4109 * "redlinks" to non-existent pages).
4110 * Adding something else to this function will cause inconsistency
4111 * since LinkHolderArray calls isAlwaysKnown() and does its own
4112 * page existence check.
4116 public function isKnown() {
4117 return $this->isAlwaysKnown() ||
$this->exists();
4121 * Does this page have source text?
4125 public function hasSourceText() {
4126 if ( $this->exists() ) {
4130 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4131 // If the page doesn't exist but is a known system message, default
4132 // message content will be displayed, same for language subpages-
4133 // Use always content language to avoid loading hundreds of languages
4134 // to get the link color.
4135 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4136 list( $name, ) = MessageCache
::singleton()->figureMessage(
4137 $contLang->lcfirst( $this->getText() )
4139 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4140 return $message->exists();
4147 * Get the default (plain) message contents for an page that overrides an
4148 * interface message key.
4150 * Primary use cases:
4153 * - Show default when viewing the page. The Article::getSubstituteContent
4154 * method displays the default message content, instead of the
4155 * 'noarticletext' placeholder message normally used.
4158 * - Title of edit page. When creating an interface message override,
4159 * the editor is told they are "Editing the page", instead of
4160 * "Creating the page". (EditPage::setHeaders)
4161 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4162 * or editing a an interface message override. (EditPage::showIntro)
4163 * - Opening the editor. The contents of the localisation message are used
4164 * as contents of the editor when creating a new page in the MediaWiki
4165 * namespace. This simplifies the process for editors when "changing"
4166 * an interface message by creating an override. (EditPage::getContentObject)
4167 * - Showing a diff. The left-hand side of a diff when an editor is
4168 * previewing their changes before saving the creation of a page in the
4169 * MediaWiki namespace. (EditPage::showDiff)
4170 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4171 * page with the proposed content matching the interface message default,
4172 * the save is rejected, the same way we disallow blank pages from being
4173 * created. (EditPage::internalAttemptSave)
4176 * - Default content, when using the 'prepend' or 'append' feature.
4179 * - Label the create action as "Edit", if the page can be an override.
4181 * @return string|bool
4183 public function getDefaultMessageText() {
4184 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4188 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4189 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4191 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4193 if ( $message->exists() ) {
4194 return $message->plain();
4201 * Updates page_touched for this page; called from LinksUpdate.php
4203 * @param string|null $purgeTime [optional] TS_MW timestamp
4204 * @return bool True if the update succeeded
4206 public function invalidateCache( $purgeTime = null ) {
4207 if ( wfReadOnly() ) {
4209 } elseif ( $this->mArticleID
=== 0 ) {
4210 return true; // avoid gap locking if we know it's not there
4213 $dbw = wfGetDB( DB_MASTER
);
4214 $dbw->onTransactionPreCommitOrIdle(
4215 function () use ( $dbw ) {
4216 ResourceLoaderWikiModule
::invalidateModuleCache(
4217 $this, null, null, $dbw->getDomainID() );
4222 $conds = $this->pageCond();
4223 DeferredUpdates
::addUpdate(
4224 new AutoCommitUpdate(
4227 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4228 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4231 [ 'page_touched' => $dbTimestamp ],
4232 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4235 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4238 DeferredUpdates
::PRESEND
4245 * Update page_touched timestamps and send CDN purge messages for
4246 * pages linking to this title. May be sent to the job queue depending
4247 * on the number of links. Typically called on create and delete.
4249 public function touchLinks() {
4250 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4251 if ( $this->mNamespace
== NS_CATEGORY
) {
4252 DeferredUpdates
::addUpdate(
4253 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4259 * Get the last touched timestamp
4261 * @param IDatabase|null $db
4262 * @return string|false Last-touched timestamp
4264 public function getTouched( $db = null ) {
4265 if ( $db === null ) {
4266 $db = wfGetDB( DB_REPLICA
);
4268 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4273 * Get the timestamp when this page was updated since the user last saw it.
4275 * @param User|null $user
4276 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4278 public function getNotificationTimestamp( $user = null ) {
4281 // Assume current user if none given
4285 // Check cache first
4286 $uid = $user->getId();
4290 // avoid isset here, as it'll return false for null entries
4291 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4292 return $this->mNotificationTimestamp
[$uid];
4294 // Don't cache too much!
4295 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4296 $this->mNotificationTimestamp
= [];
4299 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4300 $watchedItem = $store->getWatchedItem( $user, $this );
4301 if ( $watchedItem ) {
4302 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4304 $this->mNotificationTimestamp
[$uid] = false;
4307 return $this->mNotificationTimestamp
[$uid];
4311 * Generate strings used for xml 'id' names in monobook tabs
4313 * @param string $prepend Defaults to 'nstab-'
4314 * @return string XML 'id' name
4316 public function getNamespaceKey( $prepend = 'nstab-' ) {
4317 // Gets the subject namespace of this title
4318 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4319 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4320 // Prefer canonical namespace name for HTML IDs
4321 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4322 if ( $namespaceKey === false ) {
4323 // Fallback to localised text
4324 $namespaceKey = $this->getSubjectNsText();
4326 // Makes namespace key lowercase
4327 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4329 if ( $namespaceKey == '' ) {
4330 $namespaceKey = 'main';
4332 // Changes file to image for backwards compatibility
4333 if ( $namespaceKey == 'file' ) {
4334 $namespaceKey = 'image';
4336 return $prepend . $namespaceKey;
4340 * Get all extant redirects to this Title
4342 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4343 * @return Title[] Array of Title redirects to this title
4345 public function getRedirectsHere( $ns = null ) {
4348 $dbr = wfGetDB( DB_REPLICA
);
4350 'rd_namespace' => $this->mNamespace
,
4351 'rd_title' => $this->mDbkeyform
,
4354 if ( $this->isExternal() ) {
4355 $where['rd_interwiki'] = $this->mInterwiki
;
4357 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4359 if ( !is_null( $ns ) ) {
4360 $where['page_namespace'] = $ns;
4363 $res = $dbr->select(
4364 [ 'redirect', 'page' ],
4365 [ 'page_namespace', 'page_title' ],
4370 foreach ( $res as $row ) {
4371 $redirs[] = self
::newFromRow( $row );
4377 * Check if this Title is a valid redirect target
4381 public function isValidRedirectTarget() {
4382 global $wgInvalidRedirectTargets;
4384 if ( $this->isSpecialPage() ) {
4385 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4386 if ( $this->isSpecial( 'Userlogout' ) ) {
4390 foreach ( $wgInvalidRedirectTargets as $target ) {
4391 if ( $this->isSpecial( $target ) ) {
4401 * Get a backlink cache object
4403 * @return BacklinkCache
4405 public function getBacklinkCache() {
4406 return BacklinkCache
::get( $this );
4410 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4414 public function canUseNoindex() {
4415 global $wgExemptFromUserRobotsControl;
4417 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4418 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4420 return !in_array( $this->mNamespace
, $bannedNamespaces );
4424 * Returns the raw sort key to be used for categories, with the specified
4425 * prefix. This will be fed to Collation::getSortKey() to get a
4426 * binary sortkey that can be used for actual sorting.
4428 * @param string $prefix The prefix to be used, specified using
4429 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4433 public function getCategorySortkey( $prefix = '' ) {
4434 $unprefixed = $this->getText();
4436 // Anything that uses this hook should only depend
4437 // on the Title object passed in, and should probably
4438 // tell the users to run updateCollations.php --force
4439 // in order to re-sort existing category relations.
4440 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4441 if ( $prefix !== '' ) {
4442 # Separate with a line feed, so the unprefixed part is only used as
4443 # a tiebreaker when two pages have the exact same prefix.
4444 # In UCA, tab is the only character that can sort above LF
4445 # so we strip both of them from the original prefix.
4446 $prefix = strtr( $prefix, "\n\t", ' ' );
4447 return "$prefix\n$unprefixed";
4453 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4454 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4455 * the db, it will return NULL.
4457 * @return string|null|bool
4459 private function getDbPageLanguageCode() {
4460 global $wgPageLanguageUseDB;
4462 // check, if the page language could be saved in the database, and if so and
4463 // the value is not requested already, lookup the page language using LinkCache
4464 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4465 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4466 $linkCache->addLinkObj( $this );
4467 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4470 return $this->mDbPageLanguage
;
4474 * Get the language in which the content of this page is written in
4475 * wikitext. Defaults to content language, but in certain cases it can be
4476 * e.g. $wgLang (such as special pages, which are in the user language).
4481 public function getPageLanguage() {
4482 global $wgLang, $wgLanguageCode;
4483 if ( $this->isSpecialPage() ) {
4484 // special pages are in the user language
4488 // Checking if DB language is set
4489 $dbPageLanguage = $this->getDbPageLanguageCode();
4490 if ( $dbPageLanguage ) {
4491 return wfGetLangObj( $dbPageLanguage );
4494 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4495 // Note that this may depend on user settings, so the cache should
4496 // be only per-request.
4497 // NOTE: ContentHandler::getPageLanguage() may need to load the
4498 // content to determine the page language!
4499 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4501 $contentHandler = ContentHandler
::getForTitle( $this );
4502 $langObj = $contentHandler->getPageLanguage( $this );
4503 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4505 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4512 * Get the language in which the content of this page is written when
4513 * viewed by user. Defaults to content language, but in certain cases it can be
4514 * e.g. $wgLang (such as special pages, which are in the user language).
4519 public function getPageViewLanguage() {
4522 if ( $this->isSpecialPage() ) {
4523 // If the user chooses a variant, the content is actually
4524 // in a language whose code is the variant code.
4525 $variant = $wgLang->getPreferredVariant();
4526 if ( $wgLang->getCode() !== $variant ) {
4527 return Language
::factory( $variant );
4533 // Checking if DB language is set
4534 $dbPageLanguage = $this->getDbPageLanguageCode();
4535 if ( $dbPageLanguage ) {
4536 $pageLang = wfGetLangObj( $dbPageLanguage );
4537 $variant = $pageLang->getPreferredVariant();
4538 if ( $pageLang->getCode() !== $variant ) {
4539 $pageLang = Language
::factory( $variant );
4545 // @note Can't be cached persistently, depends on user settings.
4546 // @note ContentHandler::getPageViewLanguage() may need to load the
4547 // content to determine the page language!
4548 $contentHandler = ContentHandler
::getForTitle( $this );
4549 $pageLang = $contentHandler->getPageViewLanguage( $this );
4554 * Get a list of rendered edit notices for this page.
4556 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4557 * they will already be wrapped in paragraphs.
4560 * @param int $oldid Revision ID that's being edited
4563 public function getEditNotices( $oldid = 0 ) {
4566 // Optional notice for the entire namespace
4567 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4568 $msg = wfMessage( $editnotice_ns );
4569 if ( $msg->exists() ) {
4570 $html = $msg->parseAsBlock();
4571 // Edit notices may have complex logic, but output nothing (T91715)
4572 if ( trim( $html ) !== '' ) {
4573 $notices[$editnotice_ns] = Html
::rawElement(
4577 'mw-editnotice-namespace',
4578 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4586 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4587 hasSubpages( $this->mNamespace
)
4589 // Optional notice for page itself and any parent page
4590 $editnotice_base = $editnotice_ns;
4591 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4592 $editnotice_base .= '-' . $part;
4593 $msg = wfMessage( $editnotice_base );
4594 if ( $msg->exists() ) {
4595 $html = $msg->parseAsBlock();
4596 if ( trim( $html ) !== '' ) {
4597 $notices[$editnotice_base] = Html
::rawElement(
4601 'mw-editnotice-base',
4602 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4610 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4611 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4612 $msg = wfMessage( $editnoticeText );
4613 if ( $msg->exists() ) {
4614 $html = $msg->parseAsBlock();
4615 if ( trim( $html ) !== '' ) {
4616 $notices[$editnoticeText] = Html
::rawElement(
4620 'mw-editnotice-page',
4621 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4629 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4636 public function __sleep() {
4644 'mDefaultNamespace',
4648 public function __wakeup() {
4649 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4650 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4651 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );