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\Revision\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 and inject it into link cache.
56 * @deprecated since 1.34, use Title::READ_LATEST instead.
58 const GAID_FOR_UPDATE
= 512;
61 * Flag for use with factory methods like newFromLinkTarget() that have
62 * a $forceClone parameter. If set, the method must return a new instance.
63 * Without this flag, some factory methods may return existing instances.
67 const NEW_CLONE
= 'clone';
70 * @name Private member variables
71 * Please use the accessor functions instead.
76 /** @var string Text form (spaces not underscores) of the main part */
77 public $mTextform = '';
78 /** @var string URL-encoded form of the main part */
79 public $mUrlform = '';
80 /** @var string Main part with underscores */
81 public $mDbkeyform = '';
82 /** @var string Database key with the initial letter in the case specified by the user */
83 protected $mUserCaseDBKey;
84 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
85 public $mNamespace = NS_MAIN
;
86 /** @var string Interwiki prefix */
87 public $mInterwiki = '';
88 /** @var bool Was this Title created from a string with a local interwiki prefix? */
89 private $mLocalInterwiki = false;
90 /** @var string Title fragment (i.e. the bit after the #) */
91 public $mFragment = '';
93 /** @var int Article ID, fetched from the link cache on demand */
94 public $mArticleID = -1;
96 /** @var bool|int ID of most recent revision */
97 protected $mLatestID = false;
100 * @var bool|string ID of the page's content model, i.e. one of the
101 * CONTENT_MODEL_XXX constants
103 private $mContentModel = false;
106 * @var bool If a content model was forced via setContentModel()
107 * this will be true to avoid having other code paths reset it
109 private $mForcedContentModel = false;
111 /** @var int Estimated number of revisions; null of not loaded */
112 private $mEstimateRevisions;
114 /** @var array Array of groups allowed to edit this article */
115 public $mRestrictions = [];
118 * @var string|bool Comma-separated set of permission keys
119 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
120 * Edit and move sections are separated by a colon
121 * Example: "edit=autoconfirmed,sysop:move=sysop"
123 protected $mOldRestrictions = false;
125 /** @var bool Cascade restrictions on this page to included templates and images? */
126 public $mCascadeRestriction;
128 /** Caching the results of getCascadeProtectionSources */
129 public $mCascadingRestrictions;
131 /** @var array When do the restrictions on this page expire? */
132 protected $mRestrictionsExpiry = [];
134 /** @var bool Are cascading restrictions in effect on this page? */
135 protected $mHasCascadingRestrictions;
137 /** @var array Where are the cascading restrictions coming from on this page? */
138 public $mCascadeSources;
140 /** @var bool Boolean for initialisation on demand */
141 public $mRestrictionsLoaded = false;
144 * Text form including namespace/interwiki, initialised on demand
146 * Only public to share cache with TitleFormatter
151 public $prefixedText = null;
153 /** @var mixed Cached value for getTitleProtection (create protection) */
154 public $mTitleProtection;
157 * @var int Namespace index when there is no namespace. Don't change the
158 * following default, NS_MAIN is hardcoded in several places. See T2696.
159 * Zero except in {{transclusion}} tags.
161 public $mDefaultNamespace = NS_MAIN
;
163 /** @var int The page length, 0 for special pages */
164 protected $mLength = -1;
166 /** @var null Is the article at this title a redirect? */
167 public $mRedirect = null;
169 /** @var array Associative array of user ID -> timestamp/false */
170 private $mNotificationTimestamp = [];
172 /** @var bool Whether a page has any subpages */
173 private $mHasSubpages;
175 /** @var array|null The (string) language code of the page's language and content code. */
176 private $mPageLanguage;
178 /** @var string|bool|null The page language code from the database, null if not saved in
179 * the database or false if not loaded, yet.
181 private $mDbPageLanguage = false;
183 /** @var TitleValue|null A corresponding TitleValue object */
184 private $mTitleValue = null;
186 /** @var bool|null Would deleting this page be a big deletion? */
187 private $mIsBigDeletion = null;
191 * B/C kludge: provide a TitleParser for use by Title.
192 * Ideally, Title would have no methods that need this.
193 * Avoid usage of this singleton by using TitleValue
194 * and the associated services when possible.
196 * @return TitleFormatter
198 private static function getTitleFormatter() {
199 return MediaWikiServices
::getInstance()->getTitleFormatter();
203 * B/C kludge: provide an InterwikiLookup for use by Title.
204 * Ideally, Title would have no methods that need this.
205 * Avoid usage of this singleton by using TitleValue
206 * and the associated services when possible.
208 * @return InterwikiLookup
210 private static function getInterwikiLookup() {
211 return MediaWikiServices
::getInstance()->getInterwikiLookup();
217 function __construct() {
221 * Create a new Title from a prefixed DB key
223 * @param string $key The database key, which has underscores
224 * instead of spaces, possibly including namespace and
226 * @return Title|null Title, or null on an error
228 public static function newFromDBkey( $key ) {
230 $t->mDbkeyform
= $key;
233 $t->secureAndSplit();
235 } catch ( MalformedTitleException
$ex ) {
241 * Returns a Title given a TitleValue.
242 * If the given TitleValue is already a Title instance, that instance is returned,
243 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
244 * is already a Title instance, that instance is copied using the clone operator.
246 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
248 * @param TitleValue $titleValue Assumed to be safe.
249 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
253 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
254 return self
::newFromLinkTarget( $titleValue, $forceClone );
258 * Returns a Title given a LinkTarget.
259 * If the given LinkTarget is already a Title instance, that instance is returned,
260 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
261 * is already a Title instance, that instance is copied using the clone operator.
263 * @param LinkTarget $linkTarget Assumed to be safe.
264 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
268 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
269 if ( $linkTarget instanceof Title
) {
270 // Special case if it's already a Title object
271 if ( $forceClone === self
::NEW_CLONE
) {
272 return clone $linkTarget;
277 return self
::makeTitle(
278 $linkTarget->getNamespace(),
279 $linkTarget->getText(),
280 $linkTarget->getFragment(),
281 $linkTarget->getInterwiki()
286 * Same as newFromLinkTarget, but if passed null, returns null.
288 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
292 public static function castFromLinkTarget( $linkTarget ) {
293 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
297 * Create a new Title from text, such as what one would find in a link. De-
298 * codes any HTML entities in the text.
300 * Title objects returned by this method are guaranteed to be valid, and
301 * thus return true from the isValid() method.
303 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
304 * It may instead be a cached instance created previously, with references to it remaining
307 * @param string|int|null $text The link text; spaces, prefixes, and an
308 * initial ':' indicating the main namespace are accepted.
309 * @param int $defaultNamespace The namespace to use if none is specified
310 * by a prefix. If you want to force a specific namespace even if
311 * $text might begin with a namespace prefix, use makeTitle() or
313 * @throws InvalidArgumentException
314 * @return Title|null Title or null on an error.
316 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
317 // DWIM: Integers can be passed in here when page titles are used as array keys.
318 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
319 throw new InvalidArgumentException( '$text must be a string.' );
321 if ( $text === null ) {
326 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
327 } catch ( MalformedTitleException
$ex ) {
333 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
334 * rather than returning null.
336 * The exception subclasses encode detailed information about why the title is invalid.
338 * Title objects returned by this method are guaranteed to be valid, and
339 * thus return true from the isValid() method.
341 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
342 * It may instead be a cached instance created previously, with references to it remaining
345 * @see Title::newFromText
348 * @param string $text Title text to check
349 * @param int $defaultNamespace
350 * @throws MalformedTitleException If the title is invalid
353 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
354 if ( is_object( $text ) ) {
355 throw new MWException( '$text must be a string, given an object' );
356 } elseif ( $text === null ) {
357 // Legacy code relies on MalformedTitleException being thrown in this case
358 // (happens when URL with no title in it is parsed). TODO fix
359 throw new MalformedTitleException( 'title-invalid-empty' );
362 $titleCache = self
::getTitleCache();
364 // Wiki pages often contain multiple links to the same page.
365 // Title normalization and parsing can become expensive on pages with many
366 // links, so we can save a little time by caching them.
367 // In theory these are value objects and won't get changed...
368 if ( $defaultNamespace == NS_MAIN
) {
369 $t = $titleCache->get( $text );
375 // Convert things like é ā or 〗 into normalized (T16952) text
376 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
379 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
380 $t->mDefaultNamespace
= (int)$defaultNamespace;
382 $t->secureAndSplit();
383 if ( $defaultNamespace == NS_MAIN
) {
384 $titleCache->set( $text, $t );
390 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
392 * Example of wrong and broken code:
393 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
395 * Example of right code:
396 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
398 * Create a new Title from URL-encoded text. Ensures that
399 * the given title's length does not exceed the maximum.
401 * @param string $url The title, as might be taken from a URL
402 * @return Title|null The new object, or null on an error
404 public static function newFromURL( $url ) {
407 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
408 # but some URLs used it as a space replacement and they still come
409 # from some external search tools.
410 if ( strpos( self
::legalChars(), '+' ) === false ) {
411 $url = strtr( $url, '+', ' ' );
414 $t->mDbkeyform
= strtr( $url, ' ', '_' );
417 $t->secureAndSplit();
419 } catch ( MalformedTitleException
$ex ) {
425 * @return MapCacheLRU
427 private static function getTitleCache() {
428 if ( self
::$titleCache === null ) {
429 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
431 return self
::$titleCache;
435 * Returns a list of fields that are to be selected for initializing Title
436 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
437 * whether to include page_content_model.
441 protected static function getSelectFields() {
442 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
445 'page_namespace', 'page_title', 'page_id',
446 'page_len', 'page_is_redirect', 'page_latest',
449 if ( $wgContentHandlerUseDB ) {
450 $fields[] = 'page_content_model';
453 if ( $wgPageLanguageUseDB ) {
454 $fields[] = 'page_lang';
461 * Create a new Title from an article ID
463 * @param int $id The page_id corresponding to the Title to create
464 * @param int $flags Bitfield of class READ_* constants
465 * @return Title|null The new object, or null on an error
467 public static function newFromID( $id, $flags = 0 ) {
468 $flags |
= ( $flags & self
::GAID_FOR_UPDATE
) ? self
::READ_LATEST
: 0; // b/c
469 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
470 $row = wfGetDB( $index )->selectRow(
472 self
::getSelectFields(),
473 [ 'page_id' => $id ],
477 if ( $row !== false ) {
478 $title = self
::newFromRow( $row );
487 * Make an array of titles from an array of IDs
489 * @param int[] $ids Array of IDs
490 * @return Title[] Array of Titles
492 public static function newFromIDs( $ids ) {
493 if ( !count( $ids ) ) {
496 $dbr = wfGetDB( DB_REPLICA
);
500 self
::getSelectFields(),
501 [ 'page_id' => $ids ],
506 foreach ( $res as $row ) {
507 $titles[] = self
::newFromRow( $row );
513 * Make a Title object from a DB row
515 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
516 * @return Title Corresponding Title
518 public static function newFromRow( $row ) {
519 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
520 $t->loadFromRow( $row );
525 * Load Title object fields from a DB row.
526 * If false is given, the title will be treated as non-existing.
528 * @param stdClass|bool $row Database row
530 public function loadFromRow( $row ) {
531 if ( $row ) { // page found
532 if ( isset( $row->page_id
) ) {
533 $this->mArticleID
= (int)$row->page_id
;
535 if ( isset( $row->page_len
) ) {
536 $this->mLength
= (int)$row->page_len
;
538 if ( isset( $row->page_is_redirect
) ) {
539 $this->mRedirect
= (bool)$row->page_is_redirect
;
541 if ( isset( $row->page_latest
) ) {
542 $this->mLatestID
= (int)$row->page_latest
;
544 if ( isset( $row->page_content_model
) ) {
545 $this->lazyFillContentModel( $row->page_content_model
);
547 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
549 if ( isset( $row->page_lang
) ) {
550 $this->mDbPageLanguage
= (string)$row->page_lang
;
552 if ( isset( $row->page_restrictions
) ) {
553 $this->mOldRestrictions
= $row->page_restrictions
;
555 } else { // page not found
556 $this->mArticleID
= 0;
558 $this->mRedirect
= false;
559 $this->mLatestID
= 0;
560 $this->lazyFillContentModel( false ); // lazily-load getContentModel()
565 * Create a new Title from a namespace index and a DB key.
567 * It's assumed that $ns and $title are safe, for instance when
568 * they came directly from the database or a special page name,
569 * not from user input.
571 * No validation is applied. For convenience, spaces are normalized
572 * to underscores, so that e.g. user_text fields can be used directly.
574 * @note This method may return Title objects that are "invalid"
575 * according to the isValid() method. This is usually caused by
576 * configuration changes: e.g. a namespace that was once defined is
577 * no longer configured, or a character that was once allowed in
578 * titles is now forbidden.
580 * @param int $ns The namespace of the article
581 * @param string $title The unprefixed database key form
582 * @param string $fragment The link fragment (after the "#")
583 * @param string $interwiki The interwiki prefix
584 * @return Title The new object
586 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
588 $t->mInterwiki
= $interwiki;
589 $t->mFragment
= $fragment;
590 $t->mNamespace
= $ns = (int)$ns;
591 $t->mDbkeyform
= strtr( $title, ' ', '_' );
592 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
593 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
594 $t->mTextform
= strtr( $title, '_', ' ' );
599 * Create a new Title from a namespace index and a DB key.
600 * The parameters will be checked for validity, which is a bit slower
601 * than makeTitle() but safer for user-provided data.
603 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
604 * that is, they return true from the isValid() method. If no valid Title
605 * can be constructed from the input, this method returns null.
607 * @param int $ns The namespace of the article
608 * @param string $title Database key form
609 * @param string $fragment The link fragment (after the "#")
610 * @param string $interwiki Interwiki prefix
611 * @return Title|null The new object, or null on an error
613 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
614 // NOTE: ideally, this would just call makeTitle() and then isValid(),
615 // but presently, that means more overhead on a potential performance hotspot.
617 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
622 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
625 $t->secureAndSplit();
627 } catch ( MalformedTitleException
$ex ) {
633 * Create a new Title for the Main Page
635 * This uses the 'mainpage' interface message, which could be specified in
636 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
637 * will use the user language, which would involve initialising the session
638 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
639 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
640 * or ResourceloaderContext) to prevent an error.
642 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
643 * It may instead be a cached instance created previously, with references to it remaining
646 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
649 public static function newMainPage( MessageLocalizer
$localizer = null ) {
651 $msg = $localizer->msg( 'mainpage' );
653 $msg = wfMessage( 'mainpage' );
656 $title = self
::newFromText( $msg->inContentLanguage()->text() );
658 // Every page renders at least one link to the Main Page (e.g. sidebar).
659 // If the localised value is invalid, don't produce fatal errors that
660 // would make the wiki inaccessible (and hard to fix the invalid message).
661 // Gracefully fallback...
663 $title = self
::newFromText( 'Main Page' );
669 * Get the prefixed DB key associated with an ID
671 * @param int $id The page_id of the article
672 * @return string|null An object representing the article, or null if no such article was found
674 public static function nameOf( $id ) {
675 $dbr = wfGetDB( DB_REPLICA
);
677 $s = $dbr->selectRow(
679 [ 'page_namespace', 'page_title' ],
680 [ 'page_id' => $id ],
683 if ( $s === false ) {
687 return self
::makeName( $s->page_namespace
, $s->page_title
);
691 * Get a regex character class describing the legal characters in a link
693 * @return string The list of characters, not delimited
695 public static function legalChars() {
696 global $wgLegalTitleChars;
697 return $wgLegalTitleChars;
701 * Utility method for converting a character sequence from bytes to Unicode.
703 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
704 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
706 * @param string $byteClass
709 public static function convertByteClassToUnicodeClass( $byteClass ) {
710 $length = strlen( $byteClass );
712 $x0 = $x1 = $x2 = '';
714 $d0 = $d1 = $d2 = '';
715 // Decoded integer codepoints
716 $ord0 = $ord1 = $ord2 = 0;
718 $r0 = $r1 = $r2 = '';
722 $allowUnicode = false;
723 for ( $pos = 0; $pos < $length; $pos++
) {
724 // Shift the queues down
733 // Load the current input token and decoded values
734 $inChar = $byteClass[$pos];
735 if ( $inChar == '\\' ) {
736 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
737 $x0 = $inChar . $m[0];
738 $d0 = chr( hexdec( $m[1] ) );
739 $pos +
= strlen( $m[0] );
740 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
741 $x0 = $inChar . $m[0];
742 $d0 = chr( octdec( $m[0] ) );
743 $pos +
= strlen( $m[0] );
744 } elseif ( $pos +
1 >= $length ) {
747 $d0 = $byteClass[$pos +
1];
755 // Load the current re-encoded value
756 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
757 $r0 = sprintf( '\x%02x', $ord0 );
758 } elseif ( $ord0 >= 0x80 ) {
759 // Allow unicode if a single high-bit character appears
760 $r0 = sprintf( '\x%02x', $ord0 );
761 $allowUnicode = true;
762 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
763 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
769 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
771 if ( $ord2 > $ord0 ) {
773 } elseif ( $ord0 >= 0x80 ) {
775 $allowUnicode = true;
776 if ( $ord2 < 0x80 ) {
777 // Keep the non-unicode section of the range
784 // Reset state to the initial value
785 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
786 } elseif ( $ord2 < 0x80 ) {
791 if ( $ord1 < 0x80 ) {
794 if ( $ord0 < 0x80 ) {
797 if ( $allowUnicode ) {
798 $out .= '\u0080-\uFFFF';
804 * Make a prefixed DB key from a DB key and a namespace index
806 * @param int $ns Numerical representation of the namespace
807 * @param string $title The DB key form the title
808 * @param string $fragment The link fragment (after the "#")
809 * @param string $interwiki The interwiki prefix
810 * @param bool $canonicalNamespace If true, use the canonical name for
811 * $ns instead of the localized version.
812 * @return string The prefixed form of the title
814 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
815 $canonicalNamespace = false
817 if ( $canonicalNamespace ) {
818 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
819 getCanonicalName( $ns );
821 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
823 $name = $namespace == '' ?
$title : "$namespace:$title";
824 if ( strval( $interwiki ) != '' ) {
825 $name = "$interwiki:$name";
827 if ( strval( $fragment ) != '' ) {
828 $name .= '#' . $fragment;
834 * Callback for usort() to do title sorts by (namespace, title)
836 * @param LinkTarget $a
837 * @param LinkTarget $b
839 * @return int Result of string comparison, or namespace comparison
841 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
842 return $a->getNamespace() <=> $b->getNamespace()
843 ?
: strcmp( $a->getText(), $b->getText() );
847 * Returns true if the title is valid, false if it is invalid.
849 * Valid titles can be round-tripped via makeTitle() and newFromText().
850 * Their DB key can be used in the database, though it may not have the correct
853 * Invalid titles may get returned from makeTitle(), and it may be useful to
854 * allow them to exist, e.g. in order to process log entries about pages in
855 * namespaces that belong to extensions that are no longer installed.
857 * @note This method is relatively expensive. When constructing Title
858 * objects that need to be valid, use an instantiator method that is guaranteed
859 * to return valid titles, such as makeTitleSafe() or newFromText().
863 public function isValid() {
864 $services = MediaWikiServices
::getInstance();
865 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
870 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
871 } catch ( MalformedTitleException
$ex ) {
876 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
883 } catch ( InvalidArgumentException
$ex ) {
891 * Determine whether the object refers to a page within
892 * this project (either this wiki or a wiki with a local
893 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
895 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
897 public function isLocal() {
898 if ( $this->isExternal() ) {
899 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
901 return $iw->isLocal();
908 * Is this Title interwiki?
912 public function isExternal() {
913 return $this->mInterwiki
!== '';
917 * Get the interwiki prefix
919 * Use Title::isExternal to check if a interwiki is set
921 * @return string Interwiki prefix
923 public function getInterwiki() {
924 return $this->mInterwiki
;
928 * Was this a local interwiki link?
932 public function wasLocalInterwiki() {
933 return $this->mLocalInterwiki
;
937 * Determine whether the object refers to a page within
938 * this project and is transcludable.
940 * @return bool True if this is transcludable
942 public function isTrans() {
943 if ( !$this->isExternal() ) {
947 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
951 * Returns the DB name of the distant wiki which owns the object.
953 * @return string|false The DB name
955 public function getTransWikiID() {
956 if ( !$this->isExternal() ) {
960 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
964 * Get a TitleValue object representing this Title.
966 * @note Not all valid Titles have a corresponding valid TitleValue
967 * (e.g. TitleValues cannot represent page-local links that have a
968 * fragment but no title text).
970 * @return TitleValue|null
972 public function getTitleValue() {
973 if ( $this->mTitleValue
=== null ) {
975 $this->mTitleValue
= new TitleValue(
981 } catch ( InvalidArgumentException
$ex ) {
982 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
983 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
987 return $this->mTitleValue
;
991 * Get the text form (spaces not underscores) of the main part
993 * @return string Main part of the title
995 public function getText() {
996 return $this->mTextform
;
1000 * Get the URL-encoded form of the main part
1002 * @return string Main part of the title, URL-encoded
1004 public function getPartialURL() {
1005 return $this->mUrlform
;
1009 * Get the main part with underscores
1011 * @return string Main part of the title, with underscores
1013 public function getDBkey() {
1014 return $this->mDbkeyform
;
1018 * Get the DB key with the initial letter case as specified by the user
1019 * @deprecated since 1.33; please use Title::getDBKey() instead
1021 * @return string DB key
1023 function getUserCaseDBKey() {
1024 if ( !is_null( $this->mUserCaseDBKey
) ) {
1025 return $this->mUserCaseDBKey
;
1027 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1028 return $this->mDbkeyform
;
1033 * Get the namespace index, i.e. one of the NS_xxxx constants.
1035 * @return int Namespace index
1037 public function getNamespace() {
1038 return $this->mNamespace
;
1042 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1044 * @todo Deprecate this in favor of SlotRecord::getModel()
1046 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
1047 * @return string Content model id
1049 public function getContentModel( $flags = 0 ) {
1050 if ( $this->mForcedContentModel
) {
1051 if ( !$this->mContentModel
) {
1052 throw new RuntimeException( 'Got out of sync; an empty model is being forced' );
1054 // Content model is locked to the currently loaded one
1055 return $this->mContentModel
;
1058 if ( DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
) ) {
1059 $this->lazyFillContentModel( $this->loadFieldFromDB( 'page_content_model', $flags ) );
1061 ( !$this->mContentModel ||
$flags & self
::GAID_FOR_UPDATE
) &&
1062 $this->getArticleID( $flags )
1064 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1065 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1066 $this->lazyFillContentModel( $linkCache->getGoodLinkFieldObj( $this, 'model' ) );
1069 if ( !$this->mContentModel
) {
1070 $this->lazyFillContentModel( ContentHandler
::getDefaultModelFor( $this ) );
1073 return $this->mContentModel
;
1077 * Convenience method for checking a title's content model name
1079 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1080 * @return bool True if $this->getContentModel() == $id
1082 public function hasContentModel( $id ) {
1083 return $this->getContentModel() == $id;
1087 * Set a proposed content model for the page for permissions checking
1089 * This does not actually change the content model of a title in the DB.
1090 * It only affects this particular Title instance. The content model is
1091 * forced to remain this value until another setContentModel() call.
1093 * ContentHandler::canBeUsedOn() should be checked before calling this
1094 * if there is any doubt regarding the applicability of the content model
1097 * @param string $model CONTENT_MODEL_XXX constant
1099 public function setContentModel( $model ) {
1100 if ( (string)$model === '' ) {
1101 throw new InvalidArgumentException( "Missing CONTENT_MODEL_* constant" );
1104 $this->mContentModel
= $model;
1105 $this->mForcedContentModel
= true;
1109 * If the content model field is not frozen then update it with a retreived value
1111 * @param string|bool $model CONTENT_MODEL_XXX constant or false
1113 private function lazyFillContentModel( $model ) {
1114 if ( !$this->mForcedContentModel
) {
1115 $this->mContentModel
= ( $model === false ) ?
false : (string)$model;
1120 * Get the namespace text
1122 * @return string|false Namespace text
1124 public function getNsText() {
1125 if ( $this->isExternal() ) {
1126 // This probably shouldn't even happen, except for interwiki transclusion.
1127 // If possible, use the canonical name for the foreign namespace.
1128 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1129 getCanonicalName( $this->mNamespace
);
1130 if ( $nsText !== false ) {
1136 $formatter = self
::getTitleFormatter();
1137 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1138 } catch ( InvalidArgumentException
$ex ) {
1139 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1145 * Get the namespace text of the subject (rather than talk) page
1147 * @return string Namespace text
1149 public function getSubjectNsText() {
1150 $services = MediaWikiServices
::getInstance();
1151 return $services->getContentLanguage()->
1152 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1156 * Get the namespace text of the talk page
1158 * @return string Namespace text
1160 public function getTalkNsText() {
1161 $services = MediaWikiServices
::getInstance();
1162 return $services->getContentLanguage()->
1163 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1167 * Can this title have a corresponding talk page?
1169 * False for relative section links (with getText() === ''),
1170 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1172 * @see NamespaceInfo::canHaveTalkPage
1175 * @return bool True if this title either is a talk page or can have a talk page associated.
1177 public function canHaveTalkPage() {
1178 return MediaWikiServices
::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1182 * Is this in a namespace that allows actual pages?
1186 public function canExist() {
1187 return $this->mNamespace
>= NS_MAIN
;
1191 * Can this title be added to a user's watchlist?
1193 * False for relative section links (with getText() === ''),
1194 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1198 public function isWatchable() {
1199 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
1200 return $this->getText() !== '' && !$this->isExternal() &&
1201 $nsInfo->isWatchable( $this->mNamespace
);
1205 * Returns true if this is a special page.
1209 public function isSpecialPage() {
1210 return $this->mNamespace
== NS_SPECIAL
;
1214 * Returns true if this title resolves to the named special page
1216 * @param string $name The special page name
1219 public function isSpecial( $name ) {
1220 if ( $this->isSpecialPage() ) {
1221 list( $thisName, /* $subpage */ ) =
1222 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1223 resolveAlias( $this->mDbkeyform
);
1224 if ( $name == $thisName ) {
1232 * If the Title refers to a special page alias which is not the local default, resolve
1233 * the alias, and localise the name as necessary. Otherwise, return $this
1237 public function fixSpecialName() {
1238 if ( $this->isSpecialPage() ) {
1239 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1240 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1241 if ( $canonicalName ) {
1242 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1243 if ( $localName != $this->mDbkeyform
) {
1244 return self
::makeTitle( NS_SPECIAL
, $localName );
1252 * Returns true if the title is inside the specified namespace.
1254 * Please make use of this instead of comparing to getNamespace()
1255 * This function is much more resistant to changes we may make
1256 * to namespaces than code that makes direct comparisons.
1257 * @param int $ns The namespace
1261 public function inNamespace( $ns ) {
1262 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1263 equals( $this->mNamespace
, $ns );
1267 * Returns true if the title is inside one of the specified namespaces.
1269 * @param int|int[] $namespaces,... The namespaces to check for
1272 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
1274 public function inNamespaces( /* ... */ ) {
1275 $namespaces = func_get_args();
1276 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1277 $namespaces = $namespaces[0];
1280 foreach ( $namespaces as $ns ) {
1281 if ( $this->inNamespace( $ns ) ) {
1290 * Returns true if the title has the same subject namespace as the
1291 * namespace specified.
1292 * For example this method will take NS_USER and return true if namespace
1293 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1294 * as their subject namespace.
1296 * This is MUCH simpler than individually testing for equivalence
1297 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1302 public function hasSubjectNamespace( $ns ) {
1303 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1304 subjectEquals( $this->mNamespace
, $ns );
1308 * Is this Title in a namespace which contains content?
1309 * In other words, is this a content page, for the purposes of calculating
1314 public function isContentPage() {
1315 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1316 isContent( $this->mNamespace
);
1320 * Would anybody with sufficient privileges be able to move this page?
1321 * Some pages just aren't movable.
1325 public function isMovable() {
1327 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1328 isMovable( $this->mNamespace
) ||
$this->isExternal()
1330 // Interwiki title or immovable namespace. Hooks don't get to override here
1335 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1340 * Is this the mainpage?
1341 * @note Title::newFromText seems to be sufficiently optimized by the title
1342 * cache that we don't need to over-optimize by doing direct comparisons and
1343 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1344 * ends up reporting something differently than $title->isMainPage();
1349 public function isMainPage() {
1350 return $this->equals( self
::newMainPage() );
1354 * Is this a subpage?
1358 public function isSubpage() {
1359 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1360 hasSubpages( $this->mNamespace
)
1361 ?
strpos( $this->getText(), '/' ) !== false
1366 * Is this a conversion table for the LanguageConverter?
1370 public function isConversionTable() {
1371 // @todo ConversionTable should become a separate content model.
1373 return $this->mNamespace
== NS_MEDIAWIKI
&&
1374 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1378 * Does that page contain wikitext, or it is JS, CSS or whatever?
1382 public function isWikitextPage() {
1383 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1387 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1388 * global UI. This is generally true for pages in the MediaWiki namespace having
1389 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1391 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1394 * Note that this method should not return true for pages that contain and show
1395 * "inactive" CSS, JSON, or JS.
1400 public function isSiteConfigPage() {
1402 $this->isSiteCssConfigPage()
1403 ||
$this->isSiteJsonConfigPage()
1404 ||
$this->isSiteJsConfigPage()
1409 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1414 public function isUserConfigPage() {
1416 $this->isUserCssConfigPage()
1417 ||
$this->isUserJsonConfigPage()
1418 ||
$this->isUserJsConfigPage()
1423 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1425 * @return string Containing skin name from .css, .json, or .js subpage title
1428 public function getSkinFromConfigSubpage() {
1429 $subpage = explode( '/', $this->mTextform
);
1430 $subpage = $subpage[count( $subpage ) - 1];
1431 $lastdot = strrpos( $subpage, '.' );
1432 if ( $lastdot === false ) {
1433 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1435 return substr( $subpage, 0, $lastdot );
1439 * Is this a CSS "config" sub-page of a user page?
1444 public function isUserCssConfigPage() {
1446 NS_USER
== $this->mNamespace
1447 && $this->isSubpage()
1448 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1453 * Is this a JSON "config" sub-page of a user page?
1458 public function isUserJsonConfigPage() {
1460 NS_USER
== $this->mNamespace
1461 && $this->isSubpage()
1462 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1467 * Is this a JS "config" sub-page of a user page?
1472 public function isUserJsConfigPage() {
1474 NS_USER
== $this->mNamespace
1475 && $this->isSubpage()
1476 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1481 * Is this a sitewide CSS "config" page?
1486 public function isSiteCssConfigPage() {
1488 NS_MEDIAWIKI
== $this->mNamespace
1490 $this->hasContentModel( CONTENT_MODEL_CSS
)
1491 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1492 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1493 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1499 * Is this a sitewide JSON "config" page?
1504 public function isSiteJsonConfigPage() {
1506 NS_MEDIAWIKI
== $this->mNamespace
1508 $this->hasContentModel( CONTENT_MODEL_JSON
)
1509 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1510 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1511 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1517 * Is this a sitewide JS "config" page?
1522 public function isSiteJsConfigPage() {
1524 NS_MEDIAWIKI
== $this->mNamespace
1526 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1527 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1528 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1529 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1535 * Is this a message which can contain raw HTML?
1540 public function isRawHtmlMessage() {
1541 global $wgRawHtmlMessages;
1543 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1546 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1547 return in_array( $message, $wgRawHtmlMessages, true );
1551 * Is this a talk page of some sort?
1555 public function isTalkPage() {
1556 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1557 isTalk( $this->mNamespace
);
1561 * Get a Title object associated with the talk page of this article
1563 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1564 * with NamespaceInfo::canHaveTalkPage().
1565 * @return Title The object for the talk page
1566 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1567 * or because it's a relative link, or an interwiki link.
1569 public function getTalkPage() {
1570 return self
::castFromLinkTarget(
1571 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1575 * Get a Title object associated with the talk page of this article,
1576 * if such a talk page can exist.
1580 * @return Title|null The object for the talk page,
1581 * or null if no associated talk page can exist, according to canHaveTalkPage().
1583 public function getTalkPageIfDefined() {
1584 if ( !$this->canHaveTalkPage() ) {
1588 return $this->getTalkPage();
1592 * Get a title object associated with the subject page of this
1595 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1596 * @return Title The object for the subject page
1598 public function getSubjectPage() {
1599 return self
::castFromLinkTarget(
1600 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1604 * Get the other title for this page, if this is a subject page
1605 * get the talk page, if it is a subject page get the talk page
1607 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1609 * @throws MWException If the page doesn't have an other page
1612 public function getOtherPage() {
1613 return self
::castFromLinkTarget(
1614 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1618 * Get the default namespace index, for when there is no namespace
1620 * @return int Default namespace index
1622 public function getDefaultNamespace() {
1623 return $this->mDefaultNamespace
;
1627 * Get the Title fragment (i.e.\ the bit after the #) in text form
1629 * Use Title::hasFragment to check for a fragment
1631 * @return string Title fragment
1633 public function getFragment() {
1634 return $this->mFragment
;
1638 * Check if a Title fragment is set
1643 public function hasFragment() {
1644 return $this->mFragment
!== '';
1648 * Get the fragment in URL form, including the "#" character if there is one
1650 * @return string Fragment in URL form
1652 public function getFragmentForURL() {
1653 if ( !$this->hasFragment() ) {
1655 } elseif ( $this->isExternal() ) {
1656 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1657 // so we treat it like a local interwiki.
1658 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1659 if ( $interwiki && !$interwiki->isLocal() ) {
1660 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1664 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1668 * Set the fragment for this title. Removes the first character from the
1669 * specified fragment before setting, so it assumes you're passing it with
1672 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1673 * or Title::createFragmentTarget().
1674 * Still in active use privately.
1677 * @param string $fragment Text
1679 public function setFragment( $fragment ) {
1680 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1684 * Creates a new Title for a different fragment of the same page.
1687 * @param string $fragment
1690 public function createFragmentTarget( $fragment ) {
1691 return self
::makeTitle(
1700 * Prefix some arbitrary text with the namespace or interwiki prefix
1703 * @param string $name The text
1704 * @return string The prefixed text
1706 private function prefix( $name ) {
1708 if ( $this->isExternal() ) {
1709 $p = $this->mInterwiki
. ':';
1712 if ( $this->mNamespace
!= 0 ) {
1713 $nsText = $this->getNsText();
1715 if ( $nsText === false ) {
1716 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1717 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1718 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1721 $p .= $nsText . ':';
1727 * Get the prefixed database key form
1729 * @return string The prefixed title, with underscores and
1730 * any interwiki and namespace prefixes
1732 public function getPrefixedDBkey() {
1733 $s = $this->prefix( $this->mDbkeyform
);
1734 $s = strtr( $s, ' ', '_' );
1739 * Get the prefixed title with spaces.
1740 * This is the form usually used for display
1742 * @return string The prefixed title, with spaces
1744 public function getPrefixedText() {
1745 if ( $this->prefixedText
=== null ) {
1746 $s = $this->prefix( $this->mTextform
);
1747 $s = strtr( $s, '_', ' ' );
1748 $this->prefixedText
= $s;
1750 return $this->prefixedText
;
1754 * Return a string representation of this title
1756 * @return string Representation of this title
1758 public function __toString() {
1759 return $this->getPrefixedText();
1763 * Get the prefixed title with spaces, plus any fragment
1764 * (part beginning with '#')
1766 * @return string The prefixed title, with spaces and the fragment, including '#'
1768 public function getFullText() {
1769 $text = $this->getPrefixedText();
1770 if ( $this->hasFragment() ) {
1771 $text .= '#' . $this->mFragment
;
1777 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1779 * @note the return value may contain trailing whitespace and is thus
1780 * not safe for use with makeTitle or TitleValue.
1784 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1788 * @return string Root name
1791 public function getRootText() {
1793 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1794 hasSubpages( $this->mNamespace
)
1795 ||
strtok( $this->getText(), '/' ) === false
1797 return $this->getText();
1800 return strtok( $this->getText(), '/' );
1804 * Get the root page name title, i.e. the leftmost part before any slashes
1808 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1809 * # returns: Title{User:Foo}
1812 * @return Title Root title
1815 public function getRootTitle() {
1816 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getRootText() );
1817 Assert
::postcondition(
1819 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1825 * Get the base page name without a namespace, i.e. the part before the subpage name
1827 * @note the return value may contain trailing whitespace and is thus
1828 * not safe for use with makeTitle or TitleValue.
1832 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1833 * # returns: 'Foo/Bar'
1836 * @return string Base name
1838 public function getBaseText() {
1839 $text = $this->getText();
1841 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1842 hasSubpages( $this->mNamespace
)
1847 $lastSlashPos = strrpos( $text, '/' );
1848 // Don't discard the real title if there's no subpage involved
1849 if ( $lastSlashPos === false ) {
1853 return substr( $text, 0, $lastSlashPos );
1857 * Get the base page name title, i.e. the part before the subpage name.
1861 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1862 * # returns: Title{User:Foo/Bar}
1865 * @return Title Base title
1868 public function getBaseTitle() {
1869 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getBaseText() );
1870 Assert
::postcondition(
1872 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1878 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1882 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1886 * @return string Subpage name
1888 public function getSubpageText() {
1890 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1891 hasSubpages( $this->mNamespace
)
1893 return $this->mTextform
;
1895 $parts = explode( '/', $this->mTextform
);
1896 return $parts[count( $parts ) - 1];
1900 * Get the title for a subpage of the current page
1904 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1905 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1908 * @param string $text The subpage name to add to the title
1909 * @return Title|null Subpage title, or null on an error
1912 public function getSubpage( $text ) {
1913 return self
::makeTitleSafe(
1915 $this->getText() . '/' . $text,
1922 * Get a URL-encoded form of the subpage text
1924 * @return string URL-encoded subpage name
1926 public function getSubpageUrlForm() {
1927 $text = $this->getSubpageText();
1928 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1933 * Get a URL-encoded title (not an actual URL) including interwiki
1935 * @return string The URL-encoded form
1937 public function getPrefixedURL() {
1938 $s = $this->prefix( $this->mDbkeyform
);
1939 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1944 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1945 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1946 * second argument named variant. This was deprecated in favor
1947 * of passing an array of option with a "variant" key
1948 * Once $query2 is removed for good, this helper can be dropped
1949 * and the wfArrayToCgi moved to getLocalURL();
1951 * @since 1.19 (r105919)
1952 * @param array|string $query
1953 * @param string|string[]|bool $query2
1956 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1957 if ( $query2 !== false ) {
1958 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1959 "method called with a second parameter is deprecated. Add your " .
1960 "parameter to an array passed as the first parameter.", "1.19" );
1962 if ( is_array( $query ) ) {
1963 $query = wfArrayToCgi( $query );
1966 if ( is_string( $query2 ) ) {
1967 // $query2 is a string, we will consider this to be
1968 // a deprecated $variant argument and add it to the query
1969 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1971 $query2 = wfArrayToCgi( $query2 );
1973 // If we have $query content add a & to it first
1977 // Now append the queries together
1984 * Get a real URL referring to this title, with interwiki link and
1987 * @see self::getLocalURL for the arguments.
1989 * @param string|string[] $query
1990 * @param string|string[]|bool $query2
1991 * @param string|int|null $proto Protocol type to use in URL
1992 * @return string The URL
1994 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1995 $query = self
::fixUrlQueryArgs( $query, $query2 );
1997 # Hand off all the decisions on urls to getLocalURL
1998 $url = $this->getLocalURL( $query );
2000 # Expand the url to make it a full url. Note that getLocalURL has the
2001 # potential to output full urls for a variety of reasons, so we use
2002 # wfExpandUrl instead of simply prepending $wgServer
2003 $url = wfExpandUrl( $url, $proto );
2005 # Finally, add the fragment.
2006 $url .= $this->getFragmentForURL();
2007 // Avoid PHP 7.1 warning from passing $this by reference
2009 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
2014 * Get a url appropriate for making redirects based on an untrusted url arg
2016 * This is basically the same as getFullUrl(), but in the case of external
2017 * interwikis, we send the user to a landing page, to prevent possible
2018 * phishing attacks and the like.
2020 * @note Uses current protocol by default, since technically relative urls
2021 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2022 * places where the url gets cached, as might pollute between
2023 * https and non-https users.
2024 * @see self::getLocalURL for the arguments.
2025 * @param array|string $query
2026 * @param string $proto Protocol type to use in URL
2027 * @return string A url suitable to use in an HTTP location header.
2029 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
2031 if ( $this->isExternal() ) {
2032 $target = SpecialPage
::getTitleFor(
2034 $this->getPrefixedDBkey()
2037 return $target->getFullURL( $query, false, $proto );
2041 * Get a URL with no fragment or server name (relative URL) from a Title object.
2042 * If this page is generated with action=render, however,
2043 * $wgServer is prepended to make an absolute URL.
2045 * @see self::getFullURL to always get an absolute URL.
2046 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2047 * valid to link, locally, to the current Title.
2048 * @see self::newFromText to produce a Title object.
2050 * @param string|string[] $query An optional query string,
2051 * not used for interwiki links. Can be specified as an associative array as well,
2052 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2053 * Some query patterns will trigger various shorturl path replacements.
2054 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2055 * be an array. If a string is passed it will be interpreted as a deprecated
2056 * variant argument and urlencoded into a variant= argument.
2057 * This second query argument will be added to the $query
2058 * The second parameter is deprecated since 1.19. Pass it as a key,value
2059 * pair in the first parameter array instead.
2061 * @return string String of the URL.
2063 public function getLocalURL( $query = '', $query2 = false ) {
2064 global $wgArticlePath, $wgScript, $wgServer, $wgRequest, $wgMainPageIsDomainRoot;
2066 $query = self
::fixUrlQueryArgs( $query, $query2 );
2068 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2070 $namespace = $this->getNsText();
2071 if ( $namespace != '' ) {
2072 # Can this actually happen? Interwikis shouldn't be parsed.
2073 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2076 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2077 $url = wfAppendQuery( $url, $query );
2079 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2080 if ( $query == '' ) {
2081 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2082 // Avoid PHP 7.1 warning from passing $this by reference
2084 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2086 global $wgVariantArticlePath, $wgActionPaths;
2090 $articlePaths = PathRouter
::getActionPaths( $wgActionPaths, $wgArticlePath );
2093 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2095 $action = urldecode( $matches[2] );
2096 if ( isset( $articlePaths[$action] ) ) {
2097 $query = $matches[1];
2098 if ( isset( $matches[4] ) ) {
2099 $query .= $matches[4];
2101 $url = str_replace( '$1', $dbkey, $articlePaths[$action] );
2102 if ( $query != '' ) {
2103 $url = wfAppendQuery( $url, $query );
2109 && $wgVariantArticlePath
2110 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2111 && $this->getPageLanguage()->equals(
2112 MediaWikiServices
::getInstance()->getContentLanguage() )
2113 && $this->getPageLanguage()->hasVariants()
2115 $variant = urldecode( $matches[1] );
2116 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2117 // Only do the variant replacement if the given variant is a valid
2118 // variant for the page's language.
2119 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2120 $url = str_replace( '$1', $dbkey, $url );
2124 if ( $url === false ) {
2125 if ( $query == '-' ) {
2128 $url = "{$wgScript}?title={$dbkey}&{$query}";
2131 // Avoid PHP 7.1 warning from passing $this by reference
2133 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2135 // @todo FIXME: This causes breakage in various places when we
2136 // actually expected a local URL and end up with dupe prefixes.
2137 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2138 $url = $wgServer . $url;
2142 if ( $wgMainPageIsDomainRoot && $this->isMainPage() && $query === '' ) {
2146 // Avoid PHP 7.1 warning from passing $this by reference
2148 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2153 * Get a URL that's the simplest URL that will be valid to link, locally,
2154 * to the current Title. It includes the fragment, but does not include
2155 * the server unless action=render is used (or the link is external). If
2156 * there's a fragment but the prefixed text is empty, we just return a link
2159 * The result obviously should not be URL-escaped, but does need to be
2160 * HTML-escaped if it's being output in HTML.
2162 * @param string|string[] $query
2163 * @param bool $query2
2164 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2165 * or false (default) for no expansion
2166 * @see self::getLocalURL for the arguments.
2167 * @return string The URL
2169 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2170 if ( $this->isExternal() ||
$proto !== false ) {
2171 $ret = $this->getFullURL( $query, $query2, $proto );
2172 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2173 $ret = $this->getFragmentForURL();
2175 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2181 * Get the URL form for an internal link.
2182 * - Used in various CDN-related code, in case we have a different
2183 * internal hostname for the server from the exposed one.
2185 * This uses $wgInternalServer to qualify the path, or $wgServer
2186 * if $wgInternalServer is not set. If the server variable used is
2187 * protocol-relative, the URL will be expanded to http://
2189 * @see self::getLocalURL for the arguments.
2190 * @param string|string[] $query
2191 * @param string|bool $query2 Deprecated
2192 * @return string The URL
2194 public function getInternalURL( $query = '', $query2 = false ) {
2195 global $wgInternalServer, $wgServer;
2196 $query = self
::fixUrlQueryArgs( $query, $query2 );
2197 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2198 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2199 // Avoid PHP 7.1 warning from passing $this by reference
2201 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2206 * Get the URL for a canonical link, for use in things like IRC and
2207 * e-mail notifications. Uses $wgCanonicalServer and the
2208 * GetCanonicalURL hook.
2210 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2212 * @see self::getLocalURL for the arguments.
2213 * @param string|string[] $query
2214 * @param string|bool $query2 Deprecated
2215 * @return string The URL
2218 public function getCanonicalURL( $query = '', $query2 = false ) {
2219 $query = self
::fixUrlQueryArgs( $query, $query2 );
2220 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2221 // Avoid PHP 7.1 warning from passing $this by reference
2223 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2228 * Get the edit URL for this Title
2230 * @return string The URL, or a null string if this is an interwiki link
2232 public function getEditURL() {
2233 if ( $this->isExternal() ) {
2236 $s = $this->getLocalURL( 'action=edit' );
2242 * Can $user perform $action on this page?
2243 * This skips potentially expensive cascading permission checks
2244 * as well as avoids expensive error formatting
2246 * Suitable for use for nonessential UI controls in common cases, but
2247 * _not_ for functional access control.
2249 * May provide false positives, but should never provide a false negative.
2251 * @param string $action Action that permission needs to be checked for
2252 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2257 * @deprecated since 1.33,
2258 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2261 public function quickUserCan( $action, $user = null ) {
2262 return $this->userCan( $action, $user, false );
2266 * Can $user perform $action on this page?
2268 * @param string $action Action that permission needs to be checked for
2269 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2271 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2276 * @deprecated since 1.33,
2277 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2280 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2281 if ( !$user instanceof User
) {
2286 // TODO: this is for b/c, eventually will be removed
2287 if ( $rigor === true ) {
2288 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2289 } elseif ( $rigor === false ) {
2290 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2293 return MediaWikiServices
::getInstance()->getPermissionManager()
2294 ->userCan( $action, $user, $this, $rigor );
2298 * Can $user perform $action on this page?
2300 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2302 * @param string $action Action that permission needs to be checked for
2303 * @param User $user User to check
2304 * @param string $rigor One of (quick,full,secure)
2305 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2306 * - full : does cheap and expensive checks possibly from a replica DB
2307 * - secure : does cheap and expensive checks, using the master as needed
2308 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2309 * whose corresponding errors may be ignored.
2311 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2314 * @deprecated since 1.33,
2315 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2318 public function getUserPermissionsErrors(
2319 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2321 // TODO: this is for b/c, eventually will be removed
2322 if ( $rigor === true ) {
2323 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2324 } elseif ( $rigor === false ) {
2325 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2328 return MediaWikiServices
::getInstance()->getPermissionManager()
2329 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2333 * Get a filtered list of all restriction types supported by this wiki.
2334 * @param bool $exists True to get all restriction types that apply to
2335 * titles that do exist, False for all restriction types that apply to
2336 * titles that do not exist
2339 public static function getFilteredRestrictionTypes( $exists = true ) {
2340 global $wgRestrictionTypes;
2341 $types = $wgRestrictionTypes;
2343 # Remove the create restriction for existing titles
2344 $types = array_diff( $types, [ 'create' ] );
2346 # Only the create and upload restrictions apply to non-existing titles
2347 $types = array_intersect( $types, [ 'create', 'upload' ] );
2353 * Returns restriction types for the current Title
2355 * @return array Applicable restriction types
2357 public function getRestrictionTypes() {
2358 if ( $this->isSpecialPage() ) {
2362 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2364 if ( $this->mNamespace
!= NS_FILE
) {
2365 # Remove the upload restriction for non-file titles
2366 $types = array_diff( $types, [ 'upload' ] );
2369 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2371 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2372 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2378 * Is this title subject to title protection?
2379 * Title protection is the one applied against creation of such title.
2381 * @return array|bool An associative array representing any existent title
2382 * protection, or false if there's none.
2384 public function getTitleProtection() {
2385 $protection = $this->getTitleProtectionInternal();
2386 if ( $protection ) {
2387 if ( $protection['permission'] == 'sysop' ) {
2388 $protection['permission'] = 'editprotected'; // B/C
2390 if ( $protection['permission'] == 'autoconfirmed' ) {
2391 $protection['permission'] = 'editsemiprotected'; // B/C
2398 * Fetch title protection settings
2400 * To work correctly, $this->loadRestrictions() needs to have access to the
2401 * actual protections in the database without munging 'sysop' =>
2402 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2403 * callers probably want $this->getTitleProtection() instead.
2405 * @return array|bool
2407 protected function getTitleProtectionInternal() {
2408 // Can't protect pages in special namespaces
2409 if ( $this->mNamespace
< 0 ) {
2413 // Can't protect pages that exist.
2414 if ( $this->exists() ) {
2418 if ( $this->mTitleProtection
=== null ) {
2419 $dbr = wfGetDB( DB_REPLICA
);
2420 $commentStore = CommentStore
::getStore();
2421 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2422 $res = $dbr->select(
2423 [ 'protected_titles' ] +
$commentQuery['tables'],
2425 'user' => 'pt_user',
2426 'expiry' => 'pt_expiry',
2427 'permission' => 'pt_create_perm'
2428 ] +
$commentQuery['fields'],
2429 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2432 $commentQuery['joins']
2435 // fetchRow returns false if there are no rows.
2436 $row = $dbr->fetchRow( $res );
2438 $this->mTitleProtection
= [
2439 'user' => $row['user'],
2440 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2441 'permission' => $row['permission'],
2442 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2445 $this->mTitleProtection
= false;
2448 return $this->mTitleProtection
;
2452 * Remove any title protection due to page existing
2454 public function deleteTitleProtection() {
2455 $dbw = wfGetDB( DB_MASTER
);
2459 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2462 $this->mTitleProtection
= false;
2466 * Is this page "semi-protected" - the *only* protection levels are listed
2467 * in $wgSemiprotectedRestrictionLevels?
2469 * @param string $action Action to check (default: edit)
2472 public function isSemiProtected( $action = 'edit' ) {
2473 global $wgSemiprotectedRestrictionLevels;
2475 $restrictions = $this->getRestrictions( $action );
2476 $semi = $wgSemiprotectedRestrictionLevels;
2477 if ( !$restrictions ||
!$semi ) {
2478 // Not protected, or all protection is full protection
2482 // Remap autoconfirmed to editsemiprotected for BC
2483 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2484 $semi[$key] = 'editsemiprotected';
2486 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2487 $restrictions[$key] = 'editsemiprotected';
2490 return !array_diff( $restrictions, $semi );
2494 * Does the title correspond to a protected article?
2496 * @param string $action The action the page is protected from,
2497 * by default checks all actions.
2500 public function isProtected( $action = '' ) {
2501 global $wgRestrictionLevels;
2503 $restrictionTypes = $this->getRestrictionTypes();
2505 # Special pages have inherent protection
2506 if ( $this->isSpecialPage() ) {
2510 # Check regular protection levels
2511 foreach ( $restrictionTypes as $type ) {
2512 if ( $action == $type ||
$action == '' ) {
2513 $r = $this->getRestrictions( $type );
2514 foreach ( $wgRestrictionLevels as $level ) {
2515 if ( in_array( $level, $r ) && $level != '' ) {
2526 * Determines if $user is unable to edit this page because it has been protected
2527 * by $wgNamespaceProtection.
2529 * @deprecated since 1.34 Don't use this function in new code.
2530 * @param User $user User object to check permissions
2533 public function isNamespaceProtected( User
$user ) {
2534 global $wgNamespaceProtection;
2536 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2537 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2538 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2539 if ( !$permissionManager->userHasRight( $user, $right ) ) {
2548 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2550 * @return bool If the page is subject to cascading restrictions.
2552 public function isCascadeProtected() {
2553 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2554 return ( $sources > 0 );
2558 * Determines whether cascading protection sources have already been loaded from
2561 * @param bool $getPages True to check if the pages are loaded, or false to check
2562 * if the status is loaded.
2563 * @return bool Whether or not the specified information has been loaded
2566 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2567 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2571 * Cascading protection: Get the source of any cascading restrictions on this page.
2573 * @param bool $getPages Whether or not to retrieve the actual pages
2574 * that the restrictions have come from and the actual restrictions
2576 * @return array Two elements: First is an array of Title objects of the
2577 * pages from which cascading restrictions have come, false for
2578 * none, or true if such restrictions exist but $getPages was not
2579 * set. Second is an array like that returned by
2580 * Title::getAllRestrictions(), or an empty array if $getPages is
2583 public function getCascadeProtectionSources( $getPages = true ) {
2584 $pagerestrictions = [];
2586 if ( $this->mCascadeSources
!== null && $getPages ) {
2587 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2588 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2589 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2592 $dbr = wfGetDB( DB_REPLICA
);
2594 if ( $this->mNamespace
== NS_FILE
) {
2595 $tables = [ 'imagelinks', 'page_restrictions' ];
2597 'il_to' => $this->mDbkeyform
,
2602 $tables = [ 'templatelinks', 'page_restrictions' ];
2604 'tl_namespace' => $this->mNamespace
,
2605 'tl_title' => $this->mDbkeyform
,
2612 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2613 'pr_expiry', 'pr_type', 'pr_level' ];
2614 $where_clauses[] = 'page_id=pr_page';
2617 $cols = [ 'pr_expiry' ];
2620 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2622 $sources = $getPages ?
[] : false;
2623 $now = wfTimestampNow();
2625 foreach ( $res as $row ) {
2626 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2627 if ( $expiry > $now ) {
2629 $page_id = $row->pr_page
;
2630 $page_ns = $row->page_namespace
;
2631 $page_title = $row->page_title
;
2632 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2633 # Add groups needed for each restriction type if its not already there
2634 # Make sure this restriction type still exists
2636 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2637 $pagerestrictions[$row->pr_type
] = [];
2641 isset( $pagerestrictions[$row->pr_type
] )
2642 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2644 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2653 $this->mCascadeSources
= $sources;
2654 $this->mCascadingRestrictions
= $pagerestrictions;
2656 $this->mHasCascadingRestrictions
= $sources;
2659 return [ $sources, $pagerestrictions ];
2663 * Accessor for mRestrictionsLoaded
2665 * @return bool Whether or not the page's restrictions have already been
2666 * loaded from the database
2669 public function areRestrictionsLoaded() {
2670 return $this->mRestrictionsLoaded
;
2674 * Accessor/initialisation for mRestrictions
2676 * @param string $action Action that permission needs to be checked for
2677 * @return array Restriction levels needed to take the action. All levels are
2678 * required. Note that restriction levels are normally user rights, but 'sysop'
2679 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2680 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2682 public function getRestrictions( $action ) {
2683 if ( !$this->mRestrictionsLoaded
) {
2684 $this->loadRestrictions();
2686 return $this->mRestrictions
[$action] ??
[];
2690 * Accessor/initialisation for mRestrictions
2692 * @return array Keys are actions, values are arrays as returned by
2693 * Title::getRestrictions()
2696 public function getAllRestrictions() {
2697 if ( !$this->mRestrictionsLoaded
) {
2698 $this->loadRestrictions();
2700 return $this->mRestrictions
;
2704 * Get the expiry time for the restriction against a given action
2706 * @param string $action
2707 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2708 * or not protected at all, or false if the action is not recognised.
2710 public function getRestrictionExpiry( $action ) {
2711 if ( !$this->mRestrictionsLoaded
) {
2712 $this->loadRestrictions();
2714 return $this->mRestrictionsExpiry
[$action] ??
false;
2718 * Returns cascading restrictions for the current article
2722 function areRestrictionsCascading() {
2723 if ( !$this->mRestrictionsLoaded
) {
2724 $this->loadRestrictions();
2727 return $this->mCascadeRestriction
;
2731 * Compiles list of active page restrictions from both page table (pre 1.10)
2732 * and page_restrictions table for this existing page.
2733 * Public for usage by LiquidThreads.
2735 * @param array $rows Array of db result objects
2736 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2737 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2738 * Edit and move sections are separated by a colon
2739 * Example: "edit=autoconfirmed,sysop:move=sysop"
2741 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2742 // This function will only read rows from a table that we migrated away
2743 // from before adding READ_LATEST support to loadRestrictions, so we
2744 // don't need to support reading from DB_MASTER here.
2745 $dbr = wfGetDB( DB_REPLICA
);
2747 $restrictionTypes = $this->getRestrictionTypes();
2749 foreach ( $restrictionTypes as $type ) {
2750 $this->mRestrictions
[$type] = [];
2751 $this->mRestrictionsExpiry
[$type] = 'infinity';
2754 $this->mCascadeRestriction
= false;
2756 # Backwards-compatibility: also load the restrictions from the page record (old format).
2757 if ( $oldFashionedRestrictions !== null ) {
2758 $this->mOldRestrictions
= $oldFashionedRestrictions;
2761 if ( $this->mOldRestrictions
=== false ) {
2762 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2763 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2764 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2767 if ( $this->mOldRestrictions
!= '' ) {
2768 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2769 $temp = explode( '=', trim( $restrict ) );
2770 if ( count( $temp ) == 1 ) {
2771 // old old format should be treated as edit/move restriction
2772 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2773 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2775 $restriction = trim( $temp[1] );
2776 if ( $restriction != '' ) { // some old entries are empty
2777 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2783 if ( count( $rows ) ) {
2784 # Current system - load second to make them override.
2785 $now = wfTimestampNow();
2787 # Cycle through all the restrictions.
2788 foreach ( $rows as $row ) {
2789 // Don't take care of restrictions types that aren't allowed
2790 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2794 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2796 // Only apply the restrictions if they haven't expired!
2797 if ( !$expiry ||
$expiry > $now ) {
2798 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2799 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2801 $this->mCascadeRestriction |
= $row->pr_cascade
;
2806 $this->mRestrictionsLoaded
= true;
2810 * Load restrictions from the page_restrictions table
2812 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2813 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2814 * Edit and move sections are separated by a colon
2815 * Example: "edit=autoconfirmed,sysop:move=sysop"
2816 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2817 * from the master DB.
2819 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2820 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2821 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2825 $id = $this->getArticleID( $flags );
2827 $fname = __METHOD__
;
2828 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2829 return iterator_to_array(
2831 'page_restrictions',
2832 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2833 [ 'pr_page' => $id ],
2839 if ( $readLatest ) {
2840 $dbr = wfGetDB( DB_MASTER
);
2841 $rows = $loadRestrictionsFromDb( $dbr );
2843 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2844 $rows = $cache->getWithSetCallback(
2845 // Page protections always leave a new null revision
2846 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2848 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2849 $dbr = wfGetDB( DB_REPLICA
);
2851 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2852 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2853 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2854 // @TODO: cleanup Title cache and caller assumption mess in general
2855 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2858 return $loadRestrictionsFromDb( $dbr );
2863 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2865 $title_protection = $this->getTitleProtectionInternal();
2867 if ( $title_protection ) {
2868 $now = wfTimestampNow();
2869 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2871 if ( !$expiry ||
$expiry > $now ) {
2872 // Apply the restrictions
2873 $this->mRestrictionsExpiry
['create'] = $expiry;
2874 $this->mRestrictions
['create'] =
2875 explode( ',', trim( $title_protection['permission'] ) );
2876 } else { // Get rid of the old restrictions
2877 $this->mTitleProtection
= false;
2880 $this->mRestrictionsExpiry
['create'] = 'infinity';
2882 $this->mRestrictionsLoaded
= true;
2887 * Flush the protection cache in this object and force reload from the database.
2888 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2890 public function flushRestrictions() {
2891 $this->mRestrictionsLoaded
= false;
2892 $this->mTitleProtection
= null;
2896 * Purge expired restrictions from the page_restrictions table
2898 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2900 static function purgeExpiredRestrictions() {
2901 if ( wfReadOnly() ) {
2905 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2906 wfGetDB( DB_MASTER
),
2908 function ( IDatabase
$dbw, $fname ) {
2909 $config = MediaWikiServices
::getInstance()->getMainConfig();
2910 $ids = $dbw->selectFieldValues(
2911 'page_restrictions',
2913 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2915 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2918 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2923 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2924 wfGetDB( DB_MASTER
),
2926 function ( IDatabase
$dbw, $fname ) {
2929 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2937 * Does this have subpages? (Warning, usually requires an extra DB query.)
2941 public function hasSubpages() {
2943 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2944 hasSubpages( $this->mNamespace
)
2950 # We dynamically add a member variable for the purpose of this method
2951 # alone to cache the result. There's no point in having it hanging
2952 # around uninitialized in every Title object; therefore we only add it
2953 # if needed and don't declare it statically.
2954 if ( $this->mHasSubpages
=== null ) {
2955 $this->mHasSubpages
= false;
2956 $subpages = $this->getSubpages( 1 );
2957 if ( $subpages instanceof TitleArray
) {
2958 $this->mHasSubpages
= (bool)$subpages->current();
2962 return $this->mHasSubpages
;
2966 * Get all subpages of this page.
2968 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2969 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2970 * doesn't allow subpages
2972 public function getSubpages( $limit = -1 ) {
2974 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2975 hasSubpages( $this->mNamespace
)
2980 $dbr = wfGetDB( DB_REPLICA
);
2981 $conds = [ 'page_namespace' => $this->mNamespace
];
2982 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2984 if ( $limit > -1 ) {
2985 $options['LIMIT'] = $limit;
2987 return TitleArray
::newFromResult(
2988 $dbr->select( 'page',
2989 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2998 * Is there a version of this page in the deletion archive?
3000 * @return int The number of archived revisions
3002 public function isDeleted() {
3003 if ( $this->mNamespace
< 0 ) {
3006 $dbr = wfGetDB( DB_REPLICA
);
3008 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3009 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3012 if ( $this->mNamespace
== NS_FILE
) {
3013 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3014 [ 'fa_name' => $this->mDbkeyform
],
3023 * Is there a version of this page in the deletion archive?
3027 public function isDeletedQuick() {
3028 if ( $this->mNamespace
< 0 ) {
3031 $dbr = wfGetDB( DB_REPLICA
);
3032 $deleted = (bool)$dbr->selectField( 'archive', '1',
3033 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3036 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3037 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3038 [ 'fa_name' => $this->mDbkeyform
],
3046 * Get the article ID for this Title from the link cache,
3047 * adding it if necessary
3049 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3050 * @return int The ID
3052 public function getArticleID( $flags = 0 ) {
3053 if ( $this->mNamespace
< 0 ) {
3054 $this->mArticleID
= 0;
3056 return $this->mArticleID
;
3059 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3060 if ( $flags & self
::GAID_FOR_UPDATE
) {
3061 $oldUpdate = $linkCache->forUpdate( true );
3062 $linkCache->clearLink( $this );
3063 $this->mArticleID
= $linkCache->addLinkObj( $this );
3064 $linkCache->forUpdate( $oldUpdate );
3065 } elseif ( DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
) ) {
3066 $this->mArticleID
= (int)$this->loadFieldFromDB( 'page_id', $flags );
3067 } elseif ( $this->mArticleID
== -1 ) {
3068 $this->mArticleID
= $linkCache->addLinkObj( $this );
3071 return $this->mArticleID
;
3075 * Is this an article that is a redirect page?
3076 * Uses link cache, adding it if necessary
3078 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3081 public function isRedirect( $flags = 0 ) {
3082 if ( DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
) ) {
3083 $this->mRedirect
= (bool)$this->loadFieldFromDB( 'page_is_redirect', $flags );
3085 if ( $this->mRedirect
!== null ) {
3086 return $this->mRedirect
;
3087 } elseif ( !$this->getArticleID( $flags ) ) {
3088 $this->mRedirect
= false;
3090 return $this->mRedirect
;
3093 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3094 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3095 // Note that LinkCache returns null if it thinks the page does not exist;
3096 // always trust the state of LinkCache over that of this Title instance.
3097 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3100 return $this->mRedirect
;
3104 * What is the length of this page?
3105 * Uses link cache, adding it if necessary
3107 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3110 public function getLength( $flags = 0 ) {
3111 if ( DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
) ) {
3112 $this->mLength
= (int)$this->loadFieldFromDB( 'page_len', $flags );
3114 if ( $this->mLength
!= -1 ) {
3115 return $this->mLength
;
3116 } elseif ( !$this->getArticleID( $flags ) ) {
3118 return $this->mLength
;
3121 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3122 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3123 // Note that LinkCache returns null if it thinks the page does not exist;
3124 // always trust the state of LinkCache over that of this Title instance.
3125 $this->mLength
= (int)$linkCache->getGoodLinkFieldObj( $this, 'length' );
3128 return $this->mLength
;
3132 * What is the page_latest field for this page?
3134 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
3135 * @return int Int or 0 if the page doesn't exist
3137 public function getLatestRevID( $flags = 0 ) {
3138 if ( DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
) ) {
3139 $this->mLatestID
= (int)$this->loadFieldFromDB( 'page_latest', $flags );
3141 if ( $this->mLatestID
!== false ) {
3142 return (int)$this->mLatestID
;
3143 } elseif ( !$this->getArticleID( $flags ) ) {
3144 $this->mLatestID
= 0;
3146 return $this->mLatestID
;
3149 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3150 $linkCache->addLinkObj( $this ); // in case we already had an article ID
3151 // Note that LinkCache returns null if it thinks the page does not exist;
3152 // always trust the state of LinkCache over that of this Title instance.
3153 $this->mLatestID
= (int)$linkCache->getGoodLinkFieldObj( $this, 'revision' );
3156 return $this->mLatestID
;
3160 * Inject a page ID, reset DB-loaded fields, and clear the link cache for this title
3162 * This can be called on page insertion to allow loading of the new page_id without
3163 * having to create a new Title instance. Likewise with deletion.
3165 * @note This overrides Title::setContentModel()
3167 * @param int|bool $id Page ID, 0 for non-existant, or false for "unknown" (lazy-load)
3169 public function resetArticleID( $id ) {
3170 if ( $id === false ) {
3171 $this->mArticleID
= -1;
3173 $this->mArticleID
= (int)$id;
3175 $this->mRestrictionsLoaded
= false;
3176 $this->mRestrictions
= [];
3177 $this->mOldRestrictions
= false;
3178 $this->mRedirect
= null;
3179 $this->mLength
= -1;
3180 $this->mLatestID
= false;
3181 $this->mContentModel
= false;
3182 $this->mForcedContentModel
= false;
3183 $this->mEstimateRevisions
= null;
3184 $this->mPageLanguage
= null;
3185 $this->mDbPageLanguage
= false;
3186 $this->mIsBigDeletion
= null;
3188 MediaWikiServices
::getInstance()->getLinkCache()->clearLink( $this );
3191 public static function clearCaches() {
3192 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3193 $linkCache->clear();
3195 $titleCache = self
::getTitleCache();
3196 $titleCache->clear();
3200 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3202 * @param string $text Containing title to capitalize
3203 * @param int $ns Namespace index, defaults to NS_MAIN
3204 * @return string Containing capitalized title
3206 public static function capitalize( $text, $ns = NS_MAIN
) {
3207 $services = MediaWikiServices
::getInstance();
3208 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3209 return $services->getContentLanguage()->ucfirst( $text );
3216 * Secure and split - main initialisation function for this object
3218 * Assumes that mDbkeyform has been set, and is urldecoded
3219 * and uses underscores, but not otherwise munged. This function
3220 * removes illegal characters, splits off the interwiki and
3221 * namespace prefixes, sets the other forms, and canonicalizes
3224 * @throws MalformedTitleException On invalid titles
3225 * @return bool True on success
3227 private function secureAndSplit() {
3228 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3229 // the parsing code with Title, while avoiding massive refactoring.
3230 // @todo: get rid of secureAndSplit, refactor parsing code.
3231 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3232 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3233 /** @var MediaWikiTitleCodec $titleCodec */
3234 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3235 '@phan-var MediaWikiTitleCodec $titleCodec';
3236 // MalformedTitleException can be thrown here
3237 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3240 $this->setFragment( '#' . $parts['fragment'] );
3241 $this->mInterwiki
= $parts['interwiki'];
3242 $this->mLocalInterwiki
= $parts['local_interwiki'];
3243 $this->mNamespace
= $parts['namespace'];
3244 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3246 $this->mDbkeyform
= $parts['dbkey'];
3247 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3248 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3250 # We already know that some pages won't be in the database!
3251 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3252 $this->mArticleID
= 0;
3259 * Get an array of Title objects linking to this Title
3260 * Also stores the IDs in the link cache.
3262 * WARNING: do not use this function on arbitrary user-supplied titles!
3263 * On heavily-used templates it will max out the memory.
3265 * @param array $options May be FOR UPDATE
3266 * @param string $table Table name
3267 * @param string $prefix Fields prefix
3268 * @return Title[] Array of Title objects linking here
3270 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3271 if ( count( $options ) > 0 ) {
3272 $db = wfGetDB( DB_MASTER
);
3274 $db = wfGetDB( DB_REPLICA
);
3279 self
::getSelectFields(),
3281 "{$prefix}_from=page_id",
3282 "{$prefix}_namespace" => $this->mNamespace
,
3283 "{$prefix}_title" => $this->mDbkeyform
],
3289 if ( $res->numRows() ) {
3290 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3291 foreach ( $res as $row ) {
3292 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3294 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3295 $retVal[] = $titleObj;
3303 * Get an array of Title objects using this Title as a template
3304 * Also stores the IDs in the link cache.
3306 * WARNING: do not use this function on arbitrary user-supplied titles!
3307 * On heavily-used templates it will max out the memory.
3309 * @param array $options Query option to Database::select()
3310 * @return Title[] Array of Title the Title objects linking here
3312 public function getTemplateLinksTo( $options = [] ) {
3313 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3317 * Get an array of Title objects linked from this Title
3318 * Also stores the IDs in the link cache.
3320 * WARNING: do not use this function on arbitrary user-supplied titles!
3321 * On heavily-used templates it will max out the memory.
3323 * @param array $options Query option to Database::select()
3324 * @param string $table Table name
3325 * @param string $prefix Fields prefix
3326 * @return array Array of Title objects linking here
3328 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3329 $id = $this->getArticleID();
3331 # If the page doesn't exist; there can't be any link from this page
3336 $db = wfGetDB( DB_REPLICA
);
3338 $blNamespace = "{$prefix}_namespace";
3339 $blTitle = "{$prefix}_title";
3341 $pageQuery = WikiPage
::getQueryInfo();
3343 [ $table, 'nestpage' => $pageQuery['tables'] ],
3345 [ $blNamespace, $blTitle ],
3346 $pageQuery['fields']
3348 [ "{$prefix}_from" => $id ],
3353 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3354 ] ] +
$pageQuery['joins']
3358 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3359 foreach ( $res as $row ) {
3360 if ( $row->page_id
) {
3361 $titleObj = self
::newFromRow( $row );
3363 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3364 $linkCache->addBadLinkObj( $titleObj );
3366 $retVal[] = $titleObj;
3373 * Get an array of Title objects used on this Title as a template
3374 * Also stores the IDs in the link cache.
3376 * WARNING: do not use this function on arbitrary user-supplied titles!
3377 * On heavily-used templates it will max out the memory.
3379 * @param array $options May be FOR UPDATE
3380 * @return Title[] Array of Title the Title objects used here
3382 public function getTemplateLinksFrom( $options = [] ) {
3383 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3387 * Get an array of Title objects referring to non-existent articles linked
3390 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3391 * should use redirect table in this case).
3392 * @return Title[] Array of Title the Title objects
3394 public function getBrokenLinksFrom() {
3395 if ( $this->getArticleID() == 0 ) {
3396 # All links from article ID 0 are false positives
3400 $dbr = wfGetDB( DB_REPLICA
);
3401 $res = $dbr->select(
3402 [ 'page', 'pagelinks' ],
3403 [ 'pl_namespace', 'pl_title' ],
3405 'pl_from' => $this->getArticleID(),
3406 'page_namespace IS NULL'
3412 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3418 foreach ( $res as $row ) {
3419 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3425 * Get a list of URLs to purge from the CDN cache when this
3428 * @return string[] Array of String the URLs
3430 public function getCdnUrls() {
3432 $this->getInternalURL(),
3433 $this->getInternalURL( 'action=history' )
3436 $pageLang = $this->getPageLanguage();
3437 if ( $pageLang->hasVariants() ) {
3438 $variants = $pageLang->getVariants();
3439 foreach ( $variants as $vCode ) {
3440 $urls[] = $this->getInternalURL( $vCode );
3444 // If we are looking at a css/js user subpage, purge the action=raw.
3445 if ( $this->isUserJsConfigPage() ) {
3446 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3447 } elseif ( $this->isUserJsonConfigPage() ) {
3448 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3449 } elseif ( $this->isUserCssConfigPage() ) {
3450 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3453 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3458 * Purge all applicable CDN URLs
3460 public function purgeSquid() {
3461 DeferredUpdates
::addUpdate(
3462 new CdnCacheUpdate( $this->getCdnUrls() ),
3463 DeferredUpdates
::PRESEND
3468 * Check whether a given move operation would be valid.
3469 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3471 * @deprecated since 1.25, use MovePage's methods instead
3472 * @param Title &$nt The new title
3473 * @param bool $auth Whether to check user permissions (uses $wgUser)
3474 * @param string $reason Is the log summary of the move, used for spam checking
3475 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3477 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3478 wfDeprecated( __METHOD__
, '1.25' );
3482 if ( !( $nt instanceof Title
) ) {
3483 // Normally we'd add this to $errors, but we'll get
3484 // lots of syntax errors if $nt is not an object
3485 return [ [ 'badtitletext' ] ];
3488 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3489 $errors = $mp->isValidMove()->getErrorsArray();
3491 $errors = wfMergeErrorArrays(
3493 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3497 return $errors ?
: true;
3501 * Move a title to a new location
3503 * @deprecated since 1.25, use the MovePage class instead
3504 * @param Title &$nt The new title
3505 * @param bool $auth Indicates whether $wgUser's permissions
3507 * @param string $reason The reason for the move
3508 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3509 * Ignored if the user doesn't have the suppressredirect right.
3510 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3511 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3513 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3514 array $changeTags = []
3516 wfDeprecated( __METHOD__
, '1.25' );
3520 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3521 $method = $auth ?
'moveIfAllowed' : 'move';
3522 /** @var Status $status */
3523 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3524 if ( $status->isOK() ) {
3527 return $status->getErrorsArray();
3532 * Move this page's subpages to be subpages of $nt
3534 * @deprecated since 1.34, use MovePage instead
3535 * @param Title $nt Move target
3536 * @param bool $auth Whether $wgUser's permissions should be checked
3537 * @param string $reason The reason for the move
3538 * @param bool $createRedirect Whether to create redirects from the old subpages to
3539 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3540 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3541 * @return array Array with old page titles as keys, and strings (new page titles) or
3542 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3543 * getUserPermissionsErrors()-like error array with numeric indices if
3544 * no pages were moved
3546 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3547 array $changeTags = []
3549 wfDeprecated( __METHOD__
, '1.34' );
3553 $mp = new MovePage( $this, $nt );
3554 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3555 /** @var Status $result */
3556 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3558 if ( !$result->isOK() ) {
3559 return $result->getErrorsArray();
3563 foreach ( $result->getValue() as $key => $status ) {
3564 /** @var Status $status */
3565 if ( $status->isOK() ) {
3566 $retval[$key] = $status->getValue();
3568 $retval[$key] = $status->getErrorsArray();
3575 * Locks the page row and check if this page is single revision redirect
3577 * This updates the cached fields of this instance via Title::loadFromRow()
3581 public function isSingleRevRedirect() {
3582 global $wgContentHandlerUseDB;
3584 $dbw = wfGetDB( DB_MASTER
);
3587 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3588 if ( $wgContentHandlerUseDB ) {
3589 $fields[] = 'page_content_model';
3592 $row = $dbw->selectRow( 'page',
3598 # Cache some fields we may want
3599 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3600 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3601 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3602 $this->mContentModel
= $row && isset( $row->page_content_model
)
3603 ?
strval( $row->page_content_model
)
3606 if ( !$this->mRedirect
) {
3609 # Does the article have a history?
3610 $row = $dbw->selectField( [ 'page', 'revision' ],
3612 [ 'page_namespace' => $this->mNamespace
,
3613 'page_title' => $this->mDbkeyform
,
3615 'page_latest != rev_id'
3620 # Return true if there was no history
3621 return ( $row === false );
3625 * Checks if $this can be moved to a given Title
3626 * - Selects for update, so don't call it unless you mean business
3628 * @deprecated since 1.25, use MovePage's methods instead
3629 * @param Title $nt The new title to check
3632 public function isValidMoveTarget( $nt ) {
3633 wfDeprecated( __METHOD__
, '1.25' );
3635 # Is it an existing file?
3636 if ( $nt->getNamespace() == NS_FILE
) {
3637 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3639 $file->load( File
::READ_LATEST
);
3640 if ( $file->exists() ) {
3641 wfDebug( __METHOD__
. ": file exists\n" );
3645 # Is it a redirect with no history?
3646 if ( !$nt->isSingleRevRedirect() ) {
3647 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3650 # Get the article text
3651 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3652 if ( !is_object( $rev ) ) {
3655 $content = $rev->getContent();
3656 # Does the redirect point to the source?
3657 # Or is it a broken self-redirect, usually caused by namespace collisions?
3658 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3660 if ( $redirTitle ) {
3661 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3662 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3663 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3669 # Fail safe (not a redirect after all. strange.)
3670 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3671 " is a redirect, but it doesn't contain a valid redirect.\n" );
3677 * Get categories to which this Title belongs and return an array of
3678 * categories' names.
3680 * @return array Array of parents in the form:
3681 * $parent => $currentarticle
3683 public function getParentCategories() {
3686 $titleKey = $this->getArticleID();
3688 if ( $titleKey === 0 ) {
3692 $dbr = wfGetDB( DB_REPLICA
);
3694 $res = $dbr->select(
3697 [ 'cl_from' => $titleKey ],
3701 if ( $res->numRows() > 0 ) {
3702 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3703 foreach ( $res as $row ) {
3704 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3705 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3706 $this->getFullText();
3713 * Get a tree of parent categories
3715 * @param array $children Array with the children in the keys, to check for circular refs
3716 * @return array Tree of parent categories
3718 public function getParentCategoryTree( $children = [] ) {
3720 $parents = $this->getParentCategories();
3723 foreach ( $parents as $parent => $current ) {
3724 if ( array_key_exists( $parent, $children ) ) {
3725 # Circular reference
3726 $stack[$parent] = [];
3728 $nt = self
::newFromText( $parent );
3730 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3740 * Get an associative array for selecting this title from
3743 * @return array Array suitable for the $where parameter of DB::select()
3745 public function pageCond() {
3746 if ( $this->mArticleID
> 0 ) {
3747 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3748 return [ 'page_id' => $this->mArticleID
];
3750 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3755 * Get next/previous revision ID relative to another revision ID
3756 * @param int $revId Revision ID. Get the revision that was before this one.
3757 * @param int $flags Bitfield of class READ_* constants
3758 * @param string $dir 'next' or 'prev'
3759 * @return int|bool New revision ID, or false if none exists
3761 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3762 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3763 $rev = $rl->getRevisionById( $revId, $flags );
3768 $oldRev = ( $dir === 'next' )
3769 ?
$rl->getNextRevision( $rev, $flags )
3770 : $rl->getPreviousRevision( $rev, $flags );
3772 return $oldRev ?
$oldRev->getId() : false;
3776 * Get the revision ID of the previous revision
3778 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3779 * @param int $revId Revision ID. Get the revision that was before this one.
3780 * @param int $flags Bitfield of class READ_* constants
3781 * @return int|bool Old revision ID, or false if none exists
3783 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3784 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3788 * Get the revision ID of the next revision
3790 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3791 * @param int $revId Revision ID. Get the revision that was after this one.
3792 * @param int $flags Bitfield of class READ_* constants
3793 * @return int|bool Next revision ID, or false if none exists
3795 public function getNextRevisionID( $revId, $flags = 0 ) {
3796 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3800 * Get the first revision of the page
3802 * @param int $flags Bitfield of class READ_* constants
3803 * @return Revision|null If page doesn't exist
3805 public function getFirstRevision( $flags = 0 ) {
3806 $pageId = $this->getArticleID( $flags );
3808 $flags |
= ( $flags & self
::GAID_FOR_UPDATE
) ? self
::READ_LATEST
: 0; // b/c
3809 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
3810 $revQuery = Revision
::getQueryInfo();
3811 $row = wfGetDB( $index )->selectRow(
3812 $revQuery['tables'], $revQuery['fields'],
3813 [ 'rev_page' => $pageId ],
3817 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3818 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3825 return new Revision( $row, 0, $this );
3832 * Get the oldest revision timestamp of this page
3834 * @param int $flags Bitfield of class READ_* constants
3835 * @return string|null MW timestamp
3837 public function getEarliestRevTime( $flags = 0 ) {
3838 $rev = $this->getFirstRevision( $flags );
3839 return $rev ?
$rev->getTimestamp() : null;
3843 * Check if this is a new page
3847 public function isNewPage() {
3848 $dbr = wfGetDB( DB_REPLICA
);
3849 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3853 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3857 public function isBigDeletion() {
3858 global $wgDeleteRevisionsLimit;
3860 if ( !$wgDeleteRevisionsLimit ) {
3864 if ( $this->mIsBigDeletion
=== null ) {
3865 $dbr = wfGetDB( DB_REPLICA
);
3867 $revCount = $dbr->selectRowCount(
3870 [ 'rev_page' => $this->getArticleID() ],
3872 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3875 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3878 return $this->mIsBigDeletion
;
3882 * Get the approximate revision count of this page.
3886 public function estimateRevisionCount() {
3887 if ( !$this->exists() ) {
3891 if ( $this->mEstimateRevisions
=== null ) {
3892 $dbr = wfGetDB( DB_REPLICA
);
3893 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3894 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3897 return $this->mEstimateRevisions
;
3901 * Get the number of revisions between the given revision.
3902 * Used for diffs and other things that really need it.
3904 * @param int|Revision $old Old revision or rev ID (first before range)
3905 * @param int|Revision $new New revision or rev ID (first after range)
3906 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3907 * @return int Number of revisions between these revisions.
3909 public function countRevisionsBetween( $old, $new, $max = null ) {
3910 if ( !( $old instanceof Revision
) ) {
3911 $old = Revision
::newFromTitle( $this, (int)$old );
3913 if ( !( $new instanceof Revision
) ) {
3914 $new = Revision
::newFromTitle( $this, (int)$new );
3916 if ( !$old ||
!$new ) {
3917 return 0; // nothing to compare
3919 $dbr = wfGetDB( DB_REPLICA
);
3921 'rev_page' => $this->getArticleID(),
3922 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3923 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3925 if ( $max !== null ) {
3926 return $dbr->selectRowCount( 'revision', '1',
3929 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3932 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3937 * Get the authors between the given revisions or revision IDs.
3938 * Used for diffs and other things that really need it.
3942 * @param int|Revision $old Old revision or rev ID (first before range by default)
3943 * @param int|Revision $new New revision or rev ID (first after range by default)
3944 * @param int $limit Maximum number of authors
3945 * @param string|array $options (Optional): Single option, or an array of options:
3946 * 'include_old' Include $old in the range; $new is excluded.
3947 * 'include_new' Include $new in the range; $old is excluded.
3948 * 'include_both' Include both $old and $new in the range.
3949 * Unknown option values are ignored.
3950 * @return array|null Names of revision authors in the range; null if not both revisions exist
3952 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3953 if ( !( $old instanceof Revision
) ) {
3954 $old = Revision
::newFromTitle( $this, (int)$old );
3956 if ( !( $new instanceof Revision
) ) {
3957 $new = Revision
::newFromTitle( $this, (int)$new );
3959 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3960 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3961 // in the sanity check below?
3962 if ( !$old ||
!$new ) {
3963 return null; // nothing to compare
3968 $options = (array)$options;
3969 if ( in_array( 'include_old', $options ) ) {
3972 if ( in_array( 'include_new', $options ) ) {
3975 if ( in_array( 'include_both', $options ) ) {
3979 // No DB query needed if $old and $new are the same or successive revisions:
3980 if ( $old->getId() === $new->getId() ) {
3981 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3983 [ $old->getUserText( RevisionRecord
::RAW
) ];
3984 } elseif ( $old->getId() === $new->getParentId() ) {
3985 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3986 $authors[] = $oldUserText = $old->getUserText( RevisionRecord
::RAW
);
3987 $newUserText = $new->getUserText( RevisionRecord
::RAW
);
3988 if ( $oldUserText != $newUserText ) {
3989 $authors[] = $newUserText;
3991 } elseif ( $old_cmp === '>=' ) {
3992 $authors[] = $old->getUserText( RevisionRecord
::RAW
);
3993 } elseif ( $new_cmp === '<=' ) {
3994 $authors[] = $new->getUserText( RevisionRecord
::RAW
);
3998 $dbr = wfGetDB( DB_REPLICA
);
3999 $revQuery = Revision
::getQueryInfo();
4000 $authors = $dbr->selectFieldValues(
4001 $revQuery['tables'],
4002 $revQuery['fields']['rev_user_text'],
4004 'rev_page' => $this->getArticleID(),
4005 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4006 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4008 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4015 * Get the number of authors between the given revisions or revision IDs.
4016 * Used for diffs and other things that really need it.
4018 * @param int|Revision $old Old revision or rev ID (first before range by default)
4019 * @param int|Revision $new New revision or rev ID (first after range by default)
4020 * @param int $limit Maximum number of authors
4021 * @param string|array $options (Optional): Single option, or an array of options:
4022 * 'include_old' Include $old in the range; $new is excluded.
4023 * 'include_new' Include $new in the range; $old is excluded.
4024 * 'include_both' Include both $old and $new in the range.
4025 * Unknown option values are ignored.
4026 * @return int Number of revision authors in the range; zero if not both revisions exist
4028 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4029 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4030 return $authors ?
count( $authors ) : 0;
4034 * Compare with another title.
4036 * @param LinkTarget $title
4039 public function equals( LinkTarget
$title ) {
4040 // Note: === is necessary for proper matching of number-like titles.
4041 return $this->mInterwiki
=== $title->getInterwiki()
4042 && $this->mNamespace
== $title->getNamespace()
4043 && $this->mDbkeyform
=== $title->getDBkey();
4047 * Check if this title is a subpage of another title
4049 * @param Title $title
4052 public function isSubpageOf( Title
$title ) {
4053 return $this->mInterwiki
=== $title->mInterwiki
4054 && $this->mNamespace
== $title->mNamespace
4055 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4059 * Check if page exists. For historical reasons, this function simply
4060 * checks for the existence of the title in the page table, and will
4061 * thus return false for interwiki links, special pages and the like.
4062 * If you want to know if a title can be meaningfully viewed, you should
4063 * probably call the isKnown() method instead.
4065 * @param int $flags Either a bitfield of class READ_* constants or GAID_FOR_UPDATE
4068 public function exists( $flags = 0 ) {
4069 $exists = $this->getArticleID( $flags ) != 0;
4070 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4075 * Should links to this title be shown as potentially viewable (i.e. as
4076 * "bluelinks"), even if there's no record by this title in the page
4079 * This function is semi-deprecated for public use, as well as somewhat
4080 * misleadingly named. You probably just want to call isKnown(), which
4081 * calls this function internally.
4083 * (ISSUE: Most of these checks are cheap, but the file existence check
4084 * can potentially be quite expensive. Including it here fixes a lot of
4085 * existing code, but we might want to add an optional parameter to skip
4086 * it and any other expensive checks.)
4090 public function isAlwaysKnown() {
4094 * Allows overriding default behavior for determining if a page exists.
4095 * If $isKnown is kept as null, regular checks happen. If it's
4096 * a boolean, this value is returned by the isKnown method.
4100 * @param Title $title
4101 * @param bool|null $isKnown
4103 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4105 if ( !is_null( $isKnown ) ) {
4109 if ( $this->isExternal() ) {
4110 return true; // any interwiki link might be viewable, for all we know
4113 $services = MediaWikiServices
::getInstance();
4114 switch ( $this->mNamespace
) {
4117 // file exists, possibly in a foreign repo
4118 return (bool)$services->getRepoGroup()->findFile( $this );
4120 // valid special page
4121 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4123 // selflink, possibly with fragment
4124 return $this->mDbkeyform
== '';
4126 // known system message
4127 return $this->hasSourceText() !== false;
4134 * Does this title refer to a page that can (or might) be meaningfully
4135 * viewed? In particular, this function may be used to determine if
4136 * links to the title should be rendered as "bluelinks" (as opposed to
4137 * "redlinks" to non-existent pages).
4138 * Adding something else to this function will cause inconsistency
4139 * since LinkHolderArray calls isAlwaysKnown() and does its own
4140 * page existence check.
4144 public function isKnown() {
4145 return $this->isAlwaysKnown() ||
$this->exists();
4149 * Does this page have source text?
4153 public function hasSourceText() {
4154 if ( $this->exists() ) {
4158 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4159 // If the page doesn't exist but is a known system message, default
4160 // message content will be displayed, same for language subpages-
4161 // Use always content language to avoid loading hundreds of languages
4162 // to get the link color.
4163 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4164 list( $name, ) = MessageCache
::singleton()->figureMessage(
4165 $contLang->lcfirst( $this->getText() )
4167 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4168 return $message->exists();
4175 * Get the default (plain) message contents for an page that overrides an
4176 * interface message key.
4178 * Primary use cases:
4181 * - Show default when viewing the page. The Article::getSubstituteContent
4182 * method displays the default message content, instead of the
4183 * 'noarticletext' placeholder message normally used.
4186 * - Title of edit page. When creating an interface message override,
4187 * the editor is told they are "Editing the page", instead of
4188 * "Creating the page". (EditPage::setHeaders)
4189 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4190 * or editing a an interface message override. (EditPage::showIntro)
4191 * - Opening the editor. The contents of the localisation message are used
4192 * as contents of the editor when creating a new page in the MediaWiki
4193 * namespace. This simplifies the process for editors when "changing"
4194 * an interface message by creating an override. (EditPage::getContentObject)
4195 * - Showing a diff. The left-hand side of a diff when an editor is
4196 * previewing their changes before saving the creation of a page in the
4197 * MediaWiki namespace. (EditPage::showDiff)
4198 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4199 * page with the proposed content matching the interface message default,
4200 * the save is rejected, the same way we disallow blank pages from being
4201 * created. (EditPage::internalAttemptSave)
4204 * - Default content, when using the 'prepend' or 'append' feature.
4207 * - Label the create action as "Edit", if the page can be an override.
4209 * @return string|bool
4211 public function getDefaultMessageText() {
4212 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4216 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4217 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4219 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4221 if ( $message->exists() ) {
4222 return $message->plain();
4229 * Updates page_touched for this page; called from LinksUpdate.php
4231 * @param string|null $purgeTime [optional] TS_MW timestamp
4232 * @return bool True if the update succeeded
4234 public function invalidateCache( $purgeTime = null ) {
4235 if ( wfReadOnly() ) {
4237 } elseif ( $this->mArticleID
=== 0 ) {
4238 return true; // avoid gap locking if we know it's not there
4241 $dbw = wfGetDB( DB_MASTER
);
4242 $dbw->onTransactionPreCommitOrIdle(
4243 function () use ( $dbw ) {
4244 ResourceLoaderWikiModule
::invalidateModuleCache(
4245 $this, null, null, $dbw->getDomainID() );
4250 $conds = $this->pageCond();
4251 DeferredUpdates
::addUpdate(
4252 new AutoCommitUpdate(
4255 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4256 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4259 [ 'page_touched' => $dbTimestamp ],
4260 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4263 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4266 DeferredUpdates
::PRESEND
4273 * Update page_touched timestamps and send CDN purge messages for
4274 * pages linking to this title. May be sent to the job queue depending
4275 * on the number of links. Typically called on create and delete.
4277 public function touchLinks() {
4279 $jobs[] = HTMLCacheUpdateJob
::newForBacklinks(
4282 [ 'causeAction' => 'page-touch' ]
4284 if ( $this->mNamespace
== NS_CATEGORY
) {
4285 $jobs[] = HTMLCacheUpdateJob
::newForBacklinks(
4288 [ 'causeAction' => 'category-touch' ]
4292 JobQueueGroup
::singleton()->lazyPush( $jobs );
4296 * Get the last touched timestamp
4298 * @param IDatabase|null $db
4299 * @return string|false Last-touched timestamp
4301 public function getTouched( $db = null ) {
4302 if ( $db === null ) {
4303 $db = wfGetDB( DB_REPLICA
);
4305 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4310 * Get the timestamp when this page was updated since the user last saw it.
4312 * @param User|null $user
4313 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4315 public function getNotificationTimestamp( $user = null ) {
4318 // Assume current user if none given
4322 // Check cache first
4323 $uid = $user->getId();
4327 // avoid isset here, as it'll return false for null entries
4328 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4329 return $this->mNotificationTimestamp
[$uid];
4331 // Don't cache too much!
4332 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4333 $this->mNotificationTimestamp
= [];
4336 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4337 $watchedItem = $store->getWatchedItem( $user, $this );
4338 if ( $watchedItem ) {
4339 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4341 $this->mNotificationTimestamp
[$uid] = false;
4344 return $this->mNotificationTimestamp
[$uid];
4348 * Generate strings used for xml 'id' names in monobook tabs
4350 * @param string $prepend Defaults to 'nstab-'
4351 * @return string XML 'id' name
4353 public function getNamespaceKey( $prepend = 'nstab-' ) {
4354 // Gets the subject namespace of this title
4355 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4356 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4357 // Prefer canonical namespace name for HTML IDs
4358 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4359 if ( $namespaceKey === false ) {
4360 // Fallback to localised text
4361 $namespaceKey = $this->getSubjectNsText();
4363 // Makes namespace key lowercase
4364 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4366 if ( $namespaceKey == '' ) {
4367 $namespaceKey = 'main';
4369 // Changes file to image for backwards compatibility
4370 if ( $namespaceKey == 'file' ) {
4371 $namespaceKey = 'image';
4373 return $prepend . $namespaceKey;
4377 * Get all extant redirects to this Title
4379 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4380 * @return Title[] Array of Title redirects to this title
4382 public function getRedirectsHere( $ns = null ) {
4385 $dbr = wfGetDB( DB_REPLICA
);
4387 'rd_namespace' => $this->mNamespace
,
4388 'rd_title' => $this->mDbkeyform
,
4391 if ( $this->isExternal() ) {
4392 $where['rd_interwiki'] = $this->mInterwiki
;
4394 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4396 if ( !is_null( $ns ) ) {
4397 $where['page_namespace'] = $ns;
4400 $res = $dbr->select(
4401 [ 'redirect', 'page' ],
4402 [ 'page_namespace', 'page_title' ],
4407 foreach ( $res as $row ) {
4408 $redirs[] = self
::newFromRow( $row );
4414 * Check if this Title is a valid redirect target
4418 public function isValidRedirectTarget() {
4419 global $wgInvalidRedirectTargets;
4421 if ( $this->isSpecialPage() ) {
4422 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4423 if ( $this->isSpecial( 'Userlogout' ) ) {
4427 foreach ( $wgInvalidRedirectTargets as $target ) {
4428 if ( $this->isSpecial( $target ) ) {
4438 * Get a backlink cache object
4440 * @return BacklinkCache
4442 public function getBacklinkCache() {
4443 return BacklinkCache
::get( $this );
4447 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4451 public function canUseNoindex() {
4452 global $wgExemptFromUserRobotsControl;
4454 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4455 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4457 return !in_array( $this->mNamespace
, $bannedNamespaces );
4461 * Returns the raw sort key to be used for categories, with the specified
4462 * prefix. This will be fed to Collation::getSortKey() to get a
4463 * binary sortkey that can be used for actual sorting.
4465 * @param string $prefix The prefix to be used, specified using
4466 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4470 public function getCategorySortkey( $prefix = '' ) {
4471 $unprefixed = $this->getText();
4473 // Anything that uses this hook should only depend
4474 // on the Title object passed in, and should probably
4475 // tell the users to run updateCollations.php --force
4476 // in order to re-sort existing category relations.
4477 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4478 if ( $prefix !== '' ) {
4479 # Separate with a line feed, so the unprefixed part is only used as
4480 # a tiebreaker when two pages have the exact same prefix.
4481 # In UCA, tab is the only character that can sort above LF
4482 # so we strip both of them from the original prefix.
4483 $prefix = strtr( $prefix, "\n\t", ' ' );
4484 return "$prefix\n$unprefixed";
4490 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4491 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4492 * the db, it will return NULL.
4494 * @return string|null|bool
4496 private function getDbPageLanguageCode() {
4497 global $wgPageLanguageUseDB;
4499 // check, if the page language could be saved in the database, and if so and
4500 // the value is not requested already, lookup the page language using LinkCache
4501 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4502 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4503 $linkCache->addLinkObj( $this );
4504 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4507 return $this->mDbPageLanguage
;
4511 * Get the language in which the content of this page is written in
4512 * wikitext. Defaults to content language, but in certain cases it can be
4513 * e.g. $wgLang (such as special pages, which are in the user language).
4518 public function getPageLanguage() {
4519 global $wgLang, $wgLanguageCode;
4520 if ( $this->isSpecialPage() ) {
4521 // special pages are in the user language
4525 // Checking if DB language is set
4526 $dbPageLanguage = $this->getDbPageLanguageCode();
4527 if ( $dbPageLanguage ) {
4528 return wfGetLangObj( $dbPageLanguage );
4531 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4532 // Note that this may depend on user settings, so the cache should
4533 // be only per-request.
4534 // NOTE: ContentHandler::getPageLanguage() may need to load the
4535 // content to determine the page language!
4536 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4538 $contentHandler = ContentHandler
::getForTitle( $this );
4539 $langObj = $contentHandler->getPageLanguage( $this );
4540 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4542 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4549 * Get the language in which the content of this page is written when
4550 * viewed by user. Defaults to content language, but in certain cases it can be
4551 * e.g. $wgLang (such as special pages, which are in the user language).
4556 public function getPageViewLanguage() {
4559 if ( $this->isSpecialPage() ) {
4560 // If the user chooses a variant, the content is actually
4561 // in a language whose code is the variant code.
4562 $variant = $wgLang->getPreferredVariant();
4563 if ( $wgLang->getCode() !== $variant ) {
4564 return Language
::factory( $variant );
4570 // Checking if DB language is set
4571 $dbPageLanguage = $this->getDbPageLanguageCode();
4572 if ( $dbPageLanguage ) {
4573 $pageLang = wfGetLangObj( $dbPageLanguage );
4574 $variant = $pageLang->getPreferredVariant();
4575 if ( $pageLang->getCode() !== $variant ) {
4576 $pageLang = Language
::factory( $variant );
4582 // @note Can't be cached persistently, depends on user settings.
4583 // @note ContentHandler::getPageViewLanguage() may need to load the
4584 // content to determine the page language!
4585 $contentHandler = ContentHandler
::getForTitle( $this );
4586 $pageLang = $contentHandler->getPageViewLanguage( $this );
4591 * Get a list of rendered edit notices for this page.
4593 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4594 * they will already be wrapped in paragraphs.
4597 * @param int $oldid Revision ID that's being edited
4600 public function getEditNotices( $oldid = 0 ) {
4603 // Optional notice for the entire namespace
4604 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4605 $msg = wfMessage( $editnotice_ns );
4606 if ( $msg->exists() ) {
4607 $html = $msg->parseAsBlock();
4608 // Edit notices may have complex logic, but output nothing (T91715)
4609 if ( trim( $html ) !== '' ) {
4610 $notices[$editnotice_ns] = Html
::rawElement(
4614 'mw-editnotice-namespace',
4615 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4623 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4624 hasSubpages( $this->mNamespace
)
4626 // Optional notice for page itself and any parent page
4627 $editnotice_base = $editnotice_ns;
4628 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4629 $editnotice_base .= '-' . $part;
4630 $msg = wfMessage( $editnotice_base );
4631 if ( $msg->exists() ) {
4632 $html = $msg->parseAsBlock();
4633 if ( trim( $html ) !== '' ) {
4634 $notices[$editnotice_base] = Html
::rawElement(
4638 'mw-editnotice-base',
4639 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4647 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4648 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4649 $msg = wfMessage( $editnoticeText );
4650 if ( $msg->exists() ) {
4651 $html = $msg->parseAsBlock();
4652 if ( trim( $html ) !== '' ) {
4653 $notices[$editnoticeText] = Html
::rawElement(
4657 'mw-editnotice-page',
4658 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4666 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4671 * @param int $flags Bitfield of class READ_* constants
4672 * @return string|bool
4674 private function loadFieldFromDB( $field, $flags ) {
4675 if ( !in_array( $field, self
::getSelectFields(), true ) ) {
4676 return false; // field does not exist
4679 $flags |
= ( $flags & self
::GAID_FOR_UPDATE
) ? self
::READ_LATEST
: 0; // b/c
4680 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
4682 return wfGetDB( $index )->selectField(
4694 public function __sleep() {
4702 'mDefaultNamespace',
4706 public function __wakeup() {
4707 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4708 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4709 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );