3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\Permissions\PermissionManager
;
26 use MediaWiki\Storage\RevisionRecord
;
27 use Wikimedia\Assert\Assert
;
28 use Wikimedia\Rdbms\Database
;
29 use Wikimedia\Rdbms\IDatabase
;
30 use MediaWiki\Linker\LinkTarget
;
31 use MediaWiki\Interwiki\InterwikiLookup
;
32 use MediaWiki\MediaWikiServices
;
35 * Represents a title within MediaWiki.
36 * Optionally may contain an interwiki designation or namespace.
37 * @note This class can fetch various kinds of data from the database;
38 * however, it does so inefficiently.
39 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
40 * and does not rely on global state or the database.
42 class Title
implements LinkTarget
, IDBAccessObject
{
43 /** @var MapCacheLRU|null */
44 private static $titleCache = null;
47 * Title::newFromText maintains a cache to avoid expensive re-normalization of
48 * commonly used titles. On a batch operation this can become a memory leak
49 * if not bounded. After hitting this many titles reset the cache.
51 const CACHE_MAX
= 1000;
54 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
55 * to use the master DB
57 const GAID_FOR_UPDATE
= 1;
60 * Flag for use with factory methods like newFromLinkTarget() that have
61 * a $forceClone parameter. If set, the method must return a new instance.
62 * Without this flag, some factory methods may return existing instances.
66 const NEW_CLONE
= 'clone';
69 * @name Private member variables
70 * Please use the accessor functions instead.
75 /** @var string Text form (spaces not underscores) of the main part */
76 public $mTextform = '';
78 /** @var string URL-encoded form of the main part */
79 public $mUrlform = '';
81 /** @var string Main part with underscores */
82 public $mDbkeyform = '';
84 /** @var string Database key with the initial letter in the case specified by the user */
85 protected $mUserCaseDBKey;
87 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
88 public $mNamespace = NS_MAIN
;
90 /** @var string Interwiki prefix */
91 public $mInterwiki = '';
93 /** @var bool Was this Title created from a string with a local interwiki prefix? */
94 private $mLocalInterwiki = false;
96 /** @var string Title fragment (i.e. the bit after the #) */
97 public $mFragment = '';
99 /** @var int Article ID, fetched from the link cache on demand */
100 public $mArticleID = -1;
102 /** @var bool|int ID of most recent revision */
103 protected $mLatestID = false;
106 * @var bool|string ID of the page's content model, i.e. one of the
107 * CONTENT_MODEL_XXX constants
109 private $mContentModel = false;
112 * @var bool If a content model was forced via setContentModel()
113 * this will be true to avoid having other code paths reset it
115 private $mForcedContentModel = false;
117 /** @var int Estimated number of revisions; null of not loaded */
118 private $mEstimateRevisions;
120 /** @var array Array of groups allowed to edit this article */
121 public $mRestrictions = [];
124 * @var string|bool Comma-separated set of permission keys
125 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
126 * Edit and move sections are separated by a colon
127 * Example: "edit=autoconfirmed,sysop:move=sysop"
129 protected $mOldRestrictions = false;
131 /** @var bool Cascade restrictions on this page to included templates and images? */
132 public $mCascadeRestriction;
134 /** Caching the results of getCascadeProtectionSources */
135 public $mCascadingRestrictions;
137 /** @var array When do the restrictions on this page expire? */
138 protected $mRestrictionsExpiry = [];
140 /** @var bool Are cascading restrictions in effect on this page? */
141 protected $mHasCascadingRestrictions;
143 /** @var array Where are the cascading restrictions coming from on this page? */
144 public $mCascadeSources;
146 /** @var bool Boolean for initialisation on demand */
147 public $mRestrictionsLoaded = false;
150 * Text form including namespace/interwiki, initialised on demand
152 * Only public to share cache with TitleFormatter
157 public $prefixedText = null;
159 /** @var mixed Cached value for getTitleProtection (create protection) */
160 public $mTitleProtection;
163 * @var int Namespace index when there is no namespace. Don't change the
164 * following default, NS_MAIN is hardcoded in several places. See T2696.
165 * Zero except in {{transclusion}} tags.
167 public $mDefaultNamespace = NS_MAIN
;
169 /** @var int The page length, 0 for special pages */
170 protected $mLength = -1;
172 /** @var null Is the article at this title a redirect? */
173 public $mRedirect = null;
175 /** @var array Associative array of user ID -> timestamp/false */
176 private $mNotificationTimestamp = [];
178 /** @var bool Whether a page has any subpages */
179 private $mHasSubpages;
181 /** @var bool The (string) language code of the page's language and content code. */
182 private $mPageLanguage = false;
184 /** @var string|bool|null The page language code from the database, null if not saved in
185 * the database or false if not loaded, yet.
187 private $mDbPageLanguage = false;
189 /** @var TitleValue|null A corresponding TitleValue object */
190 private $mTitleValue = null;
192 /** @var bool|null Would deleting this page be a big deletion? */
193 private $mIsBigDeletion = null;
197 * B/C kludge: provide a TitleParser for use by Title.
198 * Ideally, Title would have no methods that need this.
199 * Avoid usage of this singleton by using TitleValue
200 * and the associated services when possible.
202 * @return TitleFormatter
204 private static function getTitleFormatter() {
205 return MediaWikiServices
::getInstance()->getTitleFormatter();
209 * B/C kludge: provide an InterwikiLookup for use by Title.
210 * Ideally, Title would have no methods that need this.
211 * Avoid usage of this singleton by using TitleValue
212 * and the associated services when possible.
214 * @return InterwikiLookup
216 private static function getInterwikiLookup() {
217 return MediaWikiServices
::getInstance()->getInterwikiLookup();
223 function __construct() {
227 * Create a new Title from a prefixed DB key
229 * @param string $key The database key, which has underscores
230 * instead of spaces, possibly including namespace and
232 * @return Title|null Title, or null on an error
234 public static function newFromDBkey( $key ) {
236 $t->mDbkeyform
= $key;
239 $t->secureAndSplit();
241 } catch ( MalformedTitleException
$ex ) {
247 * Returns a Title given a TitleValue.
248 * If the given TitleValue is already a Title instance, that instance is returned,
249 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
250 * is already a Title instance, that instance is copied using the clone operator.
252 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
254 * @param TitleValue $titleValue Assumed to be safe.
255 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
259 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
260 return self
::newFromLinkTarget( $titleValue, $forceClone );
264 * Returns a Title given a LinkTarget.
265 * If the given LinkTarget is already a Title instance, that instance is returned,
266 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
267 * is already a Title instance, that instance is copied using the clone operator.
269 * @param LinkTarget $linkTarget Assumed to be safe.
270 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
274 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
275 if ( $linkTarget instanceof Title
) {
276 // Special case if it's already a Title object
277 if ( $forceClone === self
::NEW_CLONE
) {
278 return clone $linkTarget;
283 return self
::makeTitle(
284 $linkTarget->getNamespace(),
285 $linkTarget->getText(),
286 $linkTarget->getFragment(),
287 $linkTarget->getInterwiki()
292 * Same as newFromLinkTarget, but if passed null, returns null.
294 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
298 public static function castFromLinkTarget( $linkTarget ) {
299 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
303 * Create a new Title from text, such as what one would find in a link. De-
304 * codes any HTML entities in the text.
306 * Title objects returned by this method are guaranteed to be valid, and
307 * thus return true from the isValid() method.
309 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
310 * It may instead be a cached instance created previously, with references to it remaining
313 * @param string|int|null $text The link text; spaces, prefixes, and an
314 * initial ':' indicating the main namespace are accepted.
315 * @param int $defaultNamespace The namespace to use if none is specified
316 * by a prefix. If you want to force a specific namespace even if
317 * $text might begin with a namespace prefix, use makeTitle() or
319 * @throws InvalidArgumentException
320 * @return Title|null Title or null on an error.
322 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
323 // DWIM: Integers can be passed in here when page titles are used as array keys.
324 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
325 throw new InvalidArgumentException( '$text must be a string.' );
327 if ( $text === null ) {
332 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
333 } catch ( MalformedTitleException
$ex ) {
339 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
340 * rather than returning null.
342 * The exception subclasses encode detailed information about why the title is invalid.
344 * Title objects returned by this method are guaranteed to be valid, and
345 * thus return true from the isValid() method.
347 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
348 * It may instead be a cached instance created previously, with references to it remaining
351 * @see Title::newFromText
354 * @param string $text Title text to check
355 * @param int $defaultNamespace
356 * @throws MalformedTitleException If the title is invalid
359 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
360 if ( is_object( $text ) ) {
361 throw new MWException( '$text must be a string, given an object' );
362 } elseif ( $text === null ) {
363 // Legacy code relies on MalformedTitleException being thrown in this case
364 // (happens when URL with no title in it is parsed). TODO fix
365 throw new MalformedTitleException( 'title-invalid-empty' );
368 $titleCache = self
::getTitleCache();
370 // Wiki pages often contain multiple links to the same page.
371 // Title normalization and parsing can become expensive on pages with many
372 // links, so we can save a little time by caching them.
373 // In theory these are value objects and won't get changed...
374 if ( $defaultNamespace == NS_MAIN
) {
375 $t = $titleCache->get( $text );
381 // Convert things like é ā or 〗 into normalized (T16952) text
382 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
385 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
386 $t->mDefaultNamespace
= (int)$defaultNamespace;
388 $t->secureAndSplit();
389 if ( $defaultNamespace == NS_MAIN
) {
390 $titleCache->set( $text, $t );
396 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
398 * Example of wrong and broken code:
399 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
401 * Example of right code:
402 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
404 * Create a new Title from URL-encoded text. Ensures that
405 * the given title's length does not exceed the maximum.
407 * @param string $url The title, as might be taken from a URL
408 * @return Title|null The new object, or null on an error
410 public static function newFromURL( $url ) {
413 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
414 # but some URLs used it as a space replacement and they still come
415 # from some external search tools.
416 if ( strpos( self
::legalChars(), '+' ) === false ) {
417 $url = strtr( $url, '+', ' ' );
420 $t->mDbkeyform
= strtr( $url, ' ', '_' );
423 $t->secureAndSplit();
425 } catch ( MalformedTitleException
$ex ) {
431 * @return MapCacheLRU
433 private static function getTitleCache() {
434 if ( self
::$titleCache === null ) {
435 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
437 return self
::$titleCache;
441 * Returns a list of fields that are to be selected for initializing Title
442 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
443 * whether to include page_content_model.
447 protected static function getSelectFields() {
448 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
451 'page_namespace', 'page_title', 'page_id',
452 'page_len', 'page_is_redirect', 'page_latest',
455 if ( $wgContentHandlerUseDB ) {
456 $fields[] = 'page_content_model';
459 if ( $wgPageLanguageUseDB ) {
460 $fields[] = 'page_lang';
467 * Create a new Title from an article ID
469 * @param int $id The page_id corresponding to the Title to create
470 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
471 * @return Title|null The new object, or null on an error
473 public static function newFromID( $id, $flags = 0 ) {
474 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
475 $row = $db->selectRow(
477 self
::getSelectFields(),
478 [ 'page_id' => $id ],
481 if ( $row !== false ) {
482 $title = self
::newFromRow( $row );
491 * Make an array of titles from an array of IDs
493 * @param int[] $ids Array of IDs
494 * @return Title[] Array of Titles
496 public static function newFromIDs( $ids ) {
497 if ( !count( $ids ) ) {
500 $dbr = wfGetDB( DB_REPLICA
);
504 self
::getSelectFields(),
505 [ 'page_id' => $ids ],
510 foreach ( $res as $row ) {
511 $titles[] = self
::newFromRow( $row );
517 * Make a Title object from a DB row
519 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
520 * @return Title Corresponding Title
522 public static function newFromRow( $row ) {
523 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
524 $t->loadFromRow( $row );
529 * Load Title object fields from a DB row.
530 * If false is given, the title will be treated as non-existing.
532 * @param stdClass|bool $row Database row
534 public function loadFromRow( $row ) {
535 if ( $row ) { // page found
536 if ( isset( $row->page_id
) ) {
537 $this->mArticleID
= (int)$row->page_id
;
539 if ( isset( $row->page_len
) ) {
540 $this->mLength
= (int)$row->page_len
;
542 if ( isset( $row->page_is_redirect
) ) {
543 $this->mRedirect
= (bool)$row->page_is_redirect
;
545 if ( isset( $row->page_latest
) ) {
546 $this->mLatestID
= (int)$row->page_latest
;
548 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
549 $this->mContentModel
= (string)$row->page_content_model
;
550 } elseif ( !$this->mForcedContentModel
) {
551 $this->mContentModel
= false; # initialized lazily in getContentModel()
553 if ( isset( $row->page_lang
) ) {
554 $this->mDbPageLanguage
= (string)$row->page_lang
;
556 if ( isset( $row->page_restrictions
) ) {
557 $this->mOldRestrictions
= $row->page_restrictions
;
559 } else { // page not found
560 $this->mArticleID
= 0;
562 $this->mRedirect
= false;
563 $this->mLatestID
= 0;
564 if ( !$this->mForcedContentModel
) {
565 $this->mContentModel
= false; # initialized lazily in getContentModel()
571 * Create a new Title from a namespace index and a DB key.
573 * It's assumed that $ns and $title are safe, for instance when
574 * they came directly from the database or a special page name,
575 * not from user input.
577 * No validation is applied. For convenience, spaces are normalized
578 * to underscores, so that e.g. user_text fields can be used directly.
580 * @note This method may return Title objects that are "invalid"
581 * according to the isValid() method. This is usually caused by
582 * configuration changes: e.g. a namespace that was once defined is
583 * no longer configured, or a character that was once allowed in
584 * titles is now forbidden.
586 * @param int $ns The namespace of the article
587 * @param string $title The unprefixed database key form
588 * @param string $fragment The link fragment (after the "#")
589 * @param string $interwiki The interwiki prefix
590 * @return Title The new object
592 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
594 $t->mInterwiki
= $interwiki;
595 $t->mFragment
= $fragment;
596 $t->mNamespace
= $ns = (int)$ns;
597 $t->mDbkeyform
= strtr( $title, ' ', '_' );
598 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
599 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
600 $t->mTextform
= strtr( $title, '_', ' ' );
601 $t->mContentModel
= false; # initialized lazily in getContentModel()
606 * Create a new Title from a namespace index and a DB key.
607 * The parameters will be checked for validity, which is a bit slower
608 * than makeTitle() but safer for user-provided data.
610 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
611 * that is, they return true from the isValid() method. If no valid Title
612 * can be constructed from the input, this method returns null.
614 * @param int $ns The namespace of the article
615 * @param string $title Database key form
616 * @param string $fragment The link fragment (after the "#")
617 * @param string $interwiki Interwiki prefix
618 * @return Title|null The new object, or null on an error
620 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
621 // NOTE: ideally, this would just call makeTitle() and then isValid(),
622 // but presently, that means more overhead on a potential performance hotspot.
624 if ( !MediaWikiServices
::getInstance()->getNamespaceInfo()->exists( $ns ) ) {
629 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
632 $t->secureAndSplit();
634 } catch ( MalformedTitleException
$ex ) {
640 * Create a new Title for the Main Page
642 * This uses the 'mainpage' interface message, which could be specified in
643 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
644 * will use the user language, which would involve initialising the session
645 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
646 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
647 * or ResourceloaderContext) to prevent an error.
649 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
650 * It may instead be a cached instance created previously, with references to it remaining
653 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
656 public static function newMainPage( MessageLocalizer
$localizer = null ) {
658 $msg = $localizer->msg( 'mainpage' );
660 $msg = wfMessage( 'mainpage' );
663 $title = self
::newFromText( $msg->inContentLanguage()->text() );
665 // Every page renders at least one link to the Main Page (e.g. sidebar).
666 // If the localised value is invalid, don't produce fatal errors that
667 // would make the wiki inaccessible (and hard to fix the invalid message).
668 // Gracefully fallback...
670 $title = self
::newFromText( 'Main Page' );
676 * Get the prefixed DB key associated with an ID
678 * @param int $id The page_id of the article
679 * @return Title|null An object representing the article, or null if no such article was found
681 public static function nameOf( $id ) {
682 $dbr = wfGetDB( DB_REPLICA
);
684 $s = $dbr->selectRow(
686 [ 'page_namespace', 'page_title' ],
687 [ 'page_id' => $id ],
690 if ( $s === false ) {
694 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
699 * Get a regex character class describing the legal characters in a link
701 * @return string The list of characters, not delimited
703 public static function legalChars() {
704 global $wgLegalTitleChars;
705 return $wgLegalTitleChars;
709 * Utility method for converting a character sequence from bytes to Unicode.
711 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
712 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
714 * @param string $byteClass
717 public static function convertByteClassToUnicodeClass( $byteClass ) {
718 $length = strlen( $byteClass );
720 $x0 = $x1 = $x2 = '';
722 $d0 = $d1 = $d2 = '';
723 // Decoded integer codepoints
724 $ord0 = $ord1 = $ord2 = 0;
726 $r0 = $r1 = $r2 = '';
730 $allowUnicode = false;
731 for ( $pos = 0; $pos < $length; $pos++
) {
732 // Shift the queues down
741 // Load the current input token and decoded values
742 $inChar = $byteClass[$pos];
743 if ( $inChar == '\\' ) {
744 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
745 $x0 = $inChar . $m[0];
746 $d0 = chr( hexdec( $m[1] ) );
747 $pos +
= strlen( $m[0] );
748 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
749 $x0 = $inChar . $m[0];
750 $d0 = chr( octdec( $m[0] ) );
751 $pos +
= strlen( $m[0] );
752 } elseif ( $pos +
1 >= $length ) {
755 $d0 = $byteClass[$pos +
1];
763 // Load the current re-encoded value
764 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
765 $r0 = sprintf( '\x%02x', $ord0 );
766 } elseif ( $ord0 >= 0x80 ) {
767 // Allow unicode if a single high-bit character appears
768 $r0 = sprintf( '\x%02x', $ord0 );
769 $allowUnicode = true;
770 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
771 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
777 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
779 if ( $ord2 > $ord0 ) {
781 } elseif ( $ord0 >= 0x80 ) {
783 $allowUnicode = true;
784 if ( $ord2 < 0x80 ) {
785 // Keep the non-unicode section of the range
792 // Reset state to the initial value
793 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
794 } elseif ( $ord2 < 0x80 ) {
799 if ( $ord1 < 0x80 ) {
802 if ( $ord0 < 0x80 ) {
805 if ( $allowUnicode ) {
806 $out .= '\u0080-\uFFFF';
812 * Make a prefixed DB key from a DB key and a namespace index
814 * @param int $ns Numerical representation of the namespace
815 * @param string $title The DB key form the title
816 * @param string $fragment The link fragment (after the "#")
817 * @param string $interwiki The interwiki prefix
818 * @param bool $canonicalNamespace If true, use the canonical name for
819 * $ns instead of the localized version.
820 * @return string The prefixed form of the title
822 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
823 $canonicalNamespace = false
825 if ( $canonicalNamespace ) {
826 $namespace = MediaWikiServices
::getInstance()->getNamespaceInfo()->
827 getCanonicalName( $ns );
829 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
831 $name = $namespace == '' ?
$title : "$namespace:$title";
832 if ( strval( $interwiki ) != '' ) {
833 $name = "$interwiki:$name";
835 if ( strval( $fragment ) != '' ) {
836 $name .= '#' . $fragment;
842 * Callback for usort() to do title sorts by (namespace, title)
844 * @param LinkTarget $a
845 * @param LinkTarget $b
847 * @return int Result of string comparison, or namespace comparison
849 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
850 return $a->getNamespace() <=> $b->getNamespace()
851 ?
: strcmp( $a->getText(), $b->getText() );
855 * Returns true if the title is valid, false if it is invalid.
857 * Valid titles can be round-tripped via makeTitle() and newFromText().
858 * Their DB key can be used in the database, though it may not have the correct
861 * Invalid titles may get returned from makeTitle(), and it may be useful to
862 * allow them to exist, e.g. in order to process log entries about pages in
863 * namespaces that belong to extensions that are no longer installed.
865 * @note This method is relatively expensive. When constructing Title
866 * objects that need to be valid, use an instantiator method that is guaranteed
867 * to return valid titles, such as makeTitleSafe() or newFromText().
871 public function isValid() {
872 $services = MediaWikiServices
::getInstance();
873 if ( !$services->getNamespaceInfo()->exists( $this->mNamespace
) ) {
878 $services->getTitleParser()->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
879 } catch ( MalformedTitleException
$ex ) {
884 // Title value applies basic syntax checks. Should perhaps be moved elsewhere.
891 } catch ( InvalidArgumentException
$ex ) {
899 * Determine whether the object refers to a page within
900 * this project (either this wiki or a wiki with a local
901 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
903 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
905 public function isLocal() {
906 if ( $this->isExternal() ) {
907 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
909 return $iw->isLocal();
916 * Is this Title interwiki?
920 public function isExternal() {
921 return $this->mInterwiki
!== '';
925 * Get the interwiki prefix
927 * Use Title::isExternal to check if a interwiki is set
929 * @return string Interwiki prefix
931 public function getInterwiki() {
932 return $this->mInterwiki
;
936 * Was this a local interwiki link?
940 public function wasLocalInterwiki() {
941 return $this->mLocalInterwiki
;
945 * Determine whether the object refers to a page within
946 * this project and is transcludable.
948 * @return bool True if this is transcludable
950 public function isTrans() {
951 if ( !$this->isExternal() ) {
955 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
959 * Returns the DB name of the distant wiki which owns the object.
961 * @return string|false The DB name
963 public function getTransWikiID() {
964 if ( !$this->isExternal() ) {
968 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
972 * Get a TitleValue object representing this Title.
974 * @note Not all valid Titles have a corresponding valid TitleValue
975 * (e.g. TitleValues cannot represent page-local links that have a
976 * fragment but no title text).
978 * @return TitleValue|null
980 public function getTitleValue() {
981 if ( $this->mTitleValue
=== null ) {
983 $this->mTitleValue
= new TitleValue(
989 } catch ( InvalidArgumentException
$ex ) {
990 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
991 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
995 return $this->mTitleValue
;
999 * Get the text form (spaces not underscores) of the main part
1001 * @return string Main part of the title
1003 public function getText() {
1004 return $this->mTextform
;
1008 * Get the URL-encoded form of the main part
1010 * @return string Main part of the title, URL-encoded
1012 public function getPartialURL() {
1013 return $this->mUrlform
;
1017 * Get the main part with underscores
1019 * @return string Main part of the title, with underscores
1021 public function getDBkey() {
1022 return $this->mDbkeyform
;
1026 * Get the DB key with the initial letter case as specified by the user
1027 * @deprecated since 1.33; please use Title::getDBKey() instead
1029 * @return string DB key
1031 function getUserCaseDBKey() {
1032 if ( !is_null( $this->mUserCaseDBKey
) ) {
1033 return $this->mUserCaseDBKey
;
1035 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1036 return $this->mDbkeyform
;
1041 * Get the namespace index, i.e. one of the NS_xxxx constants.
1043 * @return int Namespace index
1045 public function getNamespace() {
1046 return $this->mNamespace
;
1050 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1052 * @todo Deprecate this in favor of SlotRecord::getModel()
1054 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1055 * @return string Content model id
1057 public function getContentModel( $flags = 0 ) {
1058 if ( !$this->mForcedContentModel
1059 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1060 && $this->getArticleID( $flags )
1062 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1063 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1064 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1067 if ( !$this->mContentModel
) {
1068 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1071 return $this->mContentModel
;
1075 * Convenience method for checking a title's content model name
1077 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1078 * @return bool True if $this->getContentModel() == $id
1080 public function hasContentModel( $id ) {
1081 return $this->getContentModel() == $id;
1085 * Set a proposed content model for the page for permissions
1086 * checking. This does not actually change the content model
1089 * Additionally, you should make sure you've checked
1090 * ContentHandler::canBeUsedOn() first.
1093 * @param string $model CONTENT_MODEL_XXX constant
1095 public function setContentModel( $model ) {
1096 $this->mContentModel
= $model;
1097 $this->mForcedContentModel
= true;
1101 * Get the namespace text
1103 * @return string|false Namespace text
1105 public function getNsText() {
1106 if ( $this->isExternal() ) {
1107 // This probably shouldn't even happen, except for interwiki transclusion.
1108 // If possible, use the canonical name for the foreign namespace.
1109 $nsText = MediaWikiServices
::getInstance()->getNamespaceInfo()->
1110 getCanonicalName( $this->mNamespace
);
1111 if ( $nsText !== false ) {
1117 $formatter = self
::getTitleFormatter();
1118 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1119 } catch ( InvalidArgumentException
$ex ) {
1120 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1126 * Get the namespace text of the subject (rather than talk) page
1128 * @return string Namespace text
1130 public function getSubjectNsText() {
1131 $services = MediaWikiServices
::getInstance();
1132 return $services->getContentLanguage()->
1133 getNsText( $services->getNamespaceInfo()->getSubject( $this->mNamespace
) );
1137 * Get the namespace text of the talk page
1139 * @return string Namespace text
1141 public function getTalkNsText() {
1142 $services = MediaWikiServices
::getInstance();
1143 return $services->getContentLanguage()->
1144 getNsText( $services->getNamespaceInfo()->getTalk( $this->mNamespace
) );
1148 * Can this title have a corresponding talk page?
1150 * False for relative section links (with getText() === ''),
1151 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1153 * @see NamespaceInfo::canHaveTalkPage
1156 * @return bool True if this title either is a talk page or can have a talk page associated.
1158 public function canHaveTalkPage() {
1159 return MediaWikiServices
::getInstance()->getNamespaceInfo()->canHaveTalkPage( $this );
1163 * Is this in a namespace that allows actual pages?
1167 public function canExist() {
1168 return $this->mNamespace
>= NS_MAIN
;
1172 * Can this title be added to a user's watchlist?
1174 * False for relative section links (with getText() === ''),
1175 * interwiki links (with getInterwiki() !== ''), and pages in NS_SPECIAL.
1179 public function isWatchable() {
1180 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
1181 return $this->getText() !== '' && !$this->isExternal() &&
1182 $nsInfo->isWatchable( $this->mNamespace
);
1186 * Returns true if this is a special page.
1190 public function isSpecialPage() {
1191 return $this->mNamespace
== NS_SPECIAL
;
1195 * Returns true if this title resolves to the named special page
1197 * @param string $name The special page name
1200 public function isSpecial( $name ) {
1201 if ( $this->isSpecialPage() ) {
1202 list( $thisName, /* $subpage */ ) =
1203 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1204 resolveAlias( $this->mDbkeyform
);
1205 if ( $name == $thisName ) {
1213 * If the Title refers to a special page alias which is not the local default, resolve
1214 * the alias, and localise the name as necessary. Otherwise, return $this
1218 public function fixSpecialName() {
1219 if ( $this->isSpecialPage() ) {
1220 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1221 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1222 if ( $canonicalName ) {
1223 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1224 if ( $localName != $this->mDbkeyform
) {
1225 return self
::makeTitle( NS_SPECIAL
, $localName );
1233 * Returns true if the title is inside the specified namespace.
1235 * Please make use of this instead of comparing to getNamespace()
1236 * This function is much more resistant to changes we may make
1237 * to namespaces than code that makes direct comparisons.
1238 * @param int $ns The namespace
1242 public function inNamespace( $ns ) {
1243 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1244 equals( $this->mNamespace
, $ns );
1248 * Returns true if the title is inside one of the specified namespaces.
1250 * @param int|int[] $namespaces,... The namespaces to check for
1254 public function inNamespaces( /* ... */ ) {
1255 $namespaces = func_get_args();
1256 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1257 $namespaces = $namespaces[0];
1260 foreach ( $namespaces as $ns ) {
1261 if ( $this->inNamespace( $ns ) ) {
1270 * Returns true if the title has the same subject namespace as the
1271 * namespace specified.
1272 * For example this method will take NS_USER and return true if namespace
1273 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1274 * as their subject namespace.
1276 * This is MUCH simpler than individually testing for equivalence
1277 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1282 public function hasSubjectNamespace( $ns ) {
1283 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1284 subjectEquals( $this->mNamespace
, $ns );
1288 * Is this Title in a namespace which contains content?
1289 * In other words, is this a content page, for the purposes of calculating
1294 public function isContentPage() {
1295 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1296 isContent( $this->mNamespace
);
1300 * Would anybody with sufficient privileges be able to move this page?
1301 * Some pages just aren't movable.
1305 public function isMovable() {
1307 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1308 isMovable( $this->mNamespace
) ||
$this->isExternal()
1310 // Interwiki title or immovable namespace. Hooks don't get to override here
1315 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1320 * Is this the mainpage?
1321 * @note Title::newFromText seems to be sufficiently optimized by the title
1322 * cache that we don't need to over-optimize by doing direct comparisons and
1323 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1324 * ends up reporting something differently than $title->isMainPage();
1329 public function isMainPage() {
1330 return $this->equals( self
::newMainPage() );
1334 * Is this a subpage?
1338 public function isSubpage() {
1339 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1340 hasSubpages( $this->mNamespace
)
1341 ?
strpos( $this->getText(), '/' ) !== false
1346 * Is this a conversion table for the LanguageConverter?
1350 public function isConversionTable() {
1351 // @todo ConversionTable should become a separate content model.
1353 return $this->mNamespace
== NS_MEDIAWIKI
&&
1354 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1358 * Does that page contain wikitext, or it is JS, CSS or whatever?
1362 public function isWikitextPage() {
1363 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1367 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1368 * global UI. This is generally true for pages in the MediaWiki namespace having
1369 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1371 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1374 * Note that this method should not return true for pages that contain and show
1375 * "inactive" CSS, JSON, or JS.
1380 public function isSiteConfigPage() {
1382 $this->isSiteCssConfigPage()
1383 ||
$this->isSiteJsonConfigPage()
1384 ||
$this->isSiteJsConfigPage()
1389 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1394 public function isUserConfigPage() {
1396 $this->isUserCssConfigPage()
1397 ||
$this->isUserJsonConfigPage()
1398 ||
$this->isUserJsConfigPage()
1403 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1405 * @return string Containing skin name from .css, .json, or .js subpage title
1408 public function getSkinFromConfigSubpage() {
1409 $subpage = explode( '/', $this->mTextform
);
1410 $subpage = $subpage[count( $subpage ) - 1];
1411 $lastdot = strrpos( $subpage, '.' );
1412 if ( $lastdot === false ) {
1413 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1415 return substr( $subpage, 0, $lastdot );
1419 * Is this a CSS "config" sub-page of a user page?
1424 public function isUserCssConfigPage() {
1426 NS_USER
== $this->mNamespace
1427 && $this->isSubpage()
1428 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1433 * Is this a JSON "config" sub-page of a user page?
1438 public function isUserJsonConfigPage() {
1440 NS_USER
== $this->mNamespace
1441 && $this->isSubpage()
1442 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1447 * Is this a JS "config" sub-page of a user page?
1452 public function isUserJsConfigPage() {
1454 NS_USER
== $this->mNamespace
1455 && $this->isSubpage()
1456 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1461 * Is this a sitewide CSS "config" page?
1466 public function isSiteCssConfigPage() {
1468 NS_MEDIAWIKI
== $this->mNamespace
1470 $this->hasContentModel( CONTENT_MODEL_CSS
)
1471 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1472 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1473 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1479 * Is this a sitewide JSON "config" page?
1484 public function isSiteJsonConfigPage() {
1486 NS_MEDIAWIKI
== $this->mNamespace
1488 $this->hasContentModel( CONTENT_MODEL_JSON
)
1489 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1490 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1491 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1497 * Is this a sitewide JS "config" page?
1502 public function isSiteJsConfigPage() {
1504 NS_MEDIAWIKI
== $this->mNamespace
1506 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1507 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1508 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1509 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1515 * Is this a message which can contain raw HTML?
1520 public function isRawHtmlMessage() {
1521 global $wgRawHtmlMessages;
1523 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1526 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1527 return in_array( $message, $wgRawHtmlMessages, true );
1531 * Is this a talk page of some sort?
1535 public function isTalkPage() {
1536 return MediaWikiServices
::getInstance()->getNamespaceInfo()->
1537 isTalk( $this->mNamespace
);
1541 * Get a Title object associated with the talk page of this article
1543 * @deprecated since 1.34, use getTalkPageIfDefined() or NamespaceInfo::getTalkPage()
1544 * with NamespaceInfo::canHaveTalkPage(). Note that the new method will
1545 * throw if asked for the talk page of a section-only link, or of an interwiki
1547 * @return Title The object for the talk page
1548 * @throws MWException if $target doesn't have talk pages, e.g. because it's in NS_SPECIAL
1549 * or because it's a relative link, or an interwiki link.
1551 public function getTalkPage() {
1552 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1553 // Instead of failing on invalid titles, let's just log the issue for now.
1554 // See the discussion on T227817.
1556 // Is this the same title?
1557 $talkNS = MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalk( $this->mNamespace
);
1558 if ( $this->mNamespace
== $talkNS ) {
1562 $title = self
::makeTitle( $talkNS, $this->mDbkeyform
);
1564 $this->warnIfPageCannotExist( $title, __METHOD__
);
1567 // TODO: replace the above with the code below:
1568 // return self::castFromLinkTarget(
1569 // MediaWikiServices::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1573 * Get a Title object associated with the talk page of this article,
1574 * if such a talk page can exist.
1578 * @return Title|null The object for the talk page,
1579 * or null if no associated talk page can exist, according to canHaveTalkPage().
1581 public function getTalkPageIfDefined() {
1582 if ( !$this->canHaveTalkPage() ) {
1586 return $this->getTalkPage();
1590 * Get a title object associated with the subject page of this
1593 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1594 * @return Title The object for the subject page
1596 public function getSubjectPage() {
1597 // Is this the same title?
1598 $subjectNS = MediaWikiServices
::getInstance()->getNamespaceInfo()
1599 ->getSubject( $this->mNamespace
);
1600 if ( $this->mNamespace
== $subjectNS ) {
1603 // NOTE: The equivalent code in NamespaceInfo is less lenient about producing invalid titles.
1604 // Instead of failing on invalid titles, let's just log the issue for now.
1605 // See the discussion on T227817.
1606 $title = self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1608 $this->warnIfPageCannotExist( $title, __METHOD__
);
1611 // TODO: replace the above with the code below:
1612 // return self::castFromLinkTarget(
1613 // MediaWikiServices::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1617 * @param Title $title
1618 * @param string $method
1620 * @return bool whether a warning was issued
1622 private function warnIfPageCannotExist( Title
$title, $method ) {
1623 if ( $this->getText() == '' ) {
1625 $method . ': called on empty title ' . $this->getFullText() . ', returning '
1626 . $title->getFullText()
1632 if ( $this->getInterwiki() !== '' ) {
1634 $method . ': called on interwiki title ' . $this->getFullText() . ', returning '
1635 . $title->getFullText()
1645 * Get the other title for this page, if this is a subject page
1646 * get the talk page, if it is a subject page get the talk page
1648 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1650 * @throws MWException If the page doesn't have an other page
1653 public function getOtherPage() {
1654 // NOTE: Depend on the methods in this class instead of their equivalent in NamespaceInfo,
1655 // until their semantics has become exactly the same.
1656 // See the discussion on T227817.
1657 if ( $this->isSpecialPage() ) {
1658 throw new MWException( 'Special pages cannot have other pages' );
1660 if ( $this->isTalkPage() ) {
1661 return $this->getSubjectPage();
1663 if ( !$this->canHaveTalkPage() ) {
1664 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1666 return $this->getTalkPage();
1668 // TODO: replace the above with the code below:
1669 // return self::castFromLinkTarget(
1670 // MediaWikiServices::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1674 * Get the default namespace index, for when there is no namespace
1676 * @return int Default namespace index
1678 public function getDefaultNamespace() {
1679 return $this->mDefaultNamespace
;
1683 * Get the Title fragment (i.e.\ the bit after the #) in text form
1685 * Use Title::hasFragment to check for a fragment
1687 * @return string Title fragment
1689 public function getFragment() {
1690 return $this->mFragment
;
1694 * Check if a Title fragment is set
1699 public function hasFragment() {
1700 return $this->mFragment
!== '';
1704 * Get the fragment in URL form, including the "#" character if there is one
1706 * @return string Fragment in URL form
1708 public function getFragmentForURL() {
1709 if ( !$this->hasFragment() ) {
1711 } elseif ( $this->isExternal() ) {
1712 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1713 // so we treat it like a local interwiki.
1714 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1715 if ( $interwiki && !$interwiki->isLocal() ) {
1716 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1720 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1724 * Set the fragment for this title. Removes the first character from the
1725 * specified fragment before setting, so it assumes you're passing it with
1728 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1729 * or Title::createFragmentTarget().
1730 * Still in active use privately.
1733 * @param string $fragment Text
1735 public function setFragment( $fragment ) {
1736 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1740 * Creates a new Title for a different fragment of the same page.
1743 * @param string $fragment
1746 public function createFragmentTarget( $fragment ) {
1747 return self
::makeTitle(
1756 * Prefix some arbitrary text with the namespace or interwiki prefix
1759 * @param string $name The text
1760 * @return string The prefixed text
1762 private function prefix( $name ) {
1764 if ( $this->isExternal() ) {
1765 $p = $this->mInterwiki
. ':';
1768 if ( $this->mNamespace
!= 0 ) {
1769 $nsText = $this->getNsText();
1771 if ( $nsText === false ) {
1772 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1773 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1774 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1777 $p .= $nsText . ':';
1783 * Get the prefixed database key form
1785 * @return string The prefixed title, with underscores and
1786 * any interwiki and namespace prefixes
1788 public function getPrefixedDBkey() {
1789 $s = $this->prefix( $this->mDbkeyform
);
1790 $s = strtr( $s, ' ', '_' );
1795 * Get the prefixed title with spaces.
1796 * This is the form usually used for display
1798 * @return string The prefixed title, with spaces
1800 public function getPrefixedText() {
1801 if ( $this->prefixedText
=== null ) {
1802 $s = $this->prefix( $this->mTextform
);
1803 $s = strtr( $s, '_', ' ' );
1804 $this->prefixedText
= $s;
1806 return $this->prefixedText
;
1810 * Return a string representation of this title
1812 * @return string Representation of this title
1814 public function __toString() {
1815 return $this->getPrefixedText();
1819 * Get the prefixed title with spaces, plus any fragment
1820 * (part beginning with '#')
1822 * @return string The prefixed title, with spaces and the fragment, including '#'
1824 public function getFullText() {
1825 $text = $this->getPrefixedText();
1826 if ( $this->hasFragment() ) {
1827 $text .= '#' . $this->mFragment
;
1833 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1835 * @note the return value may contain trailing whitespace and is thus
1836 * not safe for use with makeTitle or TitleValue.
1840 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1844 * @return string Root name
1847 public function getRootText() {
1849 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1850 hasSubpages( $this->mNamespace
)
1851 ||
strtok( $this->getText(), '/' ) === false
1853 return $this->getText();
1856 return strtok( $this->getText(), '/' );
1860 * Get the root page name title, i.e. the leftmost part before any slashes
1864 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1865 * # returns: Title{User:Foo}
1868 * @return Title Root title
1871 public function getRootTitle() {
1872 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getRootText() );
1873 Assert
::postcondition(
1875 'makeTitleSafe() should always return a Title for the text returned by getRootText().'
1881 * Get the base page name without a namespace, i.e. the part before the subpage name
1883 * @note the return value may contain trailing whitespace and is thus
1884 * not safe for use with makeTitle or TitleValue.
1888 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1889 * # returns: 'Foo/Bar'
1892 * @return string Base name
1894 public function getBaseText() {
1895 $text = $this->getText();
1897 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1898 hasSubpages( $this->mNamespace
)
1903 $lastSlashPos = strrpos( $text, '/' );
1904 // Don't discard the real title if there's no subpage involved
1905 if ( $lastSlashPos === false ) {
1909 return substr( $text, 0, $lastSlashPos );
1913 * Get the base page name title, i.e. the part before the subpage name.
1917 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1918 * # returns: Title{User:Foo/Bar}
1921 * @return Title Base title
1924 public function getBaseTitle() {
1925 $title = self
::makeTitleSafe( $this->mNamespace
, $this->getBaseText() );
1926 Assert
::postcondition(
1928 'makeTitleSafe() should always return a Title for the text returned by getBaseText().'
1934 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1938 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1942 * @return string Subpage name
1944 public function getSubpageText() {
1946 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
1947 hasSubpages( $this->mNamespace
)
1949 return $this->mTextform
;
1951 $parts = explode( '/', $this->mTextform
);
1952 return $parts[count( $parts ) - 1];
1956 * Get the title for a subpage of the current page
1960 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1961 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1964 * @param string $text The subpage name to add to the title
1965 * @return Title|null Subpage title, or null on an error
1968 public function getSubpage( $text ) {
1969 return self
::makeTitleSafe(
1971 $this->getText() . '/' . $text,
1978 * Get a URL-encoded form of the subpage text
1980 * @return string URL-encoded subpage name
1982 public function getSubpageUrlForm() {
1983 $text = $this->getSubpageText();
1984 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1989 * Get a URL-encoded title (not an actual URL) including interwiki
1991 * @return string The URL-encoded form
1993 public function getPrefixedURL() {
1994 $s = $this->prefix( $this->mDbkeyform
);
1995 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
2000 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
2001 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
2002 * second argument named variant. This was deprecated in favor
2003 * of passing an array of option with a "variant" key
2004 * Once $query2 is removed for good, this helper can be dropped
2005 * and the wfArrayToCgi moved to getLocalURL();
2007 * @since 1.19 (r105919)
2008 * @param array|string $query
2009 * @param string|string[]|bool $query2
2012 private static function fixUrlQueryArgs( $query, $query2 = false ) {
2013 if ( $query2 !== false ) {
2014 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
2015 "method called with a second parameter is deprecated. Add your " .
2016 "parameter to an array passed as the first parameter.", "1.19" );
2018 if ( is_array( $query ) ) {
2019 $query = wfArrayToCgi( $query );
2022 if ( is_string( $query2 ) ) {
2023 // $query2 is a string, we will consider this to be
2024 // a deprecated $variant argument and add it to the query
2025 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
2027 $query2 = wfArrayToCgi( $query2 );
2029 // If we have $query content add a & to it first
2033 // Now append the queries together
2040 * Get a real URL referring to this title, with interwiki link and
2043 * @see self::getLocalURL for the arguments.
2045 * @param string|string[] $query
2046 * @param string|string[]|bool $query2
2047 * @param string|int|null $proto Protocol type to use in URL
2048 * @return string The URL
2050 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
2051 $query = self
::fixUrlQueryArgs( $query, $query2 );
2053 # Hand off all the decisions on urls to getLocalURL
2054 $url = $this->getLocalURL( $query );
2056 # Expand the url to make it a full url. Note that getLocalURL has the
2057 # potential to output full urls for a variety of reasons, so we use
2058 # wfExpandUrl instead of simply prepending $wgServer
2059 $url = wfExpandUrl( $url, $proto );
2061 # Finally, add the fragment.
2062 $url .= $this->getFragmentForURL();
2063 // Avoid PHP 7.1 warning from passing $this by reference
2065 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
2070 * Get a url appropriate for making redirects based on an untrusted url arg
2072 * This is basically the same as getFullUrl(), but in the case of external
2073 * interwikis, we send the user to a landing page, to prevent possible
2074 * phishing attacks and the like.
2076 * @note Uses current protocol by default, since technically relative urls
2077 * aren't allowed in redirects per HTTP spec, so this is not suitable for
2078 * places where the url gets cached, as might pollute between
2079 * https and non-https users.
2080 * @see self::getLocalURL for the arguments.
2081 * @param array|string $query
2082 * @param string $proto Protocol type to use in URL
2083 * @return string A url suitable to use in an HTTP location header.
2085 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
2087 if ( $this->isExternal() ) {
2088 $target = SpecialPage
::getTitleFor(
2090 $this->getPrefixedDBkey()
2093 return $target->getFullURL( $query, false, $proto );
2097 * Get a URL with no fragment or server name (relative URL) from a Title object.
2098 * If this page is generated with action=render, however,
2099 * $wgServer is prepended to make an absolute URL.
2101 * @see self::getFullURL to always get an absolute URL.
2102 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
2103 * valid to link, locally, to the current Title.
2104 * @see self::newFromText to produce a Title object.
2106 * @param string|string[] $query An optional query string,
2107 * not used for interwiki links. Can be specified as an associative array as well,
2108 * e.g., [ 'action' => 'edit' ] (keys and values will be URL-escaped).
2109 * Some query patterns will trigger various shorturl path replacements.
2110 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
2111 * be an array. If a string is passed it will be interpreted as a deprecated
2112 * variant argument and urlencoded into a variant= argument.
2113 * This second query argument will be added to the $query
2114 * The second parameter is deprecated since 1.19. Pass it as a key,value
2115 * pair in the first parameter array instead.
2117 * @return string String of the URL.
2119 public function getLocalURL( $query = '', $query2 = false ) {
2120 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
2122 $query = self
::fixUrlQueryArgs( $query, $query2 );
2124 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
2126 $namespace = $this->getNsText();
2127 if ( $namespace != '' ) {
2128 # Can this actually happen? Interwikis shouldn't be parsed.
2129 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
2132 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
2133 $url = wfAppendQuery( $url, $query );
2135 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
2136 if ( $query == '' ) {
2137 $url = str_replace( '$1', $dbkey, $wgArticlePath );
2138 // Avoid PHP 7.1 warning from passing $this by reference
2140 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
2142 global $wgVariantArticlePath, $wgActionPaths;
2146 if ( !empty( $wgActionPaths )
2147 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2149 $action = urldecode( $matches[2] );
2150 if ( isset( $wgActionPaths[$action] ) ) {
2151 $query = $matches[1];
2152 if ( isset( $matches[4] ) ) {
2153 $query .= $matches[4];
2155 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2156 if ( $query != '' ) {
2157 $url = wfAppendQuery( $url, $query );
2163 && $wgVariantArticlePath
2164 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2165 && $this->getPageLanguage()->equals(
2166 MediaWikiServices
::getInstance()->getContentLanguage() )
2167 && $this->getPageLanguage()->hasVariants()
2169 $variant = urldecode( $matches[1] );
2170 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2171 // Only do the variant replacement if the given variant is a valid
2172 // variant for the page's language.
2173 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2174 $url = str_replace( '$1', $dbkey, $url );
2178 if ( $url === false ) {
2179 if ( $query == '-' ) {
2182 $url = "{$wgScript}?title={$dbkey}&{$query}";
2185 // Avoid PHP 7.1 warning from passing $this by reference
2187 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2189 // @todo FIXME: This causes breakage in various places when we
2190 // actually expected a local URL and end up with dupe prefixes.
2191 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2192 $url = $wgServer . $url;
2195 // Avoid PHP 7.1 warning from passing $this by reference
2197 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2202 * Get a URL that's the simplest URL that will be valid to link, locally,
2203 * to the current Title. It includes the fragment, but does not include
2204 * the server unless action=render is used (or the link is external). If
2205 * there's a fragment but the prefixed text is empty, we just return a link
2208 * The result obviously should not be URL-escaped, but does need to be
2209 * HTML-escaped if it's being output in HTML.
2211 * @param string|string[] $query
2212 * @param bool $query2
2213 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2214 * or false (default) for no expansion
2215 * @see self::getLocalURL for the arguments.
2216 * @return string The URL
2218 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2219 if ( $this->isExternal() ||
$proto !== false ) {
2220 $ret = $this->getFullURL( $query, $query2, $proto );
2221 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2222 $ret = $this->getFragmentForURL();
2224 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2230 * Get the URL form for an internal link.
2231 * - Used in various CDN-related code, in case we have a different
2232 * internal hostname for the server from the exposed one.
2234 * This uses $wgInternalServer to qualify the path, or $wgServer
2235 * if $wgInternalServer is not set. If the server variable used is
2236 * protocol-relative, the URL will be expanded to http://
2238 * @see self::getLocalURL for the arguments.
2239 * @param string|string[] $query
2240 * @param string|bool $query2 Deprecated
2241 * @return string The URL
2243 public function getInternalURL( $query = '', $query2 = false ) {
2244 global $wgInternalServer, $wgServer;
2245 $query = self
::fixUrlQueryArgs( $query, $query2 );
2246 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2247 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2248 // Avoid PHP 7.1 warning from passing $this by reference
2250 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2255 * Get the URL for a canonical link, for use in things like IRC and
2256 * e-mail notifications. Uses $wgCanonicalServer and the
2257 * GetCanonicalURL hook.
2259 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2261 * @see self::getLocalURL for the arguments.
2262 * @param string|string[] $query
2263 * @param string|bool $query2 Deprecated
2264 * @return string The URL
2267 public function getCanonicalURL( $query = '', $query2 = false ) {
2268 $query = self
::fixUrlQueryArgs( $query, $query2 );
2269 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2270 // Avoid PHP 7.1 warning from passing $this by reference
2272 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2277 * Get the edit URL for this Title
2279 * @return string The URL, or a null string if this is an interwiki link
2281 public function getEditURL() {
2282 if ( $this->isExternal() ) {
2285 $s = $this->getLocalURL( 'action=edit' );
2291 * Can $user perform $action on this page?
2292 * This skips potentially expensive cascading permission checks
2293 * as well as avoids expensive error formatting
2295 * Suitable for use for nonessential UI controls in common cases, but
2296 * _not_ for functional access control.
2298 * May provide false positives, but should never provide a false negative.
2300 * @param string $action Action that permission needs to be checked for
2301 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2306 * @deprecated since 1.33,
2307 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2310 public function quickUserCan( $action, $user = null ) {
2311 return $this->userCan( $action, $user, false );
2315 * Can $user perform $action on this page?
2317 * @param string $action Action that permission needs to be checked for
2318 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2320 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2325 * @deprecated since 1.33,
2326 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2329 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2330 if ( !$user instanceof User
) {
2335 // TODO: this is for b/c, eventually will be removed
2336 if ( $rigor === true ) {
2337 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2338 } elseif ( $rigor === false ) {
2339 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2342 return MediaWikiServices
::getInstance()->getPermissionManager()
2343 ->userCan( $action, $user, $this, $rigor );
2347 * Can $user perform $action on this page?
2349 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2351 * @param string $action Action that permission needs to be checked for
2352 * @param User $user User to check
2353 * @param string $rigor One of (quick,full,secure)
2354 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2355 * - full : does cheap and expensive checks possibly from a replica DB
2356 * - secure : does cheap and expensive checks, using the master as needed
2357 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2358 * whose corresponding errors may be ignored.
2360 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2363 * @deprecated since 1.33,
2364 * use MediaWikiServices::getInstance()->getPermissionManager()->getPermissionErrors()
2367 public function getUserPermissionsErrors(
2368 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2370 // TODO: this is for b/c, eventually will be removed
2371 if ( $rigor === true ) {
2372 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2373 } elseif ( $rigor === false ) {
2374 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2377 return MediaWikiServices
::getInstance()->getPermissionManager()
2378 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2382 * Get a filtered list of all restriction types supported by this wiki.
2383 * @param bool $exists True to get all restriction types that apply to
2384 * titles that do exist, False for all restriction types that apply to
2385 * titles that do not exist
2388 public static function getFilteredRestrictionTypes( $exists = true ) {
2389 global $wgRestrictionTypes;
2390 $types = $wgRestrictionTypes;
2392 # Remove the create restriction for existing titles
2393 $types = array_diff( $types, [ 'create' ] );
2395 # Only the create and upload restrictions apply to non-existing titles
2396 $types = array_intersect( $types, [ 'create', 'upload' ] );
2402 * Returns restriction types for the current Title
2404 * @return array Applicable restriction types
2406 public function getRestrictionTypes() {
2407 if ( $this->isSpecialPage() ) {
2411 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2413 if ( $this->mNamespace
!= NS_FILE
) {
2414 # Remove the upload restriction for non-file titles
2415 $types = array_diff( $types, [ 'upload' ] );
2418 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2420 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2421 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2427 * Is this title subject to title protection?
2428 * Title protection is the one applied against creation of such title.
2430 * @return array|bool An associative array representing any existent title
2431 * protection, or false if there's none.
2433 public function getTitleProtection() {
2434 $protection = $this->getTitleProtectionInternal();
2435 if ( $protection ) {
2436 if ( $protection['permission'] == 'sysop' ) {
2437 $protection['permission'] = 'editprotected'; // B/C
2439 if ( $protection['permission'] == 'autoconfirmed' ) {
2440 $protection['permission'] = 'editsemiprotected'; // B/C
2447 * Fetch title protection settings
2449 * To work correctly, $this->loadRestrictions() needs to have access to the
2450 * actual protections in the database without munging 'sysop' =>
2451 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2452 * callers probably want $this->getTitleProtection() instead.
2454 * @return array|bool
2456 protected function getTitleProtectionInternal() {
2457 // Can't protect pages in special namespaces
2458 if ( $this->mNamespace
< 0 ) {
2462 // Can't protect pages that exist.
2463 if ( $this->exists() ) {
2467 if ( $this->mTitleProtection
=== null ) {
2468 $dbr = wfGetDB( DB_REPLICA
);
2469 $commentStore = CommentStore
::getStore();
2470 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2471 $res = $dbr->select(
2472 [ 'protected_titles' ] +
$commentQuery['tables'],
2474 'user' => 'pt_user',
2475 'expiry' => 'pt_expiry',
2476 'permission' => 'pt_create_perm'
2477 ] +
$commentQuery['fields'],
2478 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2481 $commentQuery['joins']
2484 // fetchRow returns false if there are no rows.
2485 $row = $dbr->fetchRow( $res );
2487 $this->mTitleProtection
= [
2488 'user' => $row['user'],
2489 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2490 'permission' => $row['permission'],
2491 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2494 $this->mTitleProtection
= false;
2497 return $this->mTitleProtection
;
2501 * Remove any title protection due to page existing
2503 public function deleteTitleProtection() {
2504 $dbw = wfGetDB( DB_MASTER
);
2508 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2511 $this->mTitleProtection
= false;
2515 * Is this page "semi-protected" - the *only* protection levels are listed
2516 * in $wgSemiprotectedRestrictionLevels?
2518 * @param string $action Action to check (default: edit)
2521 public function isSemiProtected( $action = 'edit' ) {
2522 global $wgSemiprotectedRestrictionLevels;
2524 $restrictions = $this->getRestrictions( $action );
2525 $semi = $wgSemiprotectedRestrictionLevels;
2526 if ( !$restrictions ||
!$semi ) {
2527 // Not protected, or all protection is full protection
2531 // Remap autoconfirmed to editsemiprotected for BC
2532 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2533 $semi[$key] = 'editsemiprotected';
2535 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2536 $restrictions[$key] = 'editsemiprotected';
2539 return !array_diff( $restrictions, $semi );
2543 * Does the title correspond to a protected article?
2545 * @param string $action The action the page is protected from,
2546 * by default checks all actions.
2549 public function isProtected( $action = '' ) {
2550 global $wgRestrictionLevels;
2552 $restrictionTypes = $this->getRestrictionTypes();
2554 # Special pages have inherent protection
2555 if ( $this->isSpecialPage() ) {
2559 # Check regular protection levels
2560 foreach ( $restrictionTypes as $type ) {
2561 if ( $action == $type ||
$action == '' ) {
2562 $r = $this->getRestrictions( $type );
2563 foreach ( $wgRestrictionLevels as $level ) {
2564 if ( in_array( $level, $r ) && $level != '' ) {
2575 * Determines if $user is unable to edit this page because it has been protected
2576 * by $wgNamespaceProtection.
2578 * @deprecated since 1.34 Don't use this function in new code.
2579 * @param User $user User object to check permissions
2582 public function isNamespaceProtected( User
$user ) {
2583 global $wgNamespaceProtection;
2585 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2586 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
2587 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2588 if ( !$permissionManager->userHasRight( $user, $right ) ) {
2597 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2599 * @return bool If the page is subject to cascading restrictions.
2601 public function isCascadeProtected() {
2602 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2603 return ( $sources > 0 );
2607 * Determines whether cascading protection sources have already been loaded from
2610 * @param bool $getPages True to check if the pages are loaded, or false to check
2611 * if the status is loaded.
2612 * @return bool Whether or not the specified information has been loaded
2615 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2616 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2620 * Cascading protection: Get the source of any cascading restrictions on this page.
2622 * @param bool $getPages Whether or not to retrieve the actual pages
2623 * that the restrictions have come from and the actual restrictions
2625 * @return array Two elements: First is an array of Title objects of the
2626 * pages from which cascading restrictions have come, false for
2627 * none, or true if such restrictions exist but $getPages was not
2628 * set. Second is an array like that returned by
2629 * Title::getAllRestrictions(), or an empty array if $getPages is
2632 public function getCascadeProtectionSources( $getPages = true ) {
2633 $pagerestrictions = [];
2635 if ( $this->mCascadeSources
!== null && $getPages ) {
2636 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2637 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2638 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2641 $dbr = wfGetDB( DB_REPLICA
);
2643 if ( $this->mNamespace
== NS_FILE
) {
2644 $tables = [ 'imagelinks', 'page_restrictions' ];
2646 'il_to' => $this->mDbkeyform
,
2651 $tables = [ 'templatelinks', 'page_restrictions' ];
2653 'tl_namespace' => $this->mNamespace
,
2654 'tl_title' => $this->mDbkeyform
,
2661 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2662 'pr_expiry', 'pr_type', 'pr_level' ];
2663 $where_clauses[] = 'page_id=pr_page';
2666 $cols = [ 'pr_expiry' ];
2669 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2671 $sources = $getPages ?
[] : false;
2672 $now = wfTimestampNow();
2674 foreach ( $res as $row ) {
2675 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2676 if ( $expiry > $now ) {
2678 $page_id = $row->pr_page
;
2679 $page_ns = $row->page_namespace
;
2680 $page_title = $row->page_title
;
2681 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2682 # Add groups needed for each restriction type if its not already there
2683 # Make sure this restriction type still exists
2685 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2686 $pagerestrictions[$row->pr_type
] = [];
2690 isset( $pagerestrictions[$row->pr_type
] )
2691 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2693 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2702 $this->mCascadeSources
= $sources;
2703 $this->mCascadingRestrictions
= $pagerestrictions;
2705 $this->mHasCascadingRestrictions
= $sources;
2708 return [ $sources, $pagerestrictions ];
2712 * Accessor for mRestrictionsLoaded
2714 * @return bool Whether or not the page's restrictions have already been
2715 * loaded from the database
2718 public function areRestrictionsLoaded() {
2719 return $this->mRestrictionsLoaded
;
2723 * Accessor/initialisation for mRestrictions
2725 * @param string $action Action that permission needs to be checked for
2726 * @return array Restriction levels needed to take the action. All levels are
2727 * required. Note that restriction levels are normally user rights, but 'sysop'
2728 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2729 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2731 public function getRestrictions( $action ) {
2732 if ( !$this->mRestrictionsLoaded
) {
2733 $this->loadRestrictions();
2735 return $this->mRestrictions
[$action] ??
[];
2739 * Accessor/initialisation for mRestrictions
2741 * @return array Keys are actions, values are arrays as returned by
2742 * Title::getRestrictions()
2745 public function getAllRestrictions() {
2746 if ( !$this->mRestrictionsLoaded
) {
2747 $this->loadRestrictions();
2749 return $this->mRestrictions
;
2753 * Get the expiry time for the restriction against a given action
2755 * @param string $action
2756 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2757 * or not protected at all, or false if the action is not recognised.
2759 public function getRestrictionExpiry( $action ) {
2760 if ( !$this->mRestrictionsLoaded
) {
2761 $this->loadRestrictions();
2763 return $this->mRestrictionsExpiry
[$action] ??
false;
2767 * Returns cascading restrictions for the current article
2771 function areRestrictionsCascading() {
2772 if ( !$this->mRestrictionsLoaded
) {
2773 $this->loadRestrictions();
2776 return $this->mCascadeRestriction
;
2780 * Compiles list of active page restrictions from both page table (pre 1.10)
2781 * and page_restrictions table for this existing page.
2782 * Public for usage by LiquidThreads.
2784 * @param array $rows Array of db result objects
2785 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2786 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2787 * Edit and move sections are separated by a colon
2788 * Example: "edit=autoconfirmed,sysop:move=sysop"
2790 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2791 // This function will only read rows from a table that we migrated away
2792 // from before adding READ_LATEST support to loadRestrictions, so we
2793 // don't need to support reading from DB_MASTER here.
2794 $dbr = wfGetDB( DB_REPLICA
);
2796 $restrictionTypes = $this->getRestrictionTypes();
2798 foreach ( $restrictionTypes as $type ) {
2799 $this->mRestrictions
[$type] = [];
2800 $this->mRestrictionsExpiry
[$type] = 'infinity';
2803 $this->mCascadeRestriction
= false;
2805 # Backwards-compatibility: also load the restrictions from the page record (old format).
2806 if ( $oldFashionedRestrictions !== null ) {
2807 $this->mOldRestrictions
= $oldFashionedRestrictions;
2810 if ( $this->mOldRestrictions
=== false ) {
2811 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2812 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2813 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2816 if ( $this->mOldRestrictions
!= '' ) {
2817 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2818 $temp = explode( '=', trim( $restrict ) );
2819 if ( count( $temp ) == 1 ) {
2820 // old old format should be treated as edit/move restriction
2821 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2822 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2824 $restriction = trim( $temp[1] );
2825 if ( $restriction != '' ) { // some old entries are empty
2826 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2832 if ( count( $rows ) ) {
2833 # Current system - load second to make them override.
2834 $now = wfTimestampNow();
2836 # Cycle through all the restrictions.
2837 foreach ( $rows as $row ) {
2838 // Don't take care of restrictions types that aren't allowed
2839 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2843 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2845 // Only apply the restrictions if they haven't expired!
2846 if ( !$expiry ||
$expiry > $now ) {
2847 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2848 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2850 $this->mCascadeRestriction |
= $row->pr_cascade
;
2855 $this->mRestrictionsLoaded
= true;
2859 * Load restrictions from the page_restrictions table
2861 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2862 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2863 * Edit and move sections are separated by a colon
2864 * Example: "edit=autoconfirmed,sysop:move=sysop"
2865 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2866 * from the master DB.
2868 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2869 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2870 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2874 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2875 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2876 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2877 $id = $this->getArticleID();
2879 $fname = __METHOD__
;
2880 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2881 return iterator_to_array(
2883 'page_restrictions',
2884 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2885 [ 'pr_page' => $id ],
2891 if ( $readLatest ) {
2892 $dbr = wfGetDB( DB_MASTER
);
2893 $rows = $loadRestrictionsFromDb( $dbr );
2895 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2896 $rows = $cache->getWithSetCallback(
2897 // Page protections always leave a new null revision
2898 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2900 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2901 $dbr = wfGetDB( DB_REPLICA
);
2903 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2904 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2905 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2906 // @TODO: cleanup Title cache and caller assumption mess in general
2907 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2910 return $loadRestrictionsFromDb( $dbr );
2915 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2917 $title_protection = $this->getTitleProtectionInternal();
2919 if ( $title_protection ) {
2920 $now = wfTimestampNow();
2921 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2923 if ( !$expiry ||
$expiry > $now ) {
2924 // Apply the restrictions
2925 $this->mRestrictionsExpiry
['create'] = $expiry;
2926 $this->mRestrictions
['create'] =
2927 explode( ',', trim( $title_protection['permission'] ) );
2928 } else { // Get rid of the old restrictions
2929 $this->mTitleProtection
= false;
2932 $this->mRestrictionsExpiry
['create'] = 'infinity';
2934 $this->mRestrictionsLoaded
= true;
2939 * Flush the protection cache in this object and force reload from the database.
2940 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2942 public function flushRestrictions() {
2943 $this->mRestrictionsLoaded
= false;
2944 $this->mTitleProtection
= null;
2948 * Purge expired restrictions from the page_restrictions table
2950 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2952 static function purgeExpiredRestrictions() {
2953 if ( wfReadOnly() ) {
2957 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2958 wfGetDB( DB_MASTER
),
2960 function ( IDatabase
$dbw, $fname ) {
2961 $config = MediaWikiServices
::getInstance()->getMainConfig();
2962 $ids = $dbw->selectFieldValues(
2963 'page_restrictions',
2965 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2967 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2970 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2975 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2976 wfGetDB( DB_MASTER
),
2978 function ( IDatabase
$dbw, $fname ) {
2981 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2989 * Does this have subpages? (Warning, usually requires an extra DB query.)
2993 public function hasSubpages() {
2995 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
2996 hasSubpages( $this->mNamespace
)
3002 # We dynamically add a member variable for the purpose of this method
3003 # alone to cache the result. There's no point in having it hanging
3004 # around uninitialized in every Title object; therefore we only add it
3005 # if needed and don't declare it statically.
3006 if ( $this->mHasSubpages
=== null ) {
3007 $this->mHasSubpages
= false;
3008 $subpages = $this->getSubpages( 1 );
3009 if ( $subpages instanceof TitleArray
) {
3010 $this->mHasSubpages
= (bool)$subpages->current();
3014 return $this->mHasSubpages
;
3018 * Get all subpages of this page.
3020 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3021 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3022 * doesn't allow subpages
3024 public function getSubpages( $limit = -1 ) {
3026 !MediaWikiServices
::getInstance()->getNamespaceInfo()->
3027 hasSubpages( $this->mNamespace
)
3032 $dbr = wfGetDB( DB_REPLICA
);
3033 $conds['page_namespace'] = $this->mNamespace
;
3034 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
3036 if ( $limit > -1 ) {
3037 $options['LIMIT'] = $limit;
3039 return TitleArray
::newFromResult(
3040 $dbr->select( 'page',
3041 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3050 * Is there a version of this page in the deletion archive?
3052 * @return int The number of archived revisions
3054 public function isDeleted() {
3055 if ( $this->mNamespace
< 0 ) {
3058 $dbr = wfGetDB( DB_REPLICA
);
3060 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3061 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3064 if ( $this->mNamespace
== NS_FILE
) {
3065 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3066 [ 'fa_name' => $this->mDbkeyform
],
3075 * Is there a version of this page in the deletion archive?
3079 public function isDeletedQuick() {
3080 if ( $this->mNamespace
< 0 ) {
3083 $dbr = wfGetDB( DB_REPLICA
);
3084 $deleted = (bool)$dbr->selectField( 'archive', '1',
3085 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
3088 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
3089 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3090 [ 'fa_name' => $this->mDbkeyform
],
3098 * Get the article ID for this Title from the link cache,
3099 * adding it if necessary
3101 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3103 * @return int The ID
3105 public function getArticleID( $flags = 0 ) {
3106 if ( $this->mNamespace
< 0 ) {
3107 $this->mArticleID
= 0;
3108 return $this->mArticleID
;
3110 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3111 if ( $flags & self
::GAID_FOR_UPDATE
) {
3112 $oldUpdate = $linkCache->forUpdate( true );
3113 $linkCache->clearLink( $this );
3114 $this->mArticleID
= $linkCache->addLinkObj( $this );
3115 $linkCache->forUpdate( $oldUpdate );
3116 } elseif ( $this->mArticleID
== -1 ) {
3117 $this->mArticleID
= $linkCache->addLinkObj( $this );
3119 return $this->mArticleID
;
3123 * Is this an article that is a redirect page?
3124 * Uses link cache, adding it if necessary
3126 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3129 public function isRedirect( $flags = 0 ) {
3130 if ( !is_null( $this->mRedirect
) ) {
3131 return $this->mRedirect
;
3133 if ( !$this->getArticleID( $flags ) ) {
3134 $this->mRedirect
= false;
3135 return $this->mRedirect
;
3138 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3139 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3140 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3141 if ( $cached === null ) {
3142 # Trust LinkCache's state over our own
3143 # LinkCache is telling us that the page doesn't exist, despite there being cached
3144 # data relating to an existing page in $this->mArticleID. Updaters should clear
3145 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3146 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3147 # LinkCache to refresh its data from the master.
3148 $this->mRedirect
= false;
3149 return $this->mRedirect
;
3152 $this->mRedirect
= (bool)$cached;
3154 return $this->mRedirect
;
3158 * What is the length of this page?
3159 * Uses link cache, adding it if necessary
3161 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3164 public function getLength( $flags = 0 ) {
3165 if ( $this->mLength
!= -1 ) {
3166 return $this->mLength
;
3168 if ( !$this->getArticleID( $flags ) ) {
3170 return $this->mLength
;
3172 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3173 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3174 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3175 if ( $cached === null ) {
3176 # Trust LinkCache's state over our own, as for isRedirect()
3178 return $this->mLength
;
3181 $this->mLength
= intval( $cached );
3183 return $this->mLength
;
3187 * What is the page_latest field for this page?
3189 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3190 * @return int Int or 0 if the page doesn't exist
3192 public function getLatestRevID( $flags = 0 ) {
3193 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3194 return intval( $this->mLatestID
);
3196 if ( !$this->getArticleID( $flags ) ) {
3197 $this->mLatestID
= 0;
3198 return $this->mLatestID
;
3200 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3201 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3202 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3203 if ( $cached === null ) {
3204 # Trust LinkCache's state over our own, as for isRedirect()
3205 $this->mLatestID
= 0;
3206 return $this->mLatestID
;
3209 $this->mLatestID
= intval( $cached );
3211 return $this->mLatestID
;
3215 * This clears some fields in this object, and clears any associated
3216 * keys in the "bad links" section of the link cache.
3218 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3219 * loading of the new page_id. It's also called from
3220 * WikiPage::doDeleteArticleReal()
3222 * @param int $newid The new Article ID
3224 public function resetArticleID( $newid ) {
3225 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3226 $linkCache->clearLink( $this );
3228 if ( $newid === false ) {
3229 $this->mArticleID
= -1;
3231 $this->mArticleID
= intval( $newid );
3233 $this->mRestrictionsLoaded
= false;
3234 $this->mRestrictions
= [];
3235 $this->mOldRestrictions
= false;
3236 $this->mRedirect
= null;
3237 $this->mLength
= -1;
3238 $this->mLatestID
= false;
3239 $this->mContentModel
= false;
3240 $this->mEstimateRevisions
= null;
3241 $this->mPageLanguage
= false;
3242 $this->mDbPageLanguage
= false;
3243 $this->mIsBigDeletion
= null;
3246 public static function clearCaches() {
3247 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3248 $linkCache->clear();
3250 $titleCache = self
::getTitleCache();
3251 $titleCache->clear();
3255 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3257 * @param string $text Containing title to capitalize
3258 * @param int $ns Namespace index, defaults to NS_MAIN
3259 * @return string Containing capitalized title
3261 public static function capitalize( $text, $ns = NS_MAIN
) {
3262 $services = MediaWikiServices
::getInstance();
3263 if ( $services->getNamespaceInfo()->isCapitalized( $ns ) ) {
3264 return $services->getContentLanguage()->ucfirst( $text );
3271 * Secure and split - main initialisation function for this object
3273 * Assumes that mDbkeyform has been set, and is urldecoded
3274 * and uses underscores, but not otherwise munged. This function
3275 * removes illegal characters, splits off the interwiki and
3276 * namespace prefixes, sets the other forms, and canonicalizes
3279 * @throws MalformedTitleException On invalid titles
3280 * @return bool True on success
3282 private function secureAndSplit() {
3283 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3284 // the parsing code with Title, while avoiding massive refactoring.
3285 // @todo: get rid of secureAndSplit, refactor parsing code.
3286 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3287 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3288 /** @var MediaWikiTitleCodec $titleCodec */
3289 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3290 // MalformedTitleException can be thrown here
3291 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3294 $this->setFragment( '#' . $parts['fragment'] );
3295 $this->mInterwiki
= $parts['interwiki'];
3296 $this->mLocalInterwiki
= $parts['local_interwiki'];
3297 $this->mNamespace
= $parts['namespace'];
3298 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3300 $this->mDbkeyform
= $parts['dbkey'];
3301 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3302 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3304 # We already know that some pages won't be in the database!
3305 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3306 $this->mArticleID
= 0;
3313 * Get an array of Title objects linking to this Title
3314 * Also stores the IDs in the link cache.
3316 * WARNING: do not use this function on arbitrary user-supplied titles!
3317 * On heavily-used templates it will max out the memory.
3319 * @param array $options May be FOR UPDATE
3320 * @param string $table Table name
3321 * @param string $prefix Fields prefix
3322 * @return Title[] Array of Title objects linking here
3324 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3325 if ( count( $options ) > 0 ) {
3326 $db = wfGetDB( DB_MASTER
);
3328 $db = wfGetDB( DB_REPLICA
);
3333 self
::getSelectFields(),
3335 "{$prefix}_from=page_id",
3336 "{$prefix}_namespace" => $this->mNamespace
,
3337 "{$prefix}_title" => $this->mDbkeyform
],
3343 if ( $res->numRows() ) {
3344 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3345 foreach ( $res as $row ) {
3346 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3348 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3349 $retVal[] = $titleObj;
3357 * Get an array of Title objects using this Title as a template
3358 * Also stores the IDs in the link cache.
3360 * WARNING: do not use this function on arbitrary user-supplied titles!
3361 * On heavily-used templates it will max out the memory.
3363 * @param array $options Query option to Database::select()
3364 * @return Title[] Array of Title the Title objects linking here
3366 public function getTemplateLinksTo( $options = [] ) {
3367 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3371 * Get an array of Title objects linked from this Title
3372 * Also stores the IDs in the link cache.
3374 * WARNING: do not use this function on arbitrary user-supplied titles!
3375 * On heavily-used templates it will max out the memory.
3377 * @param array $options Query option to Database::select()
3378 * @param string $table Table name
3379 * @param string $prefix Fields prefix
3380 * @return array Array of Title objects linking here
3382 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3383 $id = $this->getArticleID();
3385 # If the page doesn't exist; there can't be any link from this page
3390 $db = wfGetDB( DB_REPLICA
);
3392 $blNamespace = "{$prefix}_namespace";
3393 $blTitle = "{$prefix}_title";
3395 $pageQuery = WikiPage
::getQueryInfo();
3397 [ $table, 'nestpage' => $pageQuery['tables'] ],
3399 [ $blNamespace, $blTitle ],
3400 $pageQuery['fields']
3402 [ "{$prefix}_from" => $id ],
3407 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3408 ] ] +
$pageQuery['joins']
3412 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3413 foreach ( $res as $row ) {
3414 if ( $row->page_id
) {
3415 $titleObj = self
::newFromRow( $row );
3417 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3418 $linkCache->addBadLinkObj( $titleObj );
3420 $retVal[] = $titleObj;
3427 * Get an array of Title objects used on this Title as a template
3428 * Also stores the IDs in the link cache.
3430 * WARNING: do not use this function on arbitrary user-supplied titles!
3431 * On heavily-used templates it will max out the memory.
3433 * @param array $options May be FOR UPDATE
3434 * @return Title[] Array of Title the Title objects used here
3436 public function getTemplateLinksFrom( $options = [] ) {
3437 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3441 * Get an array of Title objects referring to non-existent articles linked
3444 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3445 * should use redirect table in this case).
3446 * @return Title[] Array of Title the Title objects
3448 public function getBrokenLinksFrom() {
3449 if ( $this->getArticleID() == 0 ) {
3450 # All links from article ID 0 are false positives
3454 $dbr = wfGetDB( DB_REPLICA
);
3455 $res = $dbr->select(
3456 [ 'page', 'pagelinks' ],
3457 [ 'pl_namespace', 'pl_title' ],
3459 'pl_from' => $this->getArticleID(),
3460 'page_namespace IS NULL'
3466 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3472 foreach ( $res as $row ) {
3473 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3479 * Get a list of URLs to purge from the CDN cache when this
3482 * @return string[] Array of String the URLs
3484 public function getCdnUrls() {
3486 $this->getInternalURL(),
3487 $this->getInternalURL( 'action=history' )
3490 $pageLang = $this->getPageLanguage();
3491 if ( $pageLang->hasVariants() ) {
3492 $variants = $pageLang->getVariants();
3493 foreach ( $variants as $vCode ) {
3494 $urls[] = $this->getInternalURL( $vCode );
3498 // If we are looking at a css/js user subpage, purge the action=raw.
3499 if ( $this->isUserJsConfigPage() ) {
3500 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3501 } elseif ( $this->isUserJsonConfigPage() ) {
3502 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3503 } elseif ( $this->isUserCssConfigPage() ) {
3504 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3507 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3512 * Purge all applicable CDN URLs
3514 public function purgeSquid() {
3515 DeferredUpdates
::addUpdate(
3516 new CdnCacheUpdate( $this->getCdnUrls() ),
3517 DeferredUpdates
::PRESEND
3522 * Check whether a given move operation would be valid.
3523 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3525 * @deprecated since 1.25, use MovePage's methods instead
3526 * @param Title &$nt The new title
3527 * @param bool $auth Whether to check user permissions (uses $wgUser)
3528 * @param string $reason Is the log summary of the move, used for spam checking
3529 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3531 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3532 wfDeprecated( __METHOD__
, '1.25' );
3536 if ( !( $nt instanceof Title
) ) {
3537 // Normally we'd add this to $errors, but we'll get
3538 // lots of syntax errors if $nt is not an object
3539 return [ [ 'badtitletext' ] ];
3542 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3543 $errors = $mp->isValidMove()->getErrorsArray();
3545 $errors = wfMergeErrorArrays(
3547 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3551 return $errors ?
: true;
3555 * Move a title to a new location
3557 * @deprecated since 1.25, use the MovePage class instead
3558 * @param Title &$nt The new title
3559 * @param bool $auth Indicates whether $wgUser's permissions
3561 * @param string $reason The reason for the move
3562 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3563 * Ignored if the user doesn't have the suppressredirect right.
3564 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3565 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3567 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3568 array $changeTags = []
3570 wfDeprecated( __METHOD__
, '1.25' );
3574 $mp = MediaWikiServices
::getInstance()->getMovePageFactory()->newMovePage( $this, $nt );
3575 $method = $auth ?
'moveIfAllowed' : 'move';
3576 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3577 if ( $status->isOK() ) {
3580 return $status->getErrorsArray();
3585 * Move this page's subpages to be subpages of $nt
3587 * @deprecated since 1.34, use MovePage instead
3588 * @param Title $nt Move target
3589 * @param bool $auth Whether $wgUser's permissions should be checked
3590 * @param string $reason The reason for the move
3591 * @param bool $createRedirect Whether to create redirects from the old subpages to
3592 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3593 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3594 * @return array Array with old page titles as keys, and strings (new page titles) or
3595 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3596 * getUserPermissionsErrors()-like error array with numeric indices if
3597 * no pages were moved
3599 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3600 array $changeTags = []
3602 wfDeprecated( __METHOD__
, '1.34' );
3606 $mp = new MovePage( $this, $nt );
3607 $method = $auth ?
'moveSubpagesIfAllowed' : 'moveSubpages';
3608 $result = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3610 if ( !$result->isOk() ) {
3611 return $result->getErrorsArray();
3615 foreach ( $result->getValue() as $key => $status ) {
3616 if ( $status->isOK() ) {
3617 $retval[$key] = $status->getValue();
3619 $retval[$key] = $status->getErrorsArray();
3626 * Checks if this page is just a one-rev redirect.
3627 * Adds lock, so don't use just for light purposes.
3631 public function isSingleRevRedirect() {
3632 global $wgContentHandlerUseDB;
3634 $dbw = wfGetDB( DB_MASTER
);
3637 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3638 if ( $wgContentHandlerUseDB ) {
3639 $fields[] = 'page_content_model';
3642 $row = $dbw->selectRow( 'page',
3648 # Cache some fields we may want
3649 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3650 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3651 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3652 $this->mContentModel
= $row && isset( $row->page_content_model
)
3653 ?
strval( $row->page_content_model
)
3656 if ( !$this->mRedirect
) {
3659 # Does the article have a history?
3660 $row = $dbw->selectField( [ 'page', 'revision' ],
3662 [ 'page_namespace' => $this->mNamespace
,
3663 'page_title' => $this->mDbkeyform
,
3665 'page_latest != rev_id'
3670 # Return true if there was no history
3671 return ( $row === false );
3675 * Checks if $this can be moved to a given Title
3676 * - Selects for update, so don't call it unless you mean business
3678 * @deprecated since 1.25, use MovePage's methods instead
3679 * @param Title $nt The new title to check
3682 public function isValidMoveTarget( $nt ) {
3683 wfDeprecated( __METHOD__
, '1.25' );
3685 # Is it an existing file?
3686 if ( $nt->getNamespace() == NS_FILE
) {
3687 $file = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
3689 $file->load( File
::READ_LATEST
);
3690 if ( $file->exists() ) {
3691 wfDebug( __METHOD__
. ": file exists\n" );
3695 # Is it a redirect with no history?
3696 if ( !$nt->isSingleRevRedirect() ) {
3697 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3700 # Get the article text
3701 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3702 if ( !is_object( $rev ) ) {
3705 $content = $rev->getContent();
3706 # Does the redirect point to the source?
3707 # Or is it a broken self-redirect, usually caused by namespace collisions?
3708 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3710 if ( $redirTitle ) {
3711 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3712 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3713 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3719 # Fail safe (not a redirect after all. strange.)
3720 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3721 " is a redirect, but it doesn't contain a valid redirect.\n" );
3727 * Get categories to which this Title belongs and return an array of
3728 * categories' names.
3730 * @return array Array of parents in the form:
3731 * $parent => $currentarticle
3733 public function getParentCategories() {
3736 $titleKey = $this->getArticleID();
3738 if ( $titleKey === 0 ) {
3742 $dbr = wfGetDB( DB_REPLICA
);
3744 $res = $dbr->select(
3747 [ 'cl_from' => $titleKey ],
3751 if ( $res->numRows() > 0 ) {
3752 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3753 foreach ( $res as $row ) {
3754 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3755 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3756 $this->getFullText();
3763 * Get a tree of parent categories
3765 * @param array $children Array with the children in the keys, to check for circular refs
3766 * @return array Tree of parent categories
3768 public function getParentCategoryTree( $children = [] ) {
3770 $parents = $this->getParentCategories();
3773 foreach ( $parents as $parent => $current ) {
3774 if ( array_key_exists( $parent, $children ) ) {
3775 # Circular reference
3776 $stack[$parent] = [];
3778 $nt = self
::newFromText( $parent );
3780 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3790 * Get an associative array for selecting this title from
3793 * @return array Array suitable for the $where parameter of DB::select()
3795 public function pageCond() {
3796 if ( $this->mArticleID
> 0 ) {
3797 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3798 return [ 'page_id' => $this->mArticleID
];
3800 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3805 * Get next/previous revision ID relative to another revision ID
3806 * @param int $revId Revision ID. Get the revision that was before this one.
3807 * @param int $flags Title::GAID_FOR_UPDATE
3808 * @param string $dir 'next' or 'prev'
3809 * @return int|bool New revision ID, or false if none exists
3811 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3812 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3813 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3814 $rev = $rl->getRevisionById( $revId, $rlFlags );
3818 $oldRev = $dir === 'next'
3819 ?
$rl->getNextRevision( $rev, $rlFlags )
3820 : $rl->getPreviousRevision( $rev, $rlFlags );
3824 return $oldRev->getId();
3828 * Get the revision ID of the previous revision
3830 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3831 * @param int $revId Revision ID. Get the revision that was before this one.
3832 * @param int $flags Title::GAID_FOR_UPDATE
3833 * @return int|bool Old revision ID, or false if none exists
3835 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3836 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3840 * Get the revision ID of the next revision
3842 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3843 * @param int $revId Revision ID. Get the revision that was after this one.
3844 * @param int $flags Title::GAID_FOR_UPDATE
3845 * @return int|bool Next revision ID, or false if none exists
3847 public function getNextRevisionID( $revId, $flags = 0 ) {
3848 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3852 * Get the first revision of the page
3854 * @param int $flags Title::GAID_FOR_UPDATE
3855 * @return Revision|null If page doesn't exist
3857 public function getFirstRevision( $flags = 0 ) {
3858 $pageId = $this->getArticleID( $flags );
3860 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3861 $revQuery = Revision
::getQueryInfo();
3862 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3863 [ 'rev_page' => $pageId ],
3866 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3867 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3872 return new Revision( $row, 0, $this );
3879 * Get the oldest revision timestamp of this page
3881 * @param int $flags Title::GAID_FOR_UPDATE
3882 * @return string|null MW timestamp
3884 public function getEarliestRevTime( $flags = 0 ) {
3885 $rev = $this->getFirstRevision( $flags );
3886 return $rev ?
$rev->getTimestamp() : null;
3890 * Check if this is a new page
3894 public function isNewPage() {
3895 $dbr = wfGetDB( DB_REPLICA
);
3896 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3900 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3904 public function isBigDeletion() {
3905 global $wgDeleteRevisionsLimit;
3907 if ( !$wgDeleteRevisionsLimit ) {
3911 if ( $this->mIsBigDeletion
=== null ) {
3912 $dbr = wfGetDB( DB_REPLICA
);
3914 $revCount = $dbr->selectRowCount(
3917 [ 'rev_page' => $this->getArticleID() ],
3919 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3922 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3925 return $this->mIsBigDeletion
;
3929 * Get the approximate revision count of this page.
3933 public function estimateRevisionCount() {
3934 if ( !$this->exists() ) {
3938 if ( $this->mEstimateRevisions
=== null ) {
3939 $dbr = wfGetDB( DB_REPLICA
);
3940 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3941 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3944 return $this->mEstimateRevisions
;
3948 * Get the number of revisions between the given revision.
3949 * Used for diffs and other things that really need it.
3951 * @param int|Revision $old Old revision or rev ID (first before range)
3952 * @param int|Revision $new New revision or rev ID (first after range)
3953 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3954 * @return int Number of revisions between these revisions.
3956 public function countRevisionsBetween( $old, $new, $max = null ) {
3957 if ( !( $old instanceof Revision
) ) {
3958 $old = Revision
::newFromTitle( $this, (int)$old );
3960 if ( !( $new instanceof Revision
) ) {
3961 $new = Revision
::newFromTitle( $this, (int)$new );
3963 if ( !$old ||
!$new ) {
3964 return 0; // nothing to compare
3966 $dbr = wfGetDB( DB_REPLICA
);
3968 'rev_page' => $this->getArticleID(),
3969 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3970 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3972 if ( $max !== null ) {
3973 return $dbr->selectRowCount( 'revision', '1',
3976 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3979 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3984 * Get the authors between the given revisions or revision IDs.
3985 * Used for diffs and other things that really need it.
3989 * @param int|Revision $old Old revision or rev ID (first before range by default)
3990 * @param int|Revision $new New revision or rev ID (first after range by default)
3991 * @param int $limit Maximum number of authors
3992 * @param string|array $options (Optional): Single option, or an array of options:
3993 * 'include_old' Include $old in the range; $new is excluded.
3994 * 'include_new' Include $new in the range; $old is excluded.
3995 * 'include_both' Include both $old and $new in the range.
3996 * Unknown option values are ignored.
3997 * @return array|null Names of revision authors in the range; null if not both revisions exist
3999 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4000 if ( !( $old instanceof Revision
) ) {
4001 $old = Revision
::newFromTitle( $this, (int)$old );
4003 if ( !( $new instanceof Revision
) ) {
4004 $new = Revision
::newFromTitle( $this, (int)$new );
4006 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4007 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4008 // in the sanity check below?
4009 if ( !$old ||
!$new ) {
4010 return null; // nothing to compare
4015 $options = (array)$options;
4016 if ( in_array( 'include_old', $options ) ) {
4019 if ( in_array( 'include_new', $options ) ) {
4022 if ( in_array( 'include_both', $options ) ) {
4026 // No DB query needed if $old and $new are the same or successive revisions:
4027 if ( $old->getId() === $new->getId() ) {
4028 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4030 [ $old->getUserText( RevisionRecord
::RAW
) ];
4031 } elseif ( $old->getId() === $new->getParentId() ) {
4032 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4033 $authors[] = $oldUserText = $old->getUserText( RevisionRecord
::RAW
);
4034 $newUserText = $new->getUserText( RevisionRecord
::RAW
);
4035 if ( $oldUserText != $newUserText ) {
4036 $authors[] = $newUserText;
4038 } elseif ( $old_cmp === '>=' ) {
4039 $authors[] = $old->getUserText( RevisionRecord
::RAW
);
4040 } elseif ( $new_cmp === '<=' ) {
4041 $authors[] = $new->getUserText( RevisionRecord
::RAW
);
4045 $dbr = wfGetDB( DB_REPLICA
);
4046 $revQuery = Revision
::getQueryInfo();
4047 $authors = $dbr->selectFieldValues(
4048 $revQuery['tables'],
4049 $revQuery['fields']['rev_user_text'],
4051 'rev_page' => $this->getArticleID(),
4052 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4053 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4055 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4062 * Get the number of authors between the given revisions or revision IDs.
4063 * Used for diffs and other things that really need it.
4065 * @param int|Revision $old Old revision or rev ID (first before range by default)
4066 * @param int|Revision $new New revision or rev ID (first after range by default)
4067 * @param int $limit Maximum number of authors
4068 * @param string|array $options (Optional): Single option, or an array of options:
4069 * 'include_old' Include $old in the range; $new is excluded.
4070 * 'include_new' Include $new in the range; $old is excluded.
4071 * 'include_both' Include both $old and $new in the range.
4072 * Unknown option values are ignored.
4073 * @return int Number of revision authors in the range; zero if not both revisions exist
4075 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4076 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4077 return $authors ?
count( $authors ) : 0;
4081 * Compare with another title.
4083 * @param LinkTarget $title
4086 public function equals( LinkTarget
$title ) {
4087 // Note: === is necessary for proper matching of number-like titles.
4088 return $this->mInterwiki
=== $title->getInterwiki()
4089 && $this->mNamespace
== $title->getNamespace()
4090 && $this->mDbkeyform
=== $title->getDBkey();
4094 * Check if this title is a subpage of another title
4096 * @param Title $title
4099 public function isSubpageOf( Title
$title ) {
4100 return $this->mInterwiki
=== $title->mInterwiki
4101 && $this->mNamespace
== $title->mNamespace
4102 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4106 * Check if page exists. For historical reasons, this function simply
4107 * checks for the existence of the title in the page table, and will
4108 * thus return false for interwiki links, special pages and the like.
4109 * If you want to know if a title can be meaningfully viewed, you should
4110 * probably call the isKnown() method instead.
4112 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4113 * from master/for update
4116 public function exists( $flags = 0 ) {
4117 $exists = $this->getArticleID( $flags ) != 0;
4118 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4123 * Should links to this title be shown as potentially viewable (i.e. as
4124 * "bluelinks"), even if there's no record by this title in the page
4127 * This function is semi-deprecated for public use, as well as somewhat
4128 * misleadingly named. You probably just want to call isKnown(), which
4129 * calls this function internally.
4131 * (ISSUE: Most of these checks are cheap, but the file existence check
4132 * can potentially be quite expensive. Including it here fixes a lot of
4133 * existing code, but we might want to add an optional parameter to skip
4134 * it and any other expensive checks.)
4138 public function isAlwaysKnown() {
4142 * Allows overriding default behavior for determining if a page exists.
4143 * If $isKnown is kept as null, regular checks happen. If it's
4144 * a boolean, this value is returned by the isKnown method.
4148 * @param Title $title
4149 * @param bool|null $isKnown
4151 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4153 if ( !is_null( $isKnown ) ) {
4157 if ( $this->isExternal() ) {
4158 return true; // any interwiki link might be viewable, for all we know
4161 $services = MediaWikiServices
::getInstance();
4162 switch ( $this->mNamespace
) {
4165 // file exists, possibly in a foreign repo
4166 return (bool)$services->getRepoGroup()->findFile( $this );
4168 // valid special page
4169 return $services->getSpecialPageFactory()->exists( $this->mDbkeyform
);
4171 // selflink, possibly with fragment
4172 return $this->mDbkeyform
== '';
4174 // known system message
4175 return $this->hasSourceText() !== false;
4182 * Does this title refer to a page that can (or might) be meaningfully
4183 * viewed? In particular, this function may be used to determine if
4184 * links to the title should be rendered as "bluelinks" (as opposed to
4185 * "redlinks" to non-existent pages).
4186 * Adding something else to this function will cause inconsistency
4187 * since LinkHolderArray calls isAlwaysKnown() and does its own
4188 * page existence check.
4192 public function isKnown() {
4193 return $this->isAlwaysKnown() ||
$this->exists();
4197 * Does this page have source text?
4201 public function hasSourceText() {
4202 if ( $this->exists() ) {
4206 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4207 // If the page doesn't exist but is a known system message, default
4208 // message content will be displayed, same for language subpages-
4209 // Use always content language to avoid loading hundreds of languages
4210 // to get the link color.
4211 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4212 list( $name, ) = MessageCache
::singleton()->figureMessage(
4213 $contLang->lcfirst( $this->getText() )
4215 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4216 return $message->exists();
4223 * Get the default (plain) message contents for an page that overrides an
4224 * interface message key.
4226 * Primary use cases:
4229 * - Show default when viewing the page. The Article::getSubstituteContent
4230 * method displays the default message content, instead of the
4231 * 'noarticletext' placeholder message normally used.
4234 * - Title of edit page. When creating an interface message override,
4235 * the editor is told they are "Editing the page", instead of
4236 * "Creating the page". (EditPage::setHeaders)
4237 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4238 * or editing a an interface message override. (EditPage::showIntro)
4239 * - Opening the editor. The contents of the localisation message are used
4240 * as contents of the editor when creating a new page in the MediaWiki
4241 * namespace. This simplifies the process for editors when "changing"
4242 * an interface message by creating an override. (EditPage::getContentObject)
4243 * - Showing a diff. The left-hand side of a diff when an editor is
4244 * previewing their changes before saving the creation of a page in the
4245 * MediaWiki namespace. (EditPage::showDiff)
4246 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4247 * page with the proposed content matching the interface message default,
4248 * the save is rejected, the same way we disallow blank pages from being
4249 * created. (EditPage::internalAttemptSave)
4252 * - Default content, when using the 'prepend' or 'append' feature.
4255 * - Label the create action as "Edit", if the page can be an override.
4257 * @return string|bool
4259 public function getDefaultMessageText() {
4260 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4264 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4265 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4267 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4269 if ( $message->exists() ) {
4270 return $message->plain();
4277 * Updates page_touched for this page; called from LinksUpdate.php
4279 * @param string|null $purgeTime [optional] TS_MW timestamp
4280 * @return bool True if the update succeeded
4282 public function invalidateCache( $purgeTime = null ) {
4283 if ( wfReadOnly() ) {
4285 } elseif ( $this->mArticleID
=== 0 ) {
4286 return true; // avoid gap locking if we know it's not there
4289 $dbw = wfGetDB( DB_MASTER
);
4290 $dbw->onTransactionPreCommitOrIdle(
4291 function () use ( $dbw ) {
4292 ResourceLoaderWikiModule
::invalidateModuleCache(
4293 $this, null, null, $dbw->getDomainID() );
4298 $conds = $this->pageCond();
4299 DeferredUpdates
::addUpdate(
4300 new AutoCommitUpdate(
4303 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4304 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4307 [ 'page_touched' => $dbTimestamp ],
4308 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4311 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4314 DeferredUpdates
::PRESEND
4321 * Update page_touched timestamps and send CDN purge messages for
4322 * pages linking to this title. May be sent to the job queue depending
4323 * on the number of links. Typically called on create and delete.
4325 public function touchLinks() {
4326 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4327 if ( $this->mNamespace
== NS_CATEGORY
) {
4328 DeferredUpdates
::addUpdate(
4329 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4335 * Get the last touched timestamp
4337 * @param IDatabase|null $db
4338 * @return string|false Last-touched timestamp
4340 public function getTouched( $db = null ) {
4341 if ( $db === null ) {
4342 $db = wfGetDB( DB_REPLICA
);
4344 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4349 * Get the timestamp when this page was updated since the user last saw it.
4351 * @param User|null $user
4352 * @return string|bool|null String timestamp, false if not watched, null if nothing is unseen
4354 public function getNotificationTimestamp( $user = null ) {
4357 // Assume current user if none given
4361 // Check cache first
4362 $uid = $user->getId();
4366 // avoid isset here, as it'll return false for null entries
4367 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4368 return $this->mNotificationTimestamp
[$uid];
4370 // Don't cache too much!
4371 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4372 $this->mNotificationTimestamp
= [];
4375 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4376 $watchedItem = $store->getWatchedItem( $user, $this );
4377 if ( $watchedItem ) {
4378 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4380 $this->mNotificationTimestamp
[$uid] = false;
4383 return $this->mNotificationTimestamp
[$uid];
4387 * Generate strings used for xml 'id' names in monobook tabs
4389 * @param string $prepend Defaults to 'nstab-'
4390 * @return string XML 'id' name
4392 public function getNamespaceKey( $prepend = 'nstab-' ) {
4393 // Gets the subject namespace of this title
4394 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
4395 $subjectNS = $nsInfo->getSubject( $this->mNamespace
);
4396 // Prefer canonical namespace name for HTML IDs
4397 $namespaceKey = $nsInfo->getCanonicalName( $subjectNS );
4398 if ( $namespaceKey === false ) {
4399 // Fallback to localised text
4400 $namespaceKey = $this->getSubjectNsText();
4402 // Makes namespace key lowercase
4403 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4405 if ( $namespaceKey == '' ) {
4406 $namespaceKey = 'main';
4408 // Changes file to image for backwards compatibility
4409 if ( $namespaceKey == 'file' ) {
4410 $namespaceKey = 'image';
4412 return $prepend . $namespaceKey;
4416 * Get all extant redirects to this Title
4418 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4419 * @return Title[] Array of Title redirects to this title
4421 public function getRedirectsHere( $ns = null ) {
4424 $dbr = wfGetDB( DB_REPLICA
);
4426 'rd_namespace' => $this->mNamespace
,
4427 'rd_title' => $this->mDbkeyform
,
4430 if ( $this->isExternal() ) {
4431 $where['rd_interwiki'] = $this->mInterwiki
;
4433 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4435 if ( !is_null( $ns ) ) {
4436 $where['page_namespace'] = $ns;
4439 $res = $dbr->select(
4440 [ 'redirect', 'page' ],
4441 [ 'page_namespace', 'page_title' ],
4446 foreach ( $res as $row ) {
4447 $redirs[] = self
::newFromRow( $row );
4453 * Check if this Title is a valid redirect target
4457 public function isValidRedirectTarget() {
4458 global $wgInvalidRedirectTargets;
4460 if ( $this->isSpecialPage() ) {
4461 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4462 if ( $this->isSpecial( 'Userlogout' ) ) {
4466 foreach ( $wgInvalidRedirectTargets as $target ) {
4467 if ( $this->isSpecial( $target ) ) {
4477 * Get a backlink cache object
4479 * @return BacklinkCache
4481 public function getBacklinkCache() {
4482 return BacklinkCache
::get( $this );
4486 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4490 public function canUseNoindex() {
4491 global $wgExemptFromUserRobotsControl;
4493 $bannedNamespaces = $wgExemptFromUserRobotsControl ??
4494 MediaWikiServices
::getInstance()->getNamespaceInfo()->getContentNamespaces();
4496 return !in_array( $this->mNamespace
, $bannedNamespaces );
4500 * Returns the raw sort key to be used for categories, with the specified
4501 * prefix. This will be fed to Collation::getSortKey() to get a
4502 * binary sortkey that can be used for actual sorting.
4504 * @param string $prefix The prefix to be used, specified using
4505 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4509 public function getCategorySortkey( $prefix = '' ) {
4510 $unprefixed = $this->getText();
4512 // Anything that uses this hook should only depend
4513 // on the Title object passed in, and should probably
4514 // tell the users to run updateCollations.php --force
4515 // in order to re-sort existing category relations.
4516 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4517 if ( $prefix !== '' ) {
4518 # Separate with a line feed, so the unprefixed part is only used as
4519 # a tiebreaker when two pages have the exact same prefix.
4520 # In UCA, tab is the only character that can sort above LF
4521 # so we strip both of them from the original prefix.
4522 $prefix = strtr( $prefix, "\n\t", ' ' );
4523 return "$prefix\n$unprefixed";
4529 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4530 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4531 * the db, it will return NULL.
4533 * @return string|null|bool
4535 private function getDbPageLanguageCode() {
4536 global $wgPageLanguageUseDB;
4538 // check, if the page language could be saved in the database, and if so and
4539 // the value is not requested already, lookup the page language using LinkCache
4540 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4541 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4542 $linkCache->addLinkObj( $this );
4543 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4546 return $this->mDbPageLanguage
;
4550 * Get the language in which the content of this page is written in
4551 * wikitext. Defaults to content language, but in certain cases it can be
4552 * e.g. $wgLang (such as special pages, which are in the user language).
4557 public function getPageLanguage() {
4558 global $wgLang, $wgLanguageCode;
4559 if ( $this->isSpecialPage() ) {
4560 // special pages are in the user language
4564 // Checking if DB language is set
4565 $dbPageLanguage = $this->getDbPageLanguageCode();
4566 if ( $dbPageLanguage ) {
4567 return wfGetLangObj( $dbPageLanguage );
4570 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4571 // Note that this may depend on user settings, so the cache should
4572 // be only per-request.
4573 // NOTE: ContentHandler::getPageLanguage() may need to load the
4574 // content to determine the page language!
4575 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4577 $contentHandler = ContentHandler
::getForTitle( $this );
4578 $langObj = $contentHandler->getPageLanguage( $this );
4579 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4581 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4588 * Get the language in which the content of this page is written when
4589 * viewed by user. Defaults to content language, but in certain cases it can be
4590 * e.g. $wgLang (such as special pages, which are in the user language).
4595 public function getPageViewLanguage() {
4598 if ( $this->isSpecialPage() ) {
4599 // If the user chooses a variant, the content is actually
4600 // in a language whose code is the variant code.
4601 $variant = $wgLang->getPreferredVariant();
4602 if ( $wgLang->getCode() !== $variant ) {
4603 return Language
::factory( $variant );
4609 // Checking if DB language is set
4610 $dbPageLanguage = $this->getDbPageLanguageCode();
4611 if ( $dbPageLanguage ) {
4612 $pageLang = wfGetLangObj( $dbPageLanguage );
4613 $variant = $pageLang->getPreferredVariant();
4614 if ( $pageLang->getCode() !== $variant ) {
4615 $pageLang = Language
::factory( $variant );
4621 // @note Can't be cached persistently, depends on user settings.
4622 // @note ContentHandler::getPageViewLanguage() may need to load the
4623 // content to determine the page language!
4624 $contentHandler = ContentHandler
::getForTitle( $this );
4625 $pageLang = $contentHandler->getPageViewLanguage( $this );
4630 * Get a list of rendered edit notices for this page.
4632 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4633 * they will already be wrapped in paragraphs.
4636 * @param int $oldid Revision ID that's being edited
4639 public function getEditNotices( $oldid = 0 ) {
4642 // Optional notice for the entire namespace
4643 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4644 $msg = wfMessage( $editnotice_ns );
4645 if ( $msg->exists() ) {
4646 $html = $msg->parseAsBlock();
4647 // Edit notices may have complex logic, but output nothing (T91715)
4648 if ( trim( $html ) !== '' ) {
4649 $notices[$editnotice_ns] = Html
::rawElement(
4653 'mw-editnotice-namespace',
4654 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4662 MediaWikiServices
::getInstance()->getNamespaceInfo()->
4663 hasSubpages( $this->mNamespace
)
4665 // Optional notice for page itself and any parent page
4666 $editnotice_base = $editnotice_ns;
4667 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4668 $editnotice_base .= '-' . $part;
4669 $msg = wfMessage( $editnotice_base );
4670 if ( $msg->exists() ) {
4671 $html = $msg->parseAsBlock();
4672 if ( trim( $html ) !== '' ) {
4673 $notices[$editnotice_base] = Html
::rawElement(
4677 'mw-editnotice-base',
4678 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4686 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4687 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4688 $msg = wfMessage( $editnoticeText );
4689 if ( $msg->exists() ) {
4690 $html = $msg->parseAsBlock();
4691 if ( trim( $html ) !== '' ) {
4692 $notices[$editnoticeText] = Html
::rawElement(
4696 'mw-editnotice-page',
4697 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4705 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4712 public function __sleep() {
4720 'mDefaultNamespace',
4724 public function __wakeup() {
4725 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4726 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4727 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );