3 * Representation of a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 use MediaWiki\Permissions\PermissionManager
;
26 use Wikimedia\Rdbms\Database
;
27 use Wikimedia\Rdbms\IDatabase
;
28 use MediaWiki\Linker\LinkTarget
;
29 use MediaWiki\Interwiki\InterwikiLookup
;
30 use MediaWiki\MediaWikiServices
;
33 * Represents a title within MediaWiki.
34 * Optionally may contain an interwiki designation or namespace.
35 * @note This class can fetch various kinds of data from the database;
36 * however, it does so inefficiently.
37 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
38 * and does not rely on global state or the database.
40 class Title
implements LinkTarget
, IDBAccessObject
{
41 /** @var MapCacheLRU|null */
42 private static $titleCache = null;
45 * Title::newFromText maintains a cache to avoid expensive re-normalization of
46 * commonly used titles. On a batch operation this can become a memory leak
47 * if not bounded. After hitting this many titles reset the cache.
49 const CACHE_MAX
= 1000;
52 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
53 * to use the master DB
55 const GAID_FOR_UPDATE
= 1;
58 * Flag for use with factory methods like newFromLinkTarget() that have
59 * a $forceClone parameter. If set, the method must return a new instance.
60 * Without this flag, some factory methods may return existing instances.
64 const NEW_CLONE
= 'clone';
67 * @name Private member variables
68 * Please use the accessor functions instead.
73 /** @var string Text form (spaces not underscores) of the main part */
74 public $mTextform = '';
76 /** @var string URL-encoded form of the main part */
77 public $mUrlform = '';
79 /** @var string Main part with underscores */
80 public $mDbkeyform = '';
82 /** @var string Database key with the initial letter in the case specified by the user */
83 protected $mUserCaseDBKey;
85 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
86 public $mNamespace = NS_MAIN
;
88 /** @var string Interwiki prefix */
89 public $mInterwiki = '';
91 /** @var bool Was this Title created from a string with a local interwiki prefix? */
92 private $mLocalInterwiki = false;
94 /** @var string Title fragment (i.e. the bit after the #) */
95 public $mFragment = '';
97 /** @var int Article ID, fetched from the link cache on demand */
98 public $mArticleID = -1;
100 /** @var bool|int ID of most recent revision */
101 protected $mLatestID = false;
104 * @var bool|string ID of the page's content model, i.e. one of the
105 * CONTENT_MODEL_XXX constants
107 private $mContentModel = false;
110 * @var bool If a content model was forced via setContentModel()
111 * this will be true to avoid having other code paths reset it
113 private $mForcedContentModel = false;
115 /** @var int Estimated number of revisions; null of not loaded */
116 private $mEstimateRevisions;
118 /** @var array Array of groups allowed to edit this article */
119 public $mRestrictions = [];
122 * @var string|bool Comma-separated set of permission keys
123 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
124 * Edit and move sections are separated by a colon
125 * Example: "edit=autoconfirmed,sysop:move=sysop"
127 protected $mOldRestrictions = false;
129 /** @var bool Cascade restrictions on this page to included templates and images? */
130 public $mCascadeRestriction;
132 /** Caching the results of getCascadeProtectionSources */
133 public $mCascadingRestrictions;
135 /** @var array When do the restrictions on this page expire? */
136 protected $mRestrictionsExpiry = [];
138 /** @var bool Are cascading restrictions in effect on this page? */
139 protected $mHasCascadingRestrictions;
141 /** @var array Where are the cascading restrictions coming from on this page? */
142 public $mCascadeSources;
144 /** @var bool Boolean for initialisation on demand */
145 public $mRestrictionsLoaded = false;
148 * Text form including namespace/interwiki, initialised on demand
150 * Only public to share cache with TitleFormatter
155 public $prefixedText = null;
157 /** @var mixed Cached value for getTitleProtection (create protection) */
158 public $mTitleProtection;
161 * @var int Namespace index when there is no namespace. Don't change the
162 * following default, NS_MAIN is hardcoded in several places. See T2696.
163 * Zero except in {{transclusion}} tags.
165 public $mDefaultNamespace = NS_MAIN
;
167 /** @var int The page length, 0 for special pages */
168 protected $mLength = -1;
170 /** @var null Is the article at this title a redirect? */
171 public $mRedirect = null;
173 /** @var array Associative array of user ID -> timestamp/false */
174 private $mNotificationTimestamp = [];
176 /** @var bool Whether a page has any subpages */
177 private $mHasSubpages;
179 /** @var bool The (string) language code of the page's language and content code. */
180 private $mPageLanguage = false;
182 /** @var string|bool|null The page language code from the database, null if not saved in
183 * the database or false if not loaded, yet. */
184 private $mDbPageLanguage = false;
186 /** @var TitleValue|null A corresponding TitleValue object */
187 private $mTitleValue = null;
189 /** @var bool|null Would deleting this page be a big deletion? */
190 private $mIsBigDeletion = null;
194 * B/C kludge: provide a TitleParser for use by Title.
195 * Ideally, Title would have no methods that need this.
196 * Avoid usage of this singleton by using TitleValue
197 * and the associated services when possible.
199 * @return TitleFormatter
201 private static function getTitleFormatter() {
202 return MediaWikiServices
::getInstance()->getTitleFormatter();
206 * B/C kludge: provide an InterwikiLookup for use by Title.
207 * Ideally, Title would have no methods that need this.
208 * Avoid usage of this singleton by using TitleValue
209 * and the associated services when possible.
211 * @return InterwikiLookup
213 private static function getInterwikiLookup() {
214 return MediaWikiServices
::getInstance()->getInterwikiLookup();
220 function __construct() {
224 * Create a new Title from a prefixed DB key
226 * @param string $key The database key, which has underscores
227 * instead of spaces, possibly including namespace and
229 * @return Title|null Title, or null on an error
231 public static function newFromDBkey( $key ) {
233 $t->mDbkeyform
= $key;
236 $t->secureAndSplit();
238 } catch ( MalformedTitleException
$ex ) {
244 * Returns a Title given a TitleValue.
245 * If the given TitleValue is already a Title instance, that instance is returned,
246 * unless $forceClone is "clone". If $forceClone is "clone" and the given TitleValue
247 * is already a Title instance, that instance is copied using the clone operator.
249 * @deprecated since 1.34, use newFromLinkTarget or castFromLinkTarget
251 * @param TitleValue $titleValue Assumed to be safe.
252 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
256 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
257 return self
::newFromLinkTarget( $titleValue, $forceClone );
261 * Returns a Title given a LinkTarget.
262 * If the given LinkTarget is already a Title instance, that instance is returned,
263 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
264 * is already a Title instance, that instance is copied using the clone operator.
266 * @param LinkTarget $linkTarget Assumed to be safe.
267 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
271 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
272 if ( $linkTarget instanceof Title
) {
273 // Special case if it's already a Title object
274 if ( $forceClone === self
::NEW_CLONE
) {
275 return clone $linkTarget;
280 return self
::makeTitle(
281 $linkTarget->getNamespace(),
282 $linkTarget->getText(),
283 $linkTarget->getFragment(),
284 $linkTarget->getInterwiki()
289 * Same as newFromLinkTarget, but if passed null, returns null.
291 * @param LinkTarget|null $linkTarget Assumed to be safe (if not null).
295 public static function castFromLinkTarget( $linkTarget ) {
296 return $linkTarget ? self
::newFromLinkTarget( $linkTarget ) : null;
300 * Create a new Title from text, such as what one would find in a link. De-
301 * codes any HTML entities in the text.
303 * Title objects returned by this method are guaranteed to be valid, and
304 * thus return true from the isValid() method.
306 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
307 * It may instead be a cached instance created previously, with references to it remaining
310 * @param string|int|null $text The link text; spaces, prefixes, and an
311 * initial ':' indicating the main namespace are accepted.
312 * @param int $defaultNamespace The namespace to use if none is specified
313 * by a prefix. If you want to force a specific namespace even if
314 * $text might begin with a namespace prefix, use makeTitle() or
316 * @throws InvalidArgumentException
317 * @return Title|null Title or null on an error.
319 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
320 // DWIM: Integers can be passed in here when page titles are used as array keys.
321 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
322 throw new InvalidArgumentException( '$text must be a string.' );
324 if ( $text === null ) {
329 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
330 } catch ( MalformedTitleException
$ex ) {
336 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
337 * rather than returning null.
339 * The exception subclasses encode detailed information about why the title is invalid.
341 * Title objects returned by this method are guaranteed to be valid, and
342 * thus return true from the isValid() method.
344 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
345 * It may instead be a cached instance created previously, with references to it remaining
348 * @see Title::newFromText
351 * @param string $text Title text to check
352 * @param int $defaultNamespace
353 * @throws MalformedTitleException If the title is invalid
356 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
357 if ( is_object( $text ) ) {
358 throw new MWException( '$text must be a string, given an object' );
359 } elseif ( $text === null ) {
360 // Legacy code relies on MalformedTitleException being thrown in this case
361 // (happens when URL with no title in it is parsed). TODO fix
362 throw new MalformedTitleException( 'title-invalid-empty' );
365 $titleCache = self
::getTitleCache();
367 // Wiki pages often contain multiple links to the same page.
368 // Title normalization and parsing can become expensive on pages with many
369 // links, so we can save a little time by caching them.
370 // In theory these are value objects and won't get changed...
371 if ( $defaultNamespace == NS_MAIN
) {
372 $t = $titleCache->get( $text );
378 // Convert things like é ā or 〗 into normalized (T16952) text
379 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
382 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
383 $t->mDefaultNamespace
= (int)$defaultNamespace;
385 $t->secureAndSplit();
386 if ( $defaultNamespace == NS_MAIN
) {
387 $titleCache->set( $text, $t );
393 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
395 * Example of wrong and broken code:
396 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
398 * Example of right code:
399 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
401 * Create a new Title from URL-encoded text. Ensures that
402 * the given title's length does not exceed the maximum.
404 * @param string $url The title, as might be taken from a URL
405 * @return Title|null The new object, or null on an error
407 public static function newFromURL( $url ) {
410 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
411 # but some URLs used it as a space replacement and they still come
412 # from some external search tools.
413 if ( strpos( self
::legalChars(), '+' ) === false ) {
414 $url = strtr( $url, '+', ' ' );
417 $t->mDbkeyform
= strtr( $url, ' ', '_' );
420 $t->secureAndSplit();
422 } catch ( MalformedTitleException
$ex ) {
428 * @return MapCacheLRU
430 private static function getTitleCache() {
431 if ( self
::$titleCache === null ) {
432 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
434 return self
::$titleCache;
438 * Returns a list of fields that are to be selected for initializing Title
439 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
440 * whether to include page_content_model.
444 protected static function getSelectFields() {
445 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
448 'page_namespace', 'page_title', 'page_id',
449 'page_len', 'page_is_redirect', 'page_latest',
452 if ( $wgContentHandlerUseDB ) {
453 $fields[] = 'page_content_model';
456 if ( $wgPageLanguageUseDB ) {
457 $fields[] = 'page_lang';
464 * Create a new Title from an article ID
466 * @param int $id The page_id corresponding to the Title to create
467 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
468 * @return Title|null The new object, or null on an error
470 public static function newFromID( $id, $flags = 0 ) {
471 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
472 $row = $db->selectRow(
474 self
::getSelectFields(),
475 [ 'page_id' => $id ],
478 if ( $row !== false ) {
479 $title = self
::newFromRow( $row );
488 * Make an array of titles from an array of IDs
490 * @param int[] $ids Array of IDs
491 * @return Title[] Array of Titles
493 public static function newFromIDs( $ids ) {
494 if ( !count( $ids ) ) {
497 $dbr = wfGetDB( DB_REPLICA
);
501 self
::getSelectFields(),
502 [ 'page_id' => $ids ],
507 foreach ( $res as $row ) {
508 $titles[] = self
::newFromRow( $row );
514 * Make a Title object from a DB row
516 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
517 * @return Title Corresponding Title
519 public static function newFromRow( $row ) {
520 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
521 $t->loadFromRow( $row );
526 * Load Title object fields from a DB row.
527 * If false is given, the title will be treated as non-existing.
529 * @param stdClass|bool $row Database row
531 public function loadFromRow( $row ) {
532 if ( $row ) { // page found
533 if ( isset( $row->page_id
) ) {
534 $this->mArticleID
= (int)$row->page_id
;
536 if ( isset( $row->page_len
) ) {
537 $this->mLength
= (int)$row->page_len
;
539 if ( isset( $row->page_is_redirect
) ) {
540 $this->mRedirect
= (bool)$row->page_is_redirect
;
542 if ( isset( $row->page_latest
) ) {
543 $this->mLatestID
= (int)$row->page_latest
;
545 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
546 $this->mContentModel
= (string)$row->page_content_model
;
547 } elseif ( !$this->mForcedContentModel
) {
548 $this->mContentModel
= false; # initialized lazily in getContentModel()
550 if ( isset( $row->page_lang
) ) {
551 $this->mDbPageLanguage
= (string)$row->page_lang
;
553 if ( isset( $row->page_restrictions
) ) {
554 $this->mOldRestrictions
= $row->page_restrictions
;
556 } else { // page not found
557 $this->mArticleID
= 0;
559 $this->mRedirect
= false;
560 $this->mLatestID
= 0;
561 if ( !$this->mForcedContentModel
) {
562 $this->mContentModel
= false; # initialized lazily in getContentModel()
568 * Create a new Title from a namespace index and a DB key.
570 * It's assumed that $ns and $title are safe, for instance when
571 * they came directly from the database or a special page name,
572 * not from user input.
574 * No validation is applied. For convenience, spaces are normalized
575 * to underscores, so that e.g. user_text fields can be used directly.
577 * @note This method may return Title objects that are "invalid"
578 * according to the isValid() method. This is usually caused by
579 * configuration changes: e.g. a namespace that was once defined is
580 * no longer configured, or a character that was once allowed in
581 * titles is now forbidden.
583 * @param int $ns The namespace of the article
584 * @param string $title The unprefixed database key form
585 * @param string $fragment The link fragment (after the "#")
586 * @param string $interwiki The interwiki prefix
587 * @return Title The new object
589 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
591 $t->mInterwiki
= $interwiki;
592 $t->mFragment
= $fragment;
593 $t->mNamespace
= $ns = (int)$ns;
594 $t->mDbkeyform
= strtr( $title, ' ', '_' );
595 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
596 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
597 $t->mTextform
= strtr( $title, '_', ' ' );
598 $t->mContentModel
= false; # initialized lazily in getContentModel()
603 * Create a new Title from a namespace index and a DB key.
604 * The parameters will be checked for validity, which is a bit slower
605 * than makeTitle() but safer for user-provided data.
607 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
608 * that is, they return true from the isValid() method. If no valid Title
609 * can be constructed from the input, this method returns null.
611 * @param int $ns The namespace of the article
612 * @param string $title Database key form
613 * @param string $fragment The link fragment (after the "#")
614 * @param string $interwiki Interwiki prefix
615 * @return Title|null The new object, or null on an error
617 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
618 // NOTE: ideally, this would just call makeTitle() and then isValid(),
619 // but presently, that means more overhead on a potential performance hotspot.
621 if ( !MWNamespace
::exists( $ns ) ) {
626 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
629 $t->secureAndSplit();
631 } catch ( MalformedTitleException
$ex ) {
637 * Create a new Title for the Main Page
639 * This uses the 'mainpage' interface message, which could be specified in
640 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
641 * will use the user language, which would involve initialising the session
642 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
643 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
644 * or ResourceloaderContext) to prevent an error.
646 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
647 * It may instead be a cached instance created previously, with references to it remaining
650 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
653 public static function newMainPage( MessageLocalizer
$localizer = null ) {
655 $msg = $localizer->msg( 'mainpage' );
657 $msg = wfMessage( 'mainpage' );
660 $title = self
::newFromText( $msg->inContentLanguage()->text() );
662 // Every page renders at least one link to the Main Page (e.g. sidebar).
663 // If the localised value is invalid, don't produce fatal errors that
664 // would make the wiki inaccessible (and hard to fix the invalid message).
665 // Gracefully fallback...
667 $title = self
::newFromText( 'Main Page' );
673 * Get the prefixed DB key associated with an ID
675 * @param int $id The page_id of the article
676 * @return Title|null An object representing the article, or null if no such article was found
678 public static function nameOf( $id ) {
679 $dbr = wfGetDB( DB_REPLICA
);
681 $s = $dbr->selectRow(
683 [ 'page_namespace', 'page_title' ],
684 [ 'page_id' => $id ],
687 if ( $s === false ) {
691 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
696 * Get a regex character class describing the legal characters in a link
698 * @return string The list of characters, not delimited
700 public static function legalChars() {
701 global $wgLegalTitleChars;
702 return $wgLegalTitleChars;
706 * Utility method for converting a character sequence from bytes to Unicode.
708 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
709 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
711 * @param string $byteClass
714 public static function convertByteClassToUnicodeClass( $byteClass ) {
715 $length = strlen( $byteClass );
717 $x0 = $x1 = $x2 = '';
719 $d0 = $d1 = $d2 = '';
720 // Decoded integer codepoints
721 $ord0 = $ord1 = $ord2 = 0;
723 $r0 = $r1 = $r2 = '';
727 $allowUnicode = false;
728 for ( $pos = 0; $pos < $length; $pos++
) {
729 // Shift the queues down
738 // Load the current input token and decoded values
739 $inChar = $byteClass[$pos];
740 if ( $inChar == '\\' ) {
741 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
742 $x0 = $inChar . $m[0];
743 $d0 = chr( hexdec( $m[1] ) );
744 $pos +
= strlen( $m[0] );
745 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
746 $x0 = $inChar . $m[0];
747 $d0 = chr( octdec( $m[0] ) );
748 $pos +
= strlen( $m[0] );
749 } elseif ( $pos +
1 >= $length ) {
752 $d0 = $byteClass[$pos +
1];
760 // Load the current re-encoded value
761 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
762 $r0 = sprintf( '\x%02x', $ord0 );
763 } elseif ( $ord0 >= 0x80 ) {
764 // Allow unicode if a single high-bit character appears
765 $r0 = sprintf( '\x%02x', $ord0 );
766 $allowUnicode = true;
767 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
768 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
774 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
776 if ( $ord2 > $ord0 ) {
778 } elseif ( $ord0 >= 0x80 ) {
780 $allowUnicode = true;
781 if ( $ord2 < 0x80 ) {
782 // Keep the non-unicode section of the range
789 // Reset state to the initial value
790 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
791 } elseif ( $ord2 < 0x80 ) {
796 if ( $ord1 < 0x80 ) {
799 if ( $ord0 < 0x80 ) {
802 if ( $allowUnicode ) {
803 $out .= '\u0080-\uFFFF';
809 * Make a prefixed DB key from a DB key and a namespace index
811 * @param int $ns Numerical representation of the namespace
812 * @param string $title The DB key form the title
813 * @param string $fragment The link fragment (after the "#")
814 * @param string $interwiki The interwiki prefix
815 * @param bool $canonicalNamespace If true, use the canonical name for
816 * $ns instead of the localized version.
817 * @return string The prefixed form of the title
819 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
820 $canonicalNamespace = false
822 if ( $canonicalNamespace ) {
823 $namespace = MWNamespace
::getCanonicalName( $ns );
825 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
827 $name = $namespace == '' ?
$title : "$namespace:$title";
828 if ( strval( $interwiki ) != '' ) {
829 $name = "$interwiki:$name";
831 if ( strval( $fragment ) != '' ) {
832 $name .= '#' . $fragment;
838 * Callback for usort() to do title sorts by (namespace, title)
840 * @param LinkTarget $a
841 * @param LinkTarget $b
843 * @return int Result of string comparison, or namespace comparison
845 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
846 return $a->getNamespace() <=> $b->getNamespace()
847 ?
: strcmp( $a->getText(), $b->getText() );
851 * Returns true if the title is valid, false if it is invalid.
853 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
854 * Invalid titles may get returned from makeTitle(), and it may be useful to
855 * allow them to exist, e.g. in order to process log entries about pages in
856 * namespaces that belong to extensions that are no longer installed.
858 * @note This method is relatively expensive. When constructing Title
859 * objects that need to be valid, use an instantiator method that is guaranteed
860 * to return valid titles, such as makeTitleSafe() or newFromText().
864 public function isValid() {
865 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
870 $parser = MediaWikiServices
::getInstance()->getTitleParser();
871 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
873 } catch ( MalformedTitleException
$ex ) {
879 * Determine whether the object refers to a page within
880 * this project (either this wiki or a wiki with a local
881 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
883 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
885 public function isLocal() {
886 if ( $this->isExternal() ) {
887 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
889 return $iw->isLocal();
896 * Is this Title interwiki?
900 public function isExternal() {
901 return $this->mInterwiki
!== '';
905 * Get the interwiki prefix
907 * Use Title::isExternal to check if a interwiki is set
909 * @return string Interwiki prefix
911 public function getInterwiki() {
912 return $this->mInterwiki
;
916 * Was this a local interwiki link?
920 public function wasLocalInterwiki() {
921 return $this->mLocalInterwiki
;
925 * Determine whether the object refers to a page within
926 * this project and is transcludable.
928 * @return bool True if this is transcludable
930 public function isTrans() {
931 if ( !$this->isExternal() ) {
935 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
939 * Returns the DB name of the distant wiki which owns the object.
941 * @return string|false The DB name
943 public function getTransWikiID() {
944 if ( !$this->isExternal() ) {
948 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
952 * Get a TitleValue object representing this Title.
954 * @note Not all valid Titles have a corresponding valid TitleValue
955 * (e.g. TitleValues cannot represent page-local links that have a
956 * fragment but no title text).
958 * @return TitleValue|null
960 public function getTitleValue() {
961 if ( $this->mTitleValue
=== null ) {
963 $this->mTitleValue
= new TitleValue(
969 } catch ( InvalidArgumentException
$ex ) {
970 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
971 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
975 return $this->mTitleValue
;
979 * Get the text form (spaces not underscores) of the main part
981 * @return string Main part of the title
983 public function getText() {
984 return $this->mTextform
;
988 * Get the URL-encoded form of the main part
990 * @return string Main part of the title, URL-encoded
992 public function getPartialURL() {
993 return $this->mUrlform
;
997 * Get the main part with underscores
999 * @return string Main part of the title, with underscores
1001 public function getDBkey() {
1002 return $this->mDbkeyform
;
1006 * Get the DB key with the initial letter case as specified by the user
1007 * @deprecated since 1.33; please use Title::getDBKey() instead
1009 * @return string DB key
1011 function getUserCaseDBKey() {
1012 if ( !is_null( $this->mUserCaseDBKey
) ) {
1013 return $this->mUserCaseDBKey
;
1015 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1016 return $this->mDbkeyform
;
1021 * Get the namespace index, i.e. one of the NS_xxxx constants.
1023 * @return int Namespace index
1025 public function getNamespace() {
1026 return $this->mNamespace
;
1030 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1032 * @todo Deprecate this in favor of SlotRecord::getModel()
1034 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1035 * @return string Content model id
1037 public function getContentModel( $flags = 0 ) {
1038 if ( !$this->mForcedContentModel
1039 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1040 && $this->getArticleID( $flags )
1042 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1043 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1044 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1047 if ( !$this->mContentModel
) {
1048 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1051 return $this->mContentModel
;
1055 * Convenience method for checking a title's content model name
1057 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1058 * @return bool True if $this->getContentModel() == $id
1060 public function hasContentModel( $id ) {
1061 return $this->getContentModel() == $id;
1065 * Set a proposed content model for the page for permissions
1066 * checking. This does not actually change the content model
1069 * Additionally, you should make sure you've checked
1070 * ContentHandler::canBeUsedOn() first.
1073 * @param string $model CONTENT_MODEL_XXX constant
1075 public function setContentModel( $model ) {
1076 $this->mContentModel
= $model;
1077 $this->mForcedContentModel
= true;
1081 * Get the namespace text
1083 * @return string|false Namespace text
1085 public function getNsText() {
1086 if ( $this->isExternal() ) {
1087 // This probably shouldn't even happen, except for interwiki transclusion.
1088 // If possible, use the canonical name for the foreign namespace.
1089 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1090 if ( $nsText !== false ) {
1096 $formatter = self
::getTitleFormatter();
1097 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1098 } catch ( InvalidArgumentException
$ex ) {
1099 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1105 * Get the namespace text of the subject (rather than talk) page
1107 * @return string Namespace text
1109 public function getSubjectNsText() {
1110 return MediaWikiServices
::getInstance()->getContentLanguage()->
1111 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1115 * Get the namespace text of the talk page
1117 * @return string Namespace text
1119 public function getTalkNsText() {
1120 return MediaWikiServices
::getInstance()->getContentLanguage()->
1121 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1125 * Can this title have a corresponding talk page?
1127 * @see MWNamespace::hasTalkNamespace
1130 * @return bool True if this title either is a talk page or can have a talk page associated.
1132 public function canHaveTalkPage() {
1133 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1137 * Is this in a namespace that allows actual pages?
1141 public function canExist() {
1142 return $this->mNamespace
>= NS_MAIN
;
1146 * Can this title be added to a user's watchlist?
1150 public function isWatchable() {
1151 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1155 * Returns true if this is a special page.
1159 public function isSpecialPage() {
1160 return $this->mNamespace
== NS_SPECIAL
;
1164 * Returns true if this title resolves to the named special page
1166 * @param string $name The special page name
1169 public function isSpecial( $name ) {
1170 if ( $this->isSpecialPage() ) {
1171 list( $thisName, /* $subpage */ ) =
1172 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1173 resolveAlias( $this->mDbkeyform
);
1174 if ( $name == $thisName ) {
1182 * If the Title refers to a special page alias which is not the local default, resolve
1183 * the alias, and localise the name as necessary. Otherwise, return $this
1187 public function fixSpecialName() {
1188 if ( $this->isSpecialPage() ) {
1189 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1190 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1191 if ( $canonicalName ) {
1192 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1193 if ( $localName != $this->mDbkeyform
) {
1194 return self
::makeTitle( NS_SPECIAL
, $localName );
1202 * Returns true if the title is inside the specified namespace.
1204 * Please make use of this instead of comparing to getNamespace()
1205 * This function is much more resistant to changes we may make
1206 * to namespaces than code that makes direct comparisons.
1207 * @param int $ns The namespace
1211 public function inNamespace( $ns ) {
1212 return MWNamespace
::equals( $this->mNamespace
, $ns );
1216 * Returns true if the title is inside one of the specified namespaces.
1218 * @param int|int[] $namespaces,... The namespaces to check for
1222 public function inNamespaces( /* ... */ ) {
1223 $namespaces = func_get_args();
1224 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1225 $namespaces = $namespaces[0];
1228 foreach ( $namespaces as $ns ) {
1229 if ( $this->inNamespace( $ns ) ) {
1238 * Returns true if the title has the same subject namespace as the
1239 * namespace specified.
1240 * For example this method will take NS_USER and return true if namespace
1241 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1242 * as their subject namespace.
1244 * This is MUCH simpler than individually testing for equivalence
1245 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1250 public function hasSubjectNamespace( $ns ) {
1251 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1255 * Is this Title in a namespace which contains content?
1256 * In other words, is this a content page, for the purposes of calculating
1261 public function isContentPage() {
1262 return MWNamespace
::isContent( $this->mNamespace
);
1266 * Would anybody with sufficient privileges be able to move this page?
1267 * Some pages just aren't movable.
1271 public function isMovable() {
1272 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1273 // Interwiki title or immovable namespace. Hooks don't get to override here
1278 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1283 * Is this the mainpage?
1284 * @note Title::newFromText seems to be sufficiently optimized by the title
1285 * cache that we don't need to over-optimize by doing direct comparisons and
1286 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1287 * ends up reporting something differently than $title->isMainPage();
1292 public function isMainPage() {
1293 return $this->equals( self
::newMainPage() );
1297 * Is this a subpage?
1301 public function isSubpage() {
1302 return MWNamespace
::hasSubpages( $this->mNamespace
)
1303 ?
strpos( $this->getText(), '/' ) !== false
1308 * Is this a conversion table for the LanguageConverter?
1312 public function isConversionTable() {
1313 // @todo ConversionTable should become a separate content model.
1315 return $this->mNamespace
== NS_MEDIAWIKI
&&
1316 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1320 * Does that page contain wikitext, or it is JS, CSS or whatever?
1324 public function isWikitextPage() {
1325 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1329 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1330 * global UI. This is generally true for pages in the MediaWiki namespace having
1331 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1333 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1336 * Note that this method should not return true for pages that contain and show
1337 * "inactive" CSS, JSON, or JS.
1342 public function isSiteConfigPage() {
1344 $this->isSiteCssConfigPage()
1345 ||
$this->isSiteJsonConfigPage()
1346 ||
$this->isSiteJsConfigPage()
1351 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1356 public function isUserConfigPage() {
1358 $this->isUserCssConfigPage()
1359 ||
$this->isUserJsonConfigPage()
1360 ||
$this->isUserJsConfigPage()
1365 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1367 * @return string Containing skin name from .css, .json, or .js subpage title
1370 public function getSkinFromConfigSubpage() {
1371 $subpage = explode( '/', $this->mTextform
);
1372 $subpage = $subpage[count( $subpage ) - 1];
1373 $lastdot = strrpos( $subpage, '.' );
1374 if ( $lastdot === false ) {
1375 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1377 return substr( $subpage, 0, $lastdot );
1381 * Is this a CSS "config" sub-page of a user page?
1386 public function isUserCssConfigPage() {
1388 NS_USER
== $this->mNamespace
1389 && $this->isSubpage()
1390 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1395 * Is this a JSON "config" sub-page of a user page?
1400 public function isUserJsonConfigPage() {
1402 NS_USER
== $this->mNamespace
1403 && $this->isSubpage()
1404 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1409 * Is this a JS "config" sub-page of a user page?
1414 public function isUserJsConfigPage() {
1416 NS_USER
== $this->mNamespace
1417 && $this->isSubpage()
1418 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1423 * Is this a sitewide CSS "config" page?
1428 public function isSiteCssConfigPage() {
1430 NS_MEDIAWIKI
== $this->mNamespace
1432 $this->hasContentModel( CONTENT_MODEL_CSS
)
1433 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1434 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1435 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1441 * Is this a sitewide JSON "config" page?
1446 public function isSiteJsonConfigPage() {
1448 NS_MEDIAWIKI
== $this->mNamespace
1450 $this->hasContentModel( CONTENT_MODEL_JSON
)
1451 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1452 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1453 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1459 * Is this a sitewide JS "config" page?
1464 public function isSiteJsConfigPage() {
1466 NS_MEDIAWIKI
== $this->mNamespace
1468 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1469 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1470 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1471 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1477 * Is this a message which can contain raw HTML?
1482 public function isRawHtmlMessage() {
1483 global $wgRawHtmlMessages;
1485 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1488 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1489 return in_array( $message, $wgRawHtmlMessages, true );
1493 * Is this a talk page of some sort?
1497 public function isTalkPage() {
1498 return MWNamespace
::isTalk( $this->mNamespace
);
1502 * Get a Title object associated with the talk page of this article
1504 * @deprecated since 1.34, use NamespaceInfo::getTalkPage
1505 * @return Title The object for the talk page
1507 public function getTalkPage() {
1508 return self
::castFromLinkTarget(
1509 MediaWikiServices
::getInstance()->getNamespaceInfo()->getTalkPage( $this ) );
1513 * Get a Title object associated with the talk page of this article,
1514 * if such a talk page can exist.
1518 * @return Title|null The object for the talk page,
1519 * or null if no associated talk page can exist, according to canHaveTalkPage().
1521 public function getTalkPageIfDefined() {
1522 if ( !$this->canHaveTalkPage() ) {
1526 return $this->getTalkPage();
1530 * Get a title object associated with the subject page of this
1533 * @deprecated since 1.34, use NamespaceInfo::getSubjectPage
1534 * @return Title The object for the subject page
1536 public function getSubjectPage() {
1537 return self
::castFromLinkTarget(
1538 MediaWikiServices
::getInstance()->getNamespaceInfo()->getSubjectPage( $this ) );
1542 * Get the other title for this page, if this is a subject page
1543 * get the talk page, if it is a subject page get the talk page
1545 * @deprecated since 1.34, use NamespaceInfo::getAssociatedPage
1547 * @throws MWException If the page doesn't have an other page
1550 public function getOtherPage() {
1551 return self
::castFromLinkTarget(
1552 MediaWikiServices
::getInstance()->getNamespaceInfo()->getAssociatedPage( $this ) );
1556 * Get the default namespace index, for when there is no namespace
1558 * @return int Default namespace index
1560 public function getDefaultNamespace() {
1561 return $this->mDefaultNamespace
;
1565 * Get the Title fragment (i.e.\ the bit after the #) in text form
1567 * Use Title::hasFragment to check for a fragment
1569 * @return string Title fragment
1571 public function getFragment() {
1572 return $this->mFragment
;
1576 * Check if a Title fragment is set
1581 public function hasFragment() {
1582 return $this->mFragment
!== '';
1586 * Get the fragment in URL form, including the "#" character if there is one
1588 * @return string Fragment in URL form
1590 public function getFragmentForURL() {
1591 if ( !$this->hasFragment() ) {
1593 } elseif ( $this->isExternal() ) {
1594 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1595 // so we treat it like a local interwiki.
1596 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1597 if ( $interwiki && !$interwiki->isLocal() ) {
1598 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1602 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1606 * Set the fragment for this title. Removes the first character from the
1607 * specified fragment before setting, so it assumes you're passing it with
1610 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1611 * or Title::createFragmentTarget().
1612 * Still in active use privately.
1615 * @param string $fragment Text
1617 public function setFragment( $fragment ) {
1618 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1622 * Creates a new Title for a different fragment of the same page.
1625 * @param string $fragment
1628 public function createFragmentTarget( $fragment ) {
1629 return self
::makeTitle(
1638 * Prefix some arbitrary text with the namespace or interwiki prefix
1641 * @param string $name The text
1642 * @return string The prefixed text
1644 private function prefix( $name ) {
1646 if ( $this->isExternal() ) {
1647 $p = $this->mInterwiki
. ':';
1650 if ( $this->mNamespace
!= 0 ) {
1651 $nsText = $this->getNsText();
1653 if ( $nsText === false ) {
1654 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1655 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1656 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1659 $p .= $nsText . ':';
1665 * Get the prefixed database key form
1667 * @return string The prefixed title, with underscores and
1668 * any interwiki and namespace prefixes
1670 public function getPrefixedDBkey() {
1671 $s = $this->prefix( $this->mDbkeyform
);
1672 $s = strtr( $s, ' ', '_' );
1677 * Get the prefixed title with spaces.
1678 * This is the form usually used for display
1680 * @return string The prefixed title, with spaces
1682 public function getPrefixedText() {
1683 if ( $this->prefixedText
=== null ) {
1684 $s = $this->prefix( $this->mTextform
);
1685 $s = strtr( $s, '_', ' ' );
1686 $this->prefixedText
= $s;
1688 return $this->prefixedText
;
1692 * Return a string representation of this title
1694 * @return string Representation of this title
1696 public function __toString() {
1697 return $this->getPrefixedText();
1701 * Get the prefixed title with spaces, plus any fragment
1702 * (part beginning with '#')
1704 * @return string The prefixed title, with spaces and the fragment, including '#'
1706 public function getFullText() {
1707 $text = $this->getPrefixedText();
1708 if ( $this->hasFragment() ) {
1709 $text .= '#' . $this->mFragment
;
1715 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1719 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1723 * @return string Root name
1726 public function getRootText() {
1727 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1728 return $this->getText();
1731 return strtok( $this->getText(), '/' );
1735 * Get the root page name title, i.e. the leftmost part before any slashes
1739 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1740 * # returns: Title{User:Foo}
1743 * @return Title Root title
1746 public function getRootTitle() {
1747 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1751 * Get the base page name without a namespace, i.e. the part before the subpage name
1755 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1756 * # returns: 'Foo/Bar'
1759 * @return string Base name
1761 public function getBaseText() {
1762 $text = $this->getText();
1763 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1767 $lastSlashPos = strrpos( $text, '/' );
1768 // Don't discard the real title if there's no subpage involved
1769 if ( $lastSlashPos === false ) {
1773 return substr( $text, 0, $lastSlashPos );
1777 * Get the base page name title, i.e. the part before the subpage name
1781 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1782 * # returns: Title{User:Foo/Bar}
1785 * @return Title Base title
1788 public function getBaseTitle() {
1789 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1793 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1797 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1801 * @return string Subpage name
1803 public function getSubpageText() {
1804 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1805 return $this->mTextform
;
1807 $parts = explode( '/', $this->mTextform
);
1808 return $parts[count( $parts ) - 1];
1812 * Get the title for a subpage of the current page
1816 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1817 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1820 * @param string $text The subpage name to add to the title
1821 * @return Title|null Subpage title, or null on an error
1824 public function getSubpage( $text ) {
1825 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1829 * Get a URL-encoded form of the subpage text
1831 * @return string URL-encoded subpage name
1833 public function getSubpageUrlForm() {
1834 $text = $this->getSubpageText();
1835 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1840 * Get a URL-encoded title (not an actual URL) including interwiki
1842 * @return string The URL-encoded form
1844 public function getPrefixedURL() {
1845 $s = $this->prefix( $this->mDbkeyform
);
1846 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1851 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1852 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1853 * second argument named variant. This was deprecated in favor
1854 * of passing an array of option with a "variant" key
1855 * Once $query2 is removed for good, this helper can be dropped
1856 * and the wfArrayToCgi moved to getLocalURL();
1858 * @since 1.19 (r105919)
1859 * @param array|string $query
1860 * @param string|string[]|bool $query2
1863 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1864 if ( $query2 !== false ) {
1865 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1866 "method called with a second parameter is deprecated. Add your " .
1867 "parameter to an array passed as the first parameter.", "1.19" );
1869 if ( is_array( $query ) ) {
1870 $query = wfArrayToCgi( $query );
1873 if ( is_string( $query2 ) ) {
1874 // $query2 is a string, we will consider this to be
1875 // a deprecated $variant argument and add it to the query
1876 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1878 $query2 = wfArrayToCgi( $query2 );
1880 // If we have $query content add a & to it first
1884 // Now append the queries together
1891 * Get a real URL referring to this title, with interwiki link and
1894 * @see self::getLocalURL for the arguments.
1896 * @param string|string[] $query
1897 * @param string|string[]|bool $query2
1898 * @param string|int|null $proto Protocol type to use in URL
1899 * @return string The URL
1901 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1902 $query = self
::fixUrlQueryArgs( $query, $query2 );
1904 # Hand off all the decisions on urls to getLocalURL
1905 $url = $this->getLocalURL( $query );
1907 # Expand the url to make it a full url. Note that getLocalURL has the
1908 # potential to output full urls for a variety of reasons, so we use
1909 # wfExpandUrl instead of simply prepending $wgServer
1910 $url = wfExpandUrl( $url, $proto );
1912 # Finally, add the fragment.
1913 $url .= $this->getFragmentForURL();
1914 // Avoid PHP 7.1 warning from passing $this by reference
1916 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1921 * Get a url appropriate for making redirects based on an untrusted url arg
1923 * This is basically the same as getFullUrl(), but in the case of external
1924 * interwikis, we send the user to a landing page, to prevent possible
1925 * phishing attacks and the like.
1927 * @note Uses current protocol by default, since technically relative urls
1928 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1929 * places where the url gets cached, as might pollute between
1930 * https and non-https users.
1931 * @see self::getLocalURL for the arguments.
1932 * @param array|string $query
1933 * @param string $proto Protocol type to use in URL
1934 * @return string A url suitable to use in an HTTP location header.
1936 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1938 if ( $this->isExternal() ) {
1939 $target = SpecialPage
::getTitleFor(
1941 $this->getPrefixedDBkey()
1944 return $target->getFullURL( $query, false, $proto );
1948 * Get a URL with no fragment or server name (relative URL) from a Title object.
1949 * If this page is generated with action=render, however,
1950 * $wgServer is prepended to make an absolute URL.
1952 * @see self::getFullURL to always get an absolute URL.
1953 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1954 * valid to link, locally, to the current Title.
1955 * @see self::newFromText to produce a Title object.
1957 * @param string|string[] $query An optional query string,
1958 * not used for interwiki links. Can be specified as an associative array as well,
1959 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1960 * Some query patterns will trigger various shorturl path replacements.
1961 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1962 * be an array. If a string is passed it will be interpreted as a deprecated
1963 * variant argument and urlencoded into a variant= argument.
1964 * This second query argument will be added to the $query
1965 * The second parameter is deprecated since 1.19. Pass it as a key,value
1966 * pair in the first parameter array instead.
1968 * @return string String of the URL.
1970 public function getLocalURL( $query = '', $query2 = false ) {
1971 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1973 $query = self
::fixUrlQueryArgs( $query, $query2 );
1975 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1977 $namespace = $this->getNsText();
1978 if ( $namespace != '' ) {
1979 # Can this actually happen? Interwikis shouldn't be parsed.
1980 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1983 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1984 $url = wfAppendQuery( $url, $query );
1986 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1987 if ( $query == '' ) {
1988 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1989 // Avoid PHP 7.1 warning from passing $this by reference
1991 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1993 global $wgVariantArticlePath, $wgActionPaths;
1997 if ( !empty( $wgActionPaths )
1998 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
2000 $action = urldecode( $matches[2] );
2001 if ( isset( $wgActionPaths[$action] ) ) {
2002 $query = $matches[1];
2003 if ( isset( $matches[4] ) ) {
2004 $query .= $matches[4];
2006 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2007 if ( $query != '' ) {
2008 $url = wfAppendQuery( $url, $query );
2014 && $wgVariantArticlePath
2015 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2016 && $this->getPageLanguage()->equals(
2017 MediaWikiServices
::getInstance()->getContentLanguage() )
2018 && $this->getPageLanguage()->hasVariants()
2020 $variant = urldecode( $matches[1] );
2021 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2022 // Only do the variant replacement if the given variant is a valid
2023 // variant for the page's language.
2024 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2025 $url = str_replace( '$1', $dbkey, $url );
2029 if ( $url === false ) {
2030 if ( $query == '-' ) {
2033 $url = "{$wgScript}?title={$dbkey}&{$query}";
2036 // Avoid PHP 7.1 warning from passing $this by reference
2038 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2040 // @todo FIXME: This causes breakage in various places when we
2041 // actually expected a local URL and end up with dupe prefixes.
2042 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2043 $url = $wgServer . $url;
2046 // Avoid PHP 7.1 warning from passing $this by reference
2048 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2053 * Get a URL that's the simplest URL that will be valid to link, locally,
2054 * to the current Title. It includes the fragment, but does not include
2055 * the server unless action=render is used (or the link is external). If
2056 * there's a fragment but the prefixed text is empty, we just return a link
2059 * The result obviously should not be URL-escaped, but does need to be
2060 * HTML-escaped if it's being output in HTML.
2062 * @param string|string[] $query
2063 * @param bool $query2
2064 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2065 * or false (default) for no expansion
2066 * @see self::getLocalURL for the arguments.
2067 * @return string The URL
2069 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2070 if ( $this->isExternal() ||
$proto !== false ) {
2071 $ret = $this->getFullURL( $query, $query2, $proto );
2072 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2073 $ret = $this->getFragmentForURL();
2075 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2081 * Get the URL form for an internal link.
2082 * - Used in various CDN-related code, in case we have a different
2083 * internal hostname for the server from the exposed one.
2085 * This uses $wgInternalServer to qualify the path, or $wgServer
2086 * if $wgInternalServer is not set. If the server variable used is
2087 * protocol-relative, the URL will be expanded to http://
2089 * @see self::getLocalURL for the arguments.
2090 * @param string|string[] $query
2091 * @param string|bool $query2 Deprecated
2092 * @return string The URL
2094 public function getInternalURL( $query = '', $query2 = false ) {
2095 global $wgInternalServer, $wgServer;
2096 $query = self
::fixUrlQueryArgs( $query, $query2 );
2097 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2098 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2099 // Avoid PHP 7.1 warning from passing $this by reference
2101 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2106 * Get the URL for a canonical link, for use in things like IRC and
2107 * e-mail notifications. Uses $wgCanonicalServer and the
2108 * GetCanonicalURL hook.
2110 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2112 * @see self::getLocalURL for the arguments.
2113 * @param string|string[] $query
2114 * @param string|bool $query2 Deprecated
2115 * @return string The URL
2118 public function getCanonicalURL( $query = '', $query2 = false ) {
2119 $query = self
::fixUrlQueryArgs( $query, $query2 );
2120 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2121 // Avoid PHP 7.1 warning from passing $this by reference
2123 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2128 * Get the edit URL for this Title
2130 * @return string The URL, or a null string if this is an interwiki link
2132 public function getEditURL() {
2133 if ( $this->isExternal() ) {
2136 $s = $this->getLocalURL( 'action=edit' );
2142 * Can $user perform $action on this page?
2143 * This skips potentially expensive cascading permission checks
2144 * as well as avoids expensive error formatting
2146 * Suitable for use for nonessential UI controls in common cases, but
2147 * _not_ for functional access control.
2149 * May provide false positives, but should never provide a false negative.
2151 * @param string $action Action that permission needs to be checked for
2152 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2157 * @deprecated since 1.33,
2158 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2161 public function quickUserCan( $action, $user = null ) {
2162 return $this->userCan( $action, $user, false );
2166 * Can $user perform $action on this page?
2168 * @param string $action Action that permission needs to be checked for
2169 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2171 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2176 * @deprecated since 1.33,
2177 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2180 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2181 if ( !$user instanceof User
) {
2186 // TODO: this is for b/c, eventually will be removed
2187 if ( $rigor === true ) {
2188 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2189 } elseif ( $rigor === false ) {
2190 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2193 return MediaWikiServices
::getInstance()->getPermissionManager()
2194 ->userCan( $action, $user, $this, $rigor );
2198 * Can $user perform $action on this page?
2200 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2202 * @param string $action Action that permission needs to be checked for
2203 * @param User $user User to check
2204 * @param string $rigor One of (quick,full,secure)
2205 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2206 * - full : does cheap and expensive checks possibly from a replica DB
2207 * - secure : does cheap and expensive checks, using the master as needed
2208 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2209 * whose corresponding errors may be ignored.
2211 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2214 * @deprecated since 1.33,
2215 * use MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissionsErrors()
2218 public function getUserPermissionsErrors(
2219 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2221 // TODO: this is for b/c, eventually will be removed
2222 if ( $rigor === true ) {
2223 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2224 } elseif ( $rigor === false ) {
2225 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2228 return MediaWikiServices
::getInstance()->getPermissionManager()
2229 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2233 * Add the resulting error code to the errors array
2235 * @param array $errors List of current errors
2236 * @param array $result Result of errors
2238 * @return array List of errors
2240 private function resultToError( $errors, $result ) {
2241 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2242 // A single array representing an error
2243 $errors[] = $result;
2244 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2245 // A nested array representing multiple errors
2246 $errors = array_merge( $errors, $result );
2247 } elseif ( $result !== '' && is_string( $result ) ) {
2248 // A string representing a message-id
2249 $errors[] = [ $result ];
2250 } elseif ( $result instanceof MessageSpecifier
) {
2251 // A message specifier representing an error
2252 $errors[] = [ $result ];
2253 } elseif ( $result === false ) {
2254 // a generic "We don't want them to do that"
2255 $errors[] = [ 'badaccess-group0' ];
2261 * Get a filtered list of all restriction types supported by this wiki.
2262 * @param bool $exists True to get all restriction types that apply to
2263 * titles that do exist, False for all restriction types that apply to
2264 * titles that do not exist
2267 public static function getFilteredRestrictionTypes( $exists = true ) {
2268 global $wgRestrictionTypes;
2269 $types = $wgRestrictionTypes;
2271 # Remove the create restriction for existing titles
2272 $types = array_diff( $types, [ 'create' ] );
2274 # Only the create and upload restrictions apply to non-existing titles
2275 $types = array_intersect( $types, [ 'create', 'upload' ] );
2281 * Returns restriction types for the current Title
2283 * @return array Applicable restriction types
2285 public function getRestrictionTypes() {
2286 if ( $this->isSpecialPage() ) {
2290 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2292 if ( $this->mNamespace
!= NS_FILE
) {
2293 # Remove the upload restriction for non-file titles
2294 $types = array_diff( $types, [ 'upload' ] );
2297 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2299 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2300 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2306 * Is this title subject to title protection?
2307 * Title protection is the one applied against creation of such title.
2309 * @return array|bool An associative array representing any existent title
2310 * protection, or false if there's none.
2312 public function getTitleProtection() {
2313 $protection = $this->getTitleProtectionInternal();
2314 if ( $protection ) {
2315 if ( $protection['permission'] == 'sysop' ) {
2316 $protection['permission'] = 'editprotected'; // B/C
2318 if ( $protection['permission'] == 'autoconfirmed' ) {
2319 $protection['permission'] = 'editsemiprotected'; // B/C
2326 * Fetch title protection settings
2328 * To work correctly, $this->loadRestrictions() needs to have access to the
2329 * actual protections in the database without munging 'sysop' =>
2330 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2331 * callers probably want $this->getTitleProtection() instead.
2333 * @return array|bool
2335 protected function getTitleProtectionInternal() {
2336 // Can't protect pages in special namespaces
2337 if ( $this->mNamespace
< 0 ) {
2341 // Can't protect pages that exist.
2342 if ( $this->exists() ) {
2346 if ( $this->mTitleProtection
=== null ) {
2347 $dbr = wfGetDB( DB_REPLICA
);
2348 $commentStore = CommentStore
::getStore();
2349 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2350 $res = $dbr->select(
2351 [ 'protected_titles' ] +
$commentQuery['tables'],
2353 'user' => 'pt_user',
2354 'expiry' => 'pt_expiry',
2355 'permission' => 'pt_create_perm'
2356 ] +
$commentQuery['fields'],
2357 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2360 $commentQuery['joins']
2363 // fetchRow returns false if there are no rows.
2364 $row = $dbr->fetchRow( $res );
2366 $this->mTitleProtection
= [
2367 'user' => $row['user'],
2368 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2369 'permission' => $row['permission'],
2370 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2373 $this->mTitleProtection
= false;
2376 return $this->mTitleProtection
;
2380 * Remove any title protection due to page existing
2382 public function deleteTitleProtection() {
2383 $dbw = wfGetDB( DB_MASTER
);
2387 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2390 $this->mTitleProtection
= false;
2394 * Is this page "semi-protected" - the *only* protection levels are listed
2395 * in $wgSemiprotectedRestrictionLevels?
2397 * @param string $action Action to check (default: edit)
2400 public function isSemiProtected( $action = 'edit' ) {
2401 global $wgSemiprotectedRestrictionLevels;
2403 $restrictions = $this->getRestrictions( $action );
2404 $semi = $wgSemiprotectedRestrictionLevels;
2405 if ( !$restrictions ||
!$semi ) {
2406 // Not protected, or all protection is full protection
2410 // Remap autoconfirmed to editsemiprotected for BC
2411 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2412 $semi[$key] = 'editsemiprotected';
2414 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2415 $restrictions[$key] = 'editsemiprotected';
2418 return !array_diff( $restrictions, $semi );
2422 * Does the title correspond to a protected article?
2424 * @param string $action The action the page is protected from,
2425 * by default checks all actions.
2428 public function isProtected( $action = '' ) {
2429 global $wgRestrictionLevels;
2431 $restrictionTypes = $this->getRestrictionTypes();
2433 # Special pages have inherent protection
2434 if ( $this->isSpecialPage() ) {
2438 # Check regular protection levels
2439 foreach ( $restrictionTypes as $type ) {
2440 if ( $action == $type ||
$action == '' ) {
2441 $r = $this->getRestrictions( $type );
2442 foreach ( $wgRestrictionLevels as $level ) {
2443 if ( in_array( $level, $r ) && $level != '' ) {
2454 * Determines if $user is unable to edit this page because it has been protected
2455 * by $wgNamespaceProtection.
2457 * @param User $user User object to check permissions
2460 public function isNamespaceProtected( User
$user ) {
2461 global $wgNamespaceProtection;
2463 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2464 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2465 if ( $right != '' && !$user->isAllowed( $right ) ) {
2474 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2476 * @return bool If the page is subject to cascading restrictions.
2478 public function isCascadeProtected() {
2479 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2480 return ( $sources > 0 );
2484 * Determines whether cascading protection sources have already been loaded from
2487 * @param bool $getPages True to check if the pages are loaded, or false to check
2488 * if the status is loaded.
2489 * @return bool Whether or not the specified information has been loaded
2492 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2493 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2497 * Cascading protection: Get the source of any cascading restrictions on this page.
2499 * @param bool $getPages Whether or not to retrieve the actual pages
2500 * that the restrictions have come from and the actual restrictions
2502 * @return array Two elements: First is an array of Title objects of the
2503 * pages from which cascading restrictions have come, false for
2504 * none, or true if such restrictions exist but $getPages was not
2505 * set. Second is an array like that returned by
2506 * Title::getAllRestrictions(), or an empty array if $getPages is
2509 public function getCascadeProtectionSources( $getPages = true ) {
2510 $pagerestrictions = [];
2512 if ( $this->mCascadeSources
!== null && $getPages ) {
2513 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2514 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2515 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2518 $dbr = wfGetDB( DB_REPLICA
);
2520 if ( $this->mNamespace
== NS_FILE
) {
2521 $tables = [ 'imagelinks', 'page_restrictions' ];
2523 'il_to' => $this->mDbkeyform
,
2528 $tables = [ 'templatelinks', 'page_restrictions' ];
2530 'tl_namespace' => $this->mNamespace
,
2531 'tl_title' => $this->mDbkeyform
,
2538 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2539 'pr_expiry', 'pr_type', 'pr_level' ];
2540 $where_clauses[] = 'page_id=pr_page';
2543 $cols = [ 'pr_expiry' ];
2546 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2548 $sources = $getPages ?
[] : false;
2549 $now = wfTimestampNow();
2551 foreach ( $res as $row ) {
2552 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2553 if ( $expiry > $now ) {
2555 $page_id = $row->pr_page
;
2556 $page_ns = $row->page_namespace
;
2557 $page_title = $row->page_title
;
2558 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2559 # Add groups needed for each restriction type if its not already there
2560 # Make sure this restriction type still exists
2562 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2563 $pagerestrictions[$row->pr_type
] = [];
2567 isset( $pagerestrictions[$row->pr_type
] )
2568 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2570 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2579 $this->mCascadeSources
= $sources;
2580 $this->mCascadingRestrictions
= $pagerestrictions;
2582 $this->mHasCascadingRestrictions
= $sources;
2585 return [ $sources, $pagerestrictions ];
2589 * Accessor for mRestrictionsLoaded
2591 * @return bool Whether or not the page's restrictions have already been
2592 * loaded from the database
2595 public function areRestrictionsLoaded() {
2596 return $this->mRestrictionsLoaded
;
2600 * Accessor/initialisation for mRestrictions
2602 * @param string $action Action that permission needs to be checked for
2603 * @return array Restriction levels needed to take the action. All levels are
2604 * required. Note that restriction levels are normally user rights, but 'sysop'
2605 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2606 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2608 public function getRestrictions( $action ) {
2609 if ( !$this->mRestrictionsLoaded
) {
2610 $this->loadRestrictions();
2612 return $this->mRestrictions
[$action] ??
[];
2616 * Accessor/initialisation for mRestrictions
2618 * @return array Keys are actions, values are arrays as returned by
2619 * Title::getRestrictions()
2622 public function getAllRestrictions() {
2623 if ( !$this->mRestrictionsLoaded
) {
2624 $this->loadRestrictions();
2626 return $this->mRestrictions
;
2630 * Get the expiry time for the restriction against a given action
2632 * @param string $action
2633 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2634 * or not protected at all, or false if the action is not recognised.
2636 public function getRestrictionExpiry( $action ) {
2637 if ( !$this->mRestrictionsLoaded
) {
2638 $this->loadRestrictions();
2640 return $this->mRestrictionsExpiry
[$action] ??
false;
2644 * Returns cascading restrictions for the current article
2648 function areRestrictionsCascading() {
2649 if ( !$this->mRestrictionsLoaded
) {
2650 $this->loadRestrictions();
2653 return $this->mCascadeRestriction
;
2657 * Compiles list of active page restrictions from both page table (pre 1.10)
2658 * and page_restrictions table for this existing page.
2659 * Public for usage by LiquidThreads.
2661 * @param array $rows Array of db result objects
2662 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2663 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2664 * Edit and move sections are separated by a colon
2665 * Example: "edit=autoconfirmed,sysop:move=sysop"
2667 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2668 // This function will only read rows from a table that we migrated away
2669 // from before adding READ_LATEST support to loadRestrictions, so we
2670 // don't need to support reading from DB_MASTER here.
2671 $dbr = wfGetDB( DB_REPLICA
);
2673 $restrictionTypes = $this->getRestrictionTypes();
2675 foreach ( $restrictionTypes as $type ) {
2676 $this->mRestrictions
[$type] = [];
2677 $this->mRestrictionsExpiry
[$type] = 'infinity';
2680 $this->mCascadeRestriction
= false;
2682 # Backwards-compatibility: also load the restrictions from the page record (old format).
2683 if ( $oldFashionedRestrictions !== null ) {
2684 $this->mOldRestrictions
= $oldFashionedRestrictions;
2687 if ( $this->mOldRestrictions
=== false ) {
2688 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2689 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2690 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2693 if ( $this->mOldRestrictions
!= '' ) {
2694 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2695 $temp = explode( '=', trim( $restrict ) );
2696 if ( count( $temp ) == 1 ) {
2697 // old old format should be treated as edit/move restriction
2698 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2699 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2701 $restriction = trim( $temp[1] );
2702 if ( $restriction != '' ) { // some old entries are empty
2703 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2709 if ( count( $rows ) ) {
2710 # Current system - load second to make them override.
2711 $now = wfTimestampNow();
2713 # Cycle through all the restrictions.
2714 foreach ( $rows as $row ) {
2715 // Don't take care of restrictions types that aren't allowed
2716 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2720 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2722 // Only apply the restrictions if they haven't expired!
2723 if ( !$expiry ||
$expiry > $now ) {
2724 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2725 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2727 $this->mCascadeRestriction |
= $row->pr_cascade
;
2732 $this->mRestrictionsLoaded
= true;
2736 * Load restrictions from the page_restrictions table
2738 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2739 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2740 * Edit and move sections are separated by a colon
2741 * Example: "edit=autoconfirmed,sysop:move=sysop"
2742 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2743 * from the master DB.
2745 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2746 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2747 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2751 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2752 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2753 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2754 $id = $this->getArticleID();
2756 $fname = __METHOD__
;
2757 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2758 return iterator_to_array(
2760 'page_restrictions',
2761 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2762 [ 'pr_page' => $id ],
2768 if ( $readLatest ) {
2769 $dbr = wfGetDB( DB_MASTER
);
2770 $rows = $loadRestrictionsFromDb( $dbr );
2772 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2773 $rows = $cache->getWithSetCallback(
2774 // Page protections always leave a new null revision
2775 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2777 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2778 $dbr = wfGetDB( DB_REPLICA
);
2780 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2781 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2782 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2783 // @TODO: cleanup Title cache and caller assumption mess in general
2784 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2787 return $loadRestrictionsFromDb( $dbr );
2792 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2794 $title_protection = $this->getTitleProtectionInternal();
2796 if ( $title_protection ) {
2797 $now = wfTimestampNow();
2798 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2800 if ( !$expiry ||
$expiry > $now ) {
2801 // Apply the restrictions
2802 $this->mRestrictionsExpiry
['create'] = $expiry;
2803 $this->mRestrictions
['create'] =
2804 explode( ',', trim( $title_protection['permission'] ) );
2805 } else { // Get rid of the old restrictions
2806 $this->mTitleProtection
= false;
2809 $this->mRestrictionsExpiry
['create'] = 'infinity';
2811 $this->mRestrictionsLoaded
= true;
2816 * Flush the protection cache in this object and force reload from the database.
2817 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2819 public function flushRestrictions() {
2820 $this->mRestrictionsLoaded
= false;
2821 $this->mTitleProtection
= null;
2825 * Purge expired restrictions from the page_restrictions table
2827 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2829 static function purgeExpiredRestrictions() {
2830 if ( wfReadOnly() ) {
2834 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2835 wfGetDB( DB_MASTER
),
2837 function ( IDatabase
$dbw, $fname ) {
2838 $config = MediaWikiServices
::getInstance()->getMainConfig();
2839 $ids = $dbw->selectFieldValues(
2840 'page_restrictions',
2842 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2844 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2847 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2852 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2853 wfGetDB( DB_MASTER
),
2855 function ( IDatabase
$dbw, $fname ) {
2858 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2866 * Does this have subpages? (Warning, usually requires an extra DB query.)
2870 public function hasSubpages() {
2871 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2876 # We dynamically add a member variable for the purpose of this method
2877 # alone to cache the result. There's no point in having it hanging
2878 # around uninitialized in every Title object; therefore we only add it
2879 # if needed and don't declare it statically.
2880 if ( $this->mHasSubpages
=== null ) {
2881 $this->mHasSubpages
= false;
2882 $subpages = $this->getSubpages( 1 );
2883 if ( $subpages instanceof TitleArray
) {
2884 $this->mHasSubpages
= (bool)$subpages->count();
2888 return $this->mHasSubpages
;
2892 * Get all subpages of this page.
2894 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2895 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2896 * doesn't allow subpages
2898 public function getSubpages( $limit = -1 ) {
2899 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2903 $dbr = wfGetDB( DB_REPLICA
);
2904 $conds['page_namespace'] = $this->mNamespace
;
2905 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2907 if ( $limit > -1 ) {
2908 $options['LIMIT'] = $limit;
2910 return TitleArray
::newFromResult(
2911 $dbr->select( 'page',
2912 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2921 * Is there a version of this page in the deletion archive?
2923 * @return int The number of archived revisions
2925 public function isDeleted() {
2926 if ( $this->mNamespace
< 0 ) {
2929 $dbr = wfGetDB( DB_REPLICA
);
2931 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2932 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2935 if ( $this->mNamespace
== NS_FILE
) {
2936 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2937 [ 'fa_name' => $this->mDbkeyform
],
2946 * Is there a version of this page in the deletion archive?
2950 public function isDeletedQuick() {
2951 if ( $this->mNamespace
< 0 ) {
2954 $dbr = wfGetDB( DB_REPLICA
);
2955 $deleted = (bool)$dbr->selectField( 'archive', '1',
2956 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2959 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
2960 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2961 [ 'fa_name' => $this->mDbkeyform
],
2969 * Get the article ID for this Title from the link cache,
2970 * adding it if necessary
2972 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
2974 * @return int The ID
2976 public function getArticleID( $flags = 0 ) {
2977 if ( $this->mNamespace
< 0 ) {
2978 $this->mArticleID
= 0;
2979 return $this->mArticleID
;
2981 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2982 if ( $flags & self
::GAID_FOR_UPDATE
) {
2983 $oldUpdate = $linkCache->forUpdate( true );
2984 $linkCache->clearLink( $this );
2985 $this->mArticleID
= $linkCache->addLinkObj( $this );
2986 $linkCache->forUpdate( $oldUpdate );
2987 } elseif ( $this->mArticleID
== -1 ) {
2988 $this->mArticleID
= $linkCache->addLinkObj( $this );
2990 return $this->mArticleID
;
2994 * Is this an article that is a redirect page?
2995 * Uses link cache, adding it if necessary
2997 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3000 public function isRedirect( $flags = 0 ) {
3001 if ( !is_null( $this->mRedirect
) ) {
3002 return $this->mRedirect
;
3004 if ( !$this->getArticleID( $flags ) ) {
3005 $this->mRedirect
= false;
3006 return $this->mRedirect
;
3009 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3010 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3011 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3012 if ( $cached === null ) {
3013 # Trust LinkCache's state over our own
3014 # LinkCache is telling us that the page doesn't exist, despite there being cached
3015 # data relating to an existing page in $this->mArticleID. Updaters should clear
3016 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3017 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3018 # LinkCache to refresh its data from the master.
3019 $this->mRedirect
= false;
3020 return $this->mRedirect
;
3023 $this->mRedirect
= (bool)$cached;
3025 return $this->mRedirect
;
3029 * What is the length of this page?
3030 * Uses link cache, adding it if necessary
3032 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3035 public function getLength( $flags = 0 ) {
3036 if ( $this->mLength
!= -1 ) {
3037 return $this->mLength
;
3039 if ( !$this->getArticleID( $flags ) ) {
3041 return $this->mLength
;
3043 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3044 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3045 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3046 if ( $cached === null ) {
3047 # Trust LinkCache's state over our own, as for isRedirect()
3049 return $this->mLength
;
3052 $this->mLength
= intval( $cached );
3054 return $this->mLength
;
3058 * What is the page_latest field for this page?
3060 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3061 * @return int Int or 0 if the page doesn't exist
3063 public function getLatestRevID( $flags = 0 ) {
3064 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3065 return intval( $this->mLatestID
);
3067 if ( !$this->getArticleID( $flags ) ) {
3068 $this->mLatestID
= 0;
3069 return $this->mLatestID
;
3071 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3072 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3073 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3074 if ( $cached === null ) {
3075 # Trust LinkCache's state over our own, as for isRedirect()
3076 $this->mLatestID
= 0;
3077 return $this->mLatestID
;
3080 $this->mLatestID
= intval( $cached );
3082 return $this->mLatestID
;
3086 * This clears some fields in this object, and clears any associated
3087 * keys in the "bad links" section of the link cache.
3089 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3090 * loading of the new page_id. It's also called from
3091 * WikiPage::doDeleteArticleReal()
3093 * @param int $newid The new Article ID
3095 public function resetArticleID( $newid ) {
3096 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3097 $linkCache->clearLink( $this );
3099 if ( $newid === false ) {
3100 $this->mArticleID
= -1;
3102 $this->mArticleID
= intval( $newid );
3104 $this->mRestrictionsLoaded
= false;
3105 $this->mRestrictions
= [];
3106 $this->mOldRestrictions
= false;
3107 $this->mRedirect
= null;
3108 $this->mLength
= -1;
3109 $this->mLatestID
= false;
3110 $this->mContentModel
= false;
3111 $this->mEstimateRevisions
= null;
3112 $this->mPageLanguage
= false;
3113 $this->mDbPageLanguage
= false;
3114 $this->mIsBigDeletion
= null;
3117 public static function clearCaches() {
3118 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3119 $linkCache->clear();
3121 $titleCache = self
::getTitleCache();
3122 $titleCache->clear();
3126 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3128 * @param string $text Containing title to capitalize
3129 * @param int $ns Namespace index, defaults to NS_MAIN
3130 * @return string Containing capitalized title
3132 public static function capitalize( $text, $ns = NS_MAIN
) {
3133 if ( MWNamespace
::isCapitalized( $ns ) ) {
3134 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3141 * Secure and split - main initialisation function for this object
3143 * Assumes that mDbkeyform has been set, and is urldecoded
3144 * and uses underscores, but not otherwise munged. This function
3145 * removes illegal characters, splits off the interwiki and
3146 * namespace prefixes, sets the other forms, and canonicalizes
3149 * @throws MalformedTitleException On invalid titles
3150 * @return bool True on success
3152 private function secureAndSplit() {
3153 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3154 // the parsing code with Title, while avoiding massive refactoring.
3155 // @todo: get rid of secureAndSplit, refactor parsing code.
3156 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3157 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3158 /** @var MediaWikiTitleCodec $titleCodec */
3159 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3160 // MalformedTitleException can be thrown here
3161 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3164 $this->setFragment( '#' . $parts['fragment'] );
3165 $this->mInterwiki
= $parts['interwiki'];
3166 $this->mLocalInterwiki
= $parts['local_interwiki'];
3167 $this->mNamespace
= $parts['namespace'];
3168 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3170 $this->mDbkeyform
= $parts['dbkey'];
3171 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3172 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3174 # We already know that some pages won't be in the database!
3175 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3176 $this->mArticleID
= 0;
3183 * Get an array of Title objects linking to this Title
3184 * Also stores the IDs in the link cache.
3186 * WARNING: do not use this function on arbitrary user-supplied titles!
3187 * On heavily-used templates it will max out the memory.
3189 * @param array $options May be FOR UPDATE
3190 * @param string $table Table name
3191 * @param string $prefix Fields prefix
3192 * @return Title[] Array of Title objects linking here
3194 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3195 if ( count( $options ) > 0 ) {
3196 $db = wfGetDB( DB_MASTER
);
3198 $db = wfGetDB( DB_REPLICA
);
3203 self
::getSelectFields(),
3205 "{$prefix}_from=page_id",
3206 "{$prefix}_namespace" => $this->mNamespace
,
3207 "{$prefix}_title" => $this->mDbkeyform
],
3213 if ( $res->numRows() ) {
3214 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3215 foreach ( $res as $row ) {
3216 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3218 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3219 $retVal[] = $titleObj;
3227 * Get an array of Title objects using this Title as a template
3228 * Also stores the IDs in the link cache.
3230 * WARNING: do not use this function on arbitrary user-supplied titles!
3231 * On heavily-used templates it will max out the memory.
3233 * @param array $options Query option to Database::select()
3234 * @return Title[] Array of Title the Title objects linking here
3236 public function getTemplateLinksTo( $options = [] ) {
3237 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3241 * Get an array of Title objects linked from this Title
3242 * Also stores the IDs in the link cache.
3244 * WARNING: do not use this function on arbitrary user-supplied titles!
3245 * On heavily-used templates it will max out the memory.
3247 * @param array $options Query option to Database::select()
3248 * @param string $table Table name
3249 * @param string $prefix Fields prefix
3250 * @return array Array of Title objects linking here
3252 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3253 $id = $this->getArticleID();
3255 # If the page doesn't exist; there can't be any link from this page
3260 $db = wfGetDB( DB_REPLICA
);
3262 $blNamespace = "{$prefix}_namespace";
3263 $blTitle = "{$prefix}_title";
3265 $pageQuery = WikiPage
::getQueryInfo();
3267 [ $table, 'nestpage' => $pageQuery['tables'] ],
3269 [ $blNamespace, $blTitle ],
3270 $pageQuery['fields']
3272 [ "{$prefix}_from" => $id ],
3277 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3278 ] ] +
$pageQuery['joins']
3282 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3283 foreach ( $res as $row ) {
3284 if ( $row->page_id
) {
3285 $titleObj = self
::newFromRow( $row );
3287 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3288 $linkCache->addBadLinkObj( $titleObj );
3290 $retVal[] = $titleObj;
3297 * Get an array of Title objects used on this Title as a template
3298 * Also stores the IDs in the link cache.
3300 * WARNING: do not use this function on arbitrary user-supplied titles!
3301 * On heavily-used templates it will max out the memory.
3303 * @param array $options May be FOR UPDATE
3304 * @return Title[] Array of Title the Title objects used here
3306 public function getTemplateLinksFrom( $options = [] ) {
3307 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3311 * Get an array of Title objects referring to non-existent articles linked
3314 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3315 * should use redirect table in this case).
3316 * @return Title[] Array of Title the Title objects
3318 public function getBrokenLinksFrom() {
3319 if ( $this->getArticleID() == 0 ) {
3320 # All links from article ID 0 are false positives
3324 $dbr = wfGetDB( DB_REPLICA
);
3325 $res = $dbr->select(
3326 [ 'page', 'pagelinks' ],
3327 [ 'pl_namespace', 'pl_title' ],
3329 'pl_from' => $this->getArticleID(),
3330 'page_namespace IS NULL'
3336 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3342 foreach ( $res as $row ) {
3343 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3349 * Get a list of URLs to purge from the CDN cache when this
3352 * @return string[] Array of String the URLs
3354 public function getCdnUrls() {
3356 $this->getInternalURL(),
3357 $this->getInternalURL( 'action=history' )
3360 $pageLang = $this->getPageLanguage();
3361 if ( $pageLang->hasVariants() ) {
3362 $variants = $pageLang->getVariants();
3363 foreach ( $variants as $vCode ) {
3364 $urls[] = $this->getInternalURL( $vCode );
3368 // If we are looking at a css/js user subpage, purge the action=raw.
3369 if ( $this->isUserJsConfigPage() ) {
3370 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3371 } elseif ( $this->isUserJsonConfigPage() ) {
3372 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3373 } elseif ( $this->isUserCssConfigPage() ) {
3374 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3377 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3382 * Purge all applicable CDN URLs
3384 public function purgeSquid() {
3385 DeferredUpdates
::addUpdate(
3386 new CdnCacheUpdate( $this->getCdnUrls() ),
3387 DeferredUpdates
::PRESEND
3392 * Check whether a given move operation would be valid.
3393 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3395 * @deprecated since 1.25, use MovePage's methods instead
3396 * @param Title &$nt The new title
3397 * @param bool $auth Whether to check user permissions (uses $wgUser)
3398 * @param string $reason Is the log summary of the move, used for spam checking
3399 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3401 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3404 if ( !( $nt instanceof Title
) ) {
3405 // Normally we'd add this to $errors, but we'll get
3406 // lots of syntax errors if $nt is not an object
3407 return [ [ 'badtitletext' ] ];
3410 $mp = new MovePage( $this, $nt );
3411 $errors = $mp->isValidMove()->getErrorsArray();
3413 $errors = wfMergeErrorArrays(
3415 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3419 return $errors ?
: true;
3423 * Move a title to a new location
3425 * @deprecated since 1.25, use the MovePage class instead
3426 * @param Title &$nt The new title
3427 * @param bool $auth Indicates whether $wgUser's permissions
3429 * @param string $reason The reason for the move
3430 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3431 * Ignored if the user doesn't have the suppressredirect right.
3432 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3433 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3435 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3436 array $changeTags = []
3440 $mp = new MovePage( $this, $nt );
3441 $method = $auth ?
'moveIfAllowed' : 'move';
3442 $status = $mp->$method( $wgUser, $reason, $createRedirect, $changeTags );
3443 if ( $status->isOK() ) {
3446 return $status->getErrorsArray();
3451 * Move this page's subpages to be subpages of $nt
3453 * @param Title $nt Move target
3454 * @param bool $auth Whether $wgUser's permissions should be checked
3455 * @param string $reason The reason for the move
3456 * @param bool $createRedirect Whether to create redirects from the old subpages to
3457 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3458 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3459 * @return array Array with old page titles as keys, and strings (new page titles) or
3460 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3461 * getUserPermissionsErrors()-like error array with numeric indices if
3462 * no pages were moved
3464 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3465 array $changeTags = []
3467 global $wgMaximumMovedPages;
3468 // Check permissions
3469 if ( !$this->userCan( 'move-subpages' ) ) {
3471 [ 'cant-move-subpages' ],
3474 // Do the source and target namespaces support subpages?
3475 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3477 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
3480 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3482 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3486 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3489 foreach ( $subpages as $oldSubpage ) {
3491 if ( $count > $wgMaximumMovedPages ) {
3492 $retval[$oldSubpage->getPrefixedText()] = [
3493 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3498 // We don't know whether this function was called before
3499 // or after moving the root page, so check both
3501 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3502 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3504 // When moving a page to a subpage of itself,
3505 // don't move it twice
3508 $newPageName = preg_replace(
3509 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
3510 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3511 $oldSubpage->getDBkey() );
3512 if ( $oldSubpage->isTalkPage() ) {
3513 $newNs = $nt->getTalkPage()->getNamespace();
3515 $newNs = $nt->getSubjectPage()->getNamespace();
3517 # T16385: we need makeTitleSafe because the new page names may
3518 # be longer than 255 characters.
3519 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3521 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3522 if ( $success === true ) {
3523 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3525 $retval[$oldSubpage->getPrefixedText()] = $success;
3532 * Checks if this page is just a one-rev redirect.
3533 * Adds lock, so don't use just for light purposes.
3537 public function isSingleRevRedirect() {
3538 global $wgContentHandlerUseDB;
3540 $dbw = wfGetDB( DB_MASTER
);
3543 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3544 if ( $wgContentHandlerUseDB ) {
3545 $fields[] = 'page_content_model';
3548 $row = $dbw->selectRow( 'page',
3554 # Cache some fields we may want
3555 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3556 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3557 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3558 $this->mContentModel
= $row && isset( $row->page_content_model
)
3559 ?
strval( $row->page_content_model
)
3562 if ( !$this->mRedirect
) {
3565 # Does the article have a history?
3566 $row = $dbw->selectField( [ 'page', 'revision' ],
3568 [ 'page_namespace' => $this->mNamespace
,
3569 'page_title' => $this->mDbkeyform
,
3571 'page_latest != rev_id'
3576 # Return true if there was no history
3577 return ( $row === false );
3581 * Checks if $this can be moved to a given Title
3582 * - Selects for update, so don't call it unless you mean business
3584 * @deprecated since 1.25, use MovePage's methods instead
3585 * @param Title $nt The new title to check
3588 public function isValidMoveTarget( $nt ) {
3589 # Is it an existing file?
3590 if ( $nt->getNamespace() == NS_FILE
) {
3591 $file = wfLocalFile( $nt );
3592 $file->load( File
::READ_LATEST
);
3593 if ( $file->exists() ) {
3594 wfDebug( __METHOD__
. ": file exists\n" );
3598 # Is it a redirect with no history?
3599 if ( !$nt->isSingleRevRedirect() ) {
3600 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3603 # Get the article text
3604 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3605 if ( !is_object( $rev ) ) {
3608 $content = $rev->getContent();
3609 # Does the redirect point to the source?
3610 # Or is it a broken self-redirect, usually caused by namespace collisions?
3611 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3613 if ( $redirTitle ) {
3614 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3615 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3616 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3622 # Fail safe (not a redirect after all. strange.)
3623 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3624 " is a redirect, but it doesn't contain a valid redirect.\n" );
3630 * Get categories to which this Title belongs and return an array of
3631 * categories' names.
3633 * @return array Array of parents in the form:
3634 * $parent => $currentarticle
3636 public function getParentCategories() {
3639 $titleKey = $this->getArticleID();
3641 if ( $titleKey === 0 ) {
3645 $dbr = wfGetDB( DB_REPLICA
);
3647 $res = $dbr->select(
3650 [ 'cl_from' => $titleKey ],
3654 if ( $res->numRows() > 0 ) {
3655 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3656 foreach ( $res as $row ) {
3657 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3658 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3659 $this->getFullText();
3666 * Get a tree of parent categories
3668 * @param array $children Array with the children in the keys, to check for circular refs
3669 * @return array Tree of parent categories
3671 public function getParentCategoryTree( $children = [] ) {
3673 $parents = $this->getParentCategories();
3676 foreach ( $parents as $parent => $current ) {
3677 if ( array_key_exists( $parent, $children ) ) {
3678 # Circular reference
3679 $stack[$parent] = [];
3681 $nt = self
::newFromText( $parent );
3683 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3693 * Get an associative array for selecting this title from
3696 * @return array Array suitable for the $where parameter of DB::select()
3698 public function pageCond() {
3699 if ( $this->mArticleID
> 0 ) {
3700 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3701 return [ 'page_id' => $this->mArticleID
];
3703 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3708 * Get next/previous revision ID relative to another revision ID
3709 * @param int $revId Revision ID. Get the revision that was before this one.
3710 * @param int $flags Title::GAID_FOR_UPDATE
3711 * @param string $dir 'next' or 'prev'
3712 * @return int|bool New revision ID, or false if none exists
3714 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3715 $rl = MediaWikiServices
::getInstance()->getRevisionLookup();
3716 $rlFlags = $flags === self
::GAID_FOR_UPDATE ? IDBAccessObject
::READ_LATEST
: 0;
3717 $rev = $rl->getRevisionById( $revId, $rlFlags );
3721 $oldRev = $dir === 'next'
3722 ?
$rl->getNextRevision( $rev, $rlFlags )
3723 : $rl->getPreviousRevision( $rev, $rlFlags );
3727 return $oldRev->getId();
3731 * Get the revision ID of the previous revision
3733 * @deprecated since 1.34, use RevisionLookup::getPreviousRevision
3734 * @param int $revId Revision ID. Get the revision that was before this one.
3735 * @param int $flags Title::GAID_FOR_UPDATE
3736 * @return int|bool Old revision ID, or false if none exists
3738 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3739 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3743 * Get the revision ID of the next revision
3745 * @deprecated since 1.34, use RevisionLookup::getNextRevision
3746 * @param int $revId Revision ID. Get the revision that was after this one.
3747 * @param int $flags Title::GAID_FOR_UPDATE
3748 * @return int|bool Next revision ID, or false if none exists
3750 public function getNextRevisionID( $revId, $flags = 0 ) {
3751 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3755 * Get the first revision of the page
3757 * @param int $flags Title::GAID_FOR_UPDATE
3758 * @return Revision|null If page doesn't exist
3760 public function getFirstRevision( $flags = 0 ) {
3761 $pageId = $this->getArticleID( $flags );
3763 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3764 $revQuery = Revision
::getQueryInfo();
3765 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3766 [ 'rev_page' => $pageId ],
3769 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3770 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3775 return new Revision( $row, 0, $this );
3782 * Get the oldest revision timestamp of this page
3784 * @param int $flags Title::GAID_FOR_UPDATE
3785 * @return string|null MW timestamp
3787 public function getEarliestRevTime( $flags = 0 ) {
3788 $rev = $this->getFirstRevision( $flags );
3789 return $rev ?
$rev->getTimestamp() : null;
3793 * Check if this is a new page
3797 public function isNewPage() {
3798 $dbr = wfGetDB( DB_REPLICA
);
3799 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3803 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3807 public function isBigDeletion() {
3808 global $wgDeleteRevisionsLimit;
3810 if ( !$wgDeleteRevisionsLimit ) {
3814 if ( $this->mIsBigDeletion
=== null ) {
3815 $dbr = wfGetDB( DB_REPLICA
);
3817 $revCount = $dbr->selectRowCount(
3820 [ 'rev_page' => $this->getArticleID() ],
3822 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3825 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3828 return $this->mIsBigDeletion
;
3832 * Get the approximate revision count of this page.
3836 public function estimateRevisionCount() {
3837 if ( !$this->exists() ) {
3841 if ( $this->mEstimateRevisions
=== null ) {
3842 $dbr = wfGetDB( DB_REPLICA
);
3843 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3844 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3847 return $this->mEstimateRevisions
;
3851 * Get the number of revisions between the given revision.
3852 * Used for diffs and other things that really need it.
3854 * @param int|Revision $old Old revision or rev ID (first before range)
3855 * @param int|Revision $new New revision or rev ID (first after range)
3856 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3857 * @return int Number of revisions between these revisions.
3859 public function countRevisionsBetween( $old, $new, $max = null ) {
3860 if ( !( $old instanceof Revision
) ) {
3861 $old = Revision
::newFromTitle( $this, (int)$old );
3863 if ( !( $new instanceof Revision
) ) {
3864 $new = Revision
::newFromTitle( $this, (int)$new );
3866 if ( !$old ||
!$new ) {
3867 return 0; // nothing to compare
3869 $dbr = wfGetDB( DB_REPLICA
);
3871 'rev_page' => $this->getArticleID(),
3872 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3873 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3875 if ( $max !== null ) {
3876 return $dbr->selectRowCount( 'revision', '1',
3879 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3882 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3887 * Get the authors between the given revisions or revision IDs.
3888 * Used for diffs and other things that really need it.
3892 * @param int|Revision $old Old revision or rev ID (first before range by default)
3893 * @param int|Revision $new New revision or rev ID (first after range by default)
3894 * @param int $limit Maximum number of authors
3895 * @param string|array $options (Optional): Single option, or an array of options:
3896 * 'include_old' Include $old in the range; $new is excluded.
3897 * 'include_new' Include $new in the range; $old is excluded.
3898 * 'include_both' Include both $old and $new in the range.
3899 * Unknown option values are ignored.
3900 * @return array|null Names of revision authors in the range; null if not both revisions exist
3902 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3903 if ( !( $old instanceof Revision
) ) {
3904 $old = Revision
::newFromTitle( $this, (int)$old );
3906 if ( !( $new instanceof Revision
) ) {
3907 $new = Revision
::newFromTitle( $this, (int)$new );
3909 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3910 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3911 // in the sanity check below?
3912 if ( !$old ||
!$new ) {
3913 return null; // nothing to compare
3918 $options = (array)$options;
3919 if ( in_array( 'include_old', $options ) ) {
3922 if ( in_array( 'include_new', $options ) ) {
3925 if ( in_array( 'include_both', $options ) ) {
3929 // No DB query needed if $old and $new are the same or successive revisions:
3930 if ( $old->getId() === $new->getId() ) {
3931 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3933 [ $old->getUserText( Revision
::RAW
) ];
3934 } elseif ( $old->getId() === $new->getParentId() ) {
3935 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3936 $authors[] = $old->getUserText( Revision
::RAW
);
3937 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3938 $authors[] = $new->getUserText( Revision
::RAW
);
3940 } elseif ( $old_cmp === '>=' ) {
3941 $authors[] = $old->getUserText( Revision
::RAW
);
3942 } elseif ( $new_cmp === '<=' ) {
3943 $authors[] = $new->getUserText( Revision
::RAW
);
3947 $dbr = wfGetDB( DB_REPLICA
);
3948 $revQuery = Revision
::getQueryInfo();
3949 $authors = $dbr->selectFieldValues(
3950 $revQuery['tables'],
3951 $revQuery['fields']['rev_user_text'],
3953 'rev_page' => $this->getArticleID(),
3954 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3955 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3957 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
3964 * Get the number of authors between the given revisions or revision IDs.
3965 * Used for diffs and other things that really need it.
3967 * @param int|Revision $old Old revision or rev ID (first before range by default)
3968 * @param int|Revision $new New revision or rev ID (first after range by default)
3969 * @param int $limit Maximum number of authors
3970 * @param string|array $options (Optional): Single option, or an array of options:
3971 * 'include_old' Include $old in the range; $new is excluded.
3972 * 'include_new' Include $new in the range; $old is excluded.
3973 * 'include_both' Include both $old and $new in the range.
3974 * Unknown option values are ignored.
3975 * @return int Number of revision authors in the range; zero if not both revisions exist
3977 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
3978 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
3979 return $authors ?
count( $authors ) : 0;
3983 * Compare with another title.
3985 * @param LinkTarget $title
3988 public function equals( LinkTarget
$title ) {
3989 // Note: === is necessary for proper matching of number-like titles.
3990 return $this->mInterwiki
=== $title->getInterwiki()
3991 && $this->mNamespace
== $title->getNamespace()
3992 && $this->mDbkeyform
=== $title->getDBkey();
3996 * Check if this title is a subpage of another title
3998 * @param Title $title
4001 public function isSubpageOf( Title
$title ) {
4002 return $this->mInterwiki
=== $title->mInterwiki
4003 && $this->mNamespace
== $title->mNamespace
4004 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4008 * Check if page exists. For historical reasons, this function simply
4009 * checks for the existence of the title in the page table, and will
4010 * thus return false for interwiki links, special pages and the like.
4011 * If you want to know if a title can be meaningfully viewed, you should
4012 * probably call the isKnown() method instead.
4014 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4015 * from master/for update
4018 public function exists( $flags = 0 ) {
4019 $exists = $this->getArticleID( $flags ) != 0;
4020 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4025 * Should links to this title be shown as potentially viewable (i.e. as
4026 * "bluelinks"), even if there's no record by this title in the page
4029 * This function is semi-deprecated for public use, as well as somewhat
4030 * misleadingly named. You probably just want to call isKnown(), which
4031 * calls this function internally.
4033 * (ISSUE: Most of these checks are cheap, but the file existence check
4034 * can potentially be quite expensive. Including it here fixes a lot of
4035 * existing code, but we might want to add an optional parameter to skip
4036 * it and any other expensive checks.)
4040 public function isAlwaysKnown() {
4044 * Allows overriding default behavior for determining if a page exists.
4045 * If $isKnown is kept as null, regular checks happen. If it's
4046 * a boolean, this value is returned by the isKnown method.
4050 * @param Title $title
4051 * @param bool|null $isKnown
4053 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4055 if ( !is_null( $isKnown ) ) {
4059 if ( $this->isExternal() ) {
4060 return true; // any interwiki link might be viewable, for all we know
4063 switch ( $this->mNamespace
) {
4066 // file exists, possibly in a foreign repo
4067 return (bool)wfFindFile( $this );
4069 // valid special page
4070 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4071 exists( $this->mDbkeyform
);
4073 // selflink, possibly with fragment
4074 return $this->mDbkeyform
== '';
4076 // known system message
4077 return $this->hasSourceText() !== false;
4084 * Does this title refer to a page that can (or might) be meaningfully
4085 * viewed? In particular, this function may be used to determine if
4086 * links to the title should be rendered as "bluelinks" (as opposed to
4087 * "redlinks" to non-existent pages).
4088 * Adding something else to this function will cause inconsistency
4089 * since LinkHolderArray calls isAlwaysKnown() and does its own
4090 * page existence check.
4094 public function isKnown() {
4095 return $this->isAlwaysKnown() ||
$this->exists();
4099 * Does this page have source text?
4103 public function hasSourceText() {
4104 if ( $this->exists() ) {
4108 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4109 // If the page doesn't exist but is a known system message, default
4110 // message content will be displayed, same for language subpages-
4111 // Use always content language to avoid loading hundreds of languages
4112 // to get the link color.
4113 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4114 list( $name, ) = MessageCache
::singleton()->figureMessage(
4115 $contLang->lcfirst( $this->getText() )
4117 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4118 return $message->exists();
4125 * Get the default (plain) message contents for an page that overrides an
4126 * interface message key.
4128 * Primary use cases:
4131 * - Show default when viewing the page. The Article::getSubstituteContent
4132 * method displays the default message content, instead of the
4133 * 'noarticletext' placeholder message normally used.
4136 * - Title of edit page. When creating an interface message override,
4137 * the editor is told they are "Editing the page", instead of
4138 * "Creating the page". (EditPage::setHeaders)
4139 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4140 * or editing a an interface message override. (EditPage::showIntro)
4141 * - Opening the editor. The contents of the localisation message are used
4142 * as contents of the editor when creating a new page in the MediaWiki
4143 * namespace. This simplifies the process for editors when "changing"
4144 * an interface message by creating an override. (EditPage::getContentObject)
4145 * - Showing a diff. The left-hand side of a diff when an editor is
4146 * previewing their changes before saving the creation of a page in the
4147 * MediaWiki namespace. (EditPage::showDiff)
4148 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4149 * page with the proposed content matching the interface message default,
4150 * the save is rejected, the same way we disallow blank pages from being
4151 * created. (EditPage::internalAttemptSave)
4154 * - Default content, when using the 'prepend' or 'append' feature.
4157 * - Label the create action as "Edit", if the page can be an override.
4159 * @return string|bool
4161 public function getDefaultMessageText() {
4162 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4166 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4167 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4169 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4171 if ( $message->exists() ) {
4172 return $message->plain();
4179 * Updates page_touched for this page; called from LinksUpdate.php
4181 * @param string|null $purgeTime [optional] TS_MW timestamp
4182 * @return bool True if the update succeeded
4184 public function invalidateCache( $purgeTime = null ) {
4185 if ( wfReadOnly() ) {
4187 } elseif ( $this->mArticleID
=== 0 ) {
4188 return true; // avoid gap locking if we know it's not there
4191 $dbw = wfGetDB( DB_MASTER
);
4192 $dbw->onTransactionPreCommitOrIdle(
4193 function () use ( $dbw ) {
4194 ResourceLoaderWikiModule
::invalidateModuleCache(
4195 $this, null, null, $dbw->getDomainID() );
4200 $conds = $this->pageCond();
4201 DeferredUpdates
::addUpdate(
4202 new AutoCommitUpdate(
4205 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4206 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4209 [ 'page_touched' => $dbTimestamp ],
4210 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4213 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4216 DeferredUpdates
::PRESEND
4223 * Update page_touched timestamps and send CDN purge messages for
4224 * pages linking to this title. May be sent to the job queue depending
4225 * on the number of links. Typically called on create and delete.
4227 public function touchLinks() {
4228 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4229 if ( $this->mNamespace
== NS_CATEGORY
) {
4230 DeferredUpdates
::addUpdate(
4231 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4237 * Get the last touched timestamp
4239 * @param IDatabase|null $db
4240 * @return string|false Last-touched timestamp
4242 public function getTouched( $db = null ) {
4243 if ( $db === null ) {
4244 $db = wfGetDB( DB_REPLICA
);
4246 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4251 * Get the timestamp when this page was updated since the user last saw it.
4253 * @param User|null $user
4254 * @return string|null
4256 public function getNotificationTimestamp( $user = null ) {
4259 // Assume current user if none given
4263 // Check cache first
4264 $uid = $user->getId();
4268 // avoid isset here, as it'll return false for null entries
4269 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4270 return $this->mNotificationTimestamp
[$uid];
4272 // Don't cache too much!
4273 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4274 $this->mNotificationTimestamp
= [];
4277 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4278 $watchedItem = $store->getWatchedItem( $user, $this );
4279 if ( $watchedItem ) {
4280 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4282 $this->mNotificationTimestamp
[$uid] = false;
4285 return $this->mNotificationTimestamp
[$uid];
4289 * Generate strings used for xml 'id' names in monobook tabs
4291 * @param string $prepend Defaults to 'nstab-'
4292 * @return string XML 'id' name
4294 public function getNamespaceKey( $prepend = 'nstab-' ) {
4295 // Gets the subject namespace of this title
4296 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4297 // Prefer canonical namespace name for HTML IDs
4298 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4299 if ( $namespaceKey === false ) {
4300 // Fallback to localised text
4301 $namespaceKey = $this->getSubjectNsText();
4303 // Makes namespace key lowercase
4304 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4306 if ( $namespaceKey == '' ) {
4307 $namespaceKey = 'main';
4309 // Changes file to image for backwards compatibility
4310 if ( $namespaceKey == 'file' ) {
4311 $namespaceKey = 'image';
4313 return $prepend . $namespaceKey;
4317 * Get all extant redirects to this Title
4319 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4320 * @return Title[] Array of Title redirects to this title
4322 public function getRedirectsHere( $ns = null ) {
4325 $dbr = wfGetDB( DB_REPLICA
);
4327 'rd_namespace' => $this->mNamespace
,
4328 'rd_title' => $this->mDbkeyform
,
4331 if ( $this->isExternal() ) {
4332 $where['rd_interwiki'] = $this->mInterwiki
;
4334 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4336 if ( !is_null( $ns ) ) {
4337 $where['page_namespace'] = $ns;
4340 $res = $dbr->select(
4341 [ 'redirect', 'page' ],
4342 [ 'page_namespace', 'page_title' ],
4347 foreach ( $res as $row ) {
4348 $redirs[] = self
::newFromRow( $row );
4354 * Check if this Title is a valid redirect target
4358 public function isValidRedirectTarget() {
4359 global $wgInvalidRedirectTargets;
4361 if ( $this->isSpecialPage() ) {
4362 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4363 if ( $this->isSpecial( 'Userlogout' ) ) {
4367 foreach ( $wgInvalidRedirectTargets as $target ) {
4368 if ( $this->isSpecial( $target ) ) {
4378 * Get a backlink cache object
4380 * @return BacklinkCache
4382 public function getBacklinkCache() {
4383 return BacklinkCache
::get( $this );
4387 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4391 public function canUseNoindex() {
4392 global $wgExemptFromUserRobotsControl;
4394 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
4396 return !in_array( $this->mNamespace
, $bannedNamespaces );
4400 * Returns the raw sort key to be used for categories, with the specified
4401 * prefix. This will be fed to Collation::getSortKey() to get a
4402 * binary sortkey that can be used for actual sorting.
4404 * @param string $prefix The prefix to be used, specified using
4405 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4409 public function getCategorySortkey( $prefix = '' ) {
4410 $unprefixed = $this->getText();
4412 // Anything that uses this hook should only depend
4413 // on the Title object passed in, and should probably
4414 // tell the users to run updateCollations.php --force
4415 // in order to re-sort existing category relations.
4416 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4417 if ( $prefix !== '' ) {
4418 # Separate with a line feed, so the unprefixed part is only used as
4419 # a tiebreaker when two pages have the exact same prefix.
4420 # In UCA, tab is the only character that can sort above LF
4421 # so we strip both of them from the original prefix.
4422 $prefix = strtr( $prefix, "\n\t", ' ' );
4423 return "$prefix\n$unprefixed";
4429 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4430 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4431 * the db, it will return NULL.
4433 * @return string|null|bool
4435 private function getDbPageLanguageCode() {
4436 global $wgPageLanguageUseDB;
4438 // check, if the page language could be saved in the database, and if so and
4439 // the value is not requested already, lookup the page language using LinkCache
4440 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4441 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4442 $linkCache->addLinkObj( $this );
4443 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4446 return $this->mDbPageLanguage
;
4450 * Get the language in which the content of this page is written in
4451 * wikitext. Defaults to content language, but in certain cases it can be
4452 * e.g. $wgLang (such as special pages, which are in the user language).
4457 public function getPageLanguage() {
4458 global $wgLang, $wgLanguageCode;
4459 if ( $this->isSpecialPage() ) {
4460 // special pages are in the user language
4464 // Checking if DB language is set
4465 $dbPageLanguage = $this->getDbPageLanguageCode();
4466 if ( $dbPageLanguage ) {
4467 return wfGetLangObj( $dbPageLanguage );
4470 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4471 // Note that this may depend on user settings, so the cache should
4472 // be only per-request.
4473 // NOTE: ContentHandler::getPageLanguage() may need to load the
4474 // content to determine the page language!
4475 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4477 $contentHandler = ContentHandler
::getForTitle( $this );
4478 $langObj = $contentHandler->getPageLanguage( $this );
4479 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4481 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4488 * Get the language in which the content of this page is written when
4489 * viewed by user. Defaults to content language, but in certain cases it can be
4490 * e.g. $wgLang (such as special pages, which are in the user language).
4495 public function getPageViewLanguage() {
4498 if ( $this->isSpecialPage() ) {
4499 // If the user chooses a variant, the content is actually
4500 // in a language whose code is the variant code.
4501 $variant = $wgLang->getPreferredVariant();
4502 if ( $wgLang->getCode() !== $variant ) {
4503 return Language
::factory( $variant );
4509 // Checking if DB language is set
4510 $dbPageLanguage = $this->getDbPageLanguageCode();
4511 if ( $dbPageLanguage ) {
4512 $pageLang = wfGetLangObj( $dbPageLanguage );
4513 $variant = $pageLang->getPreferredVariant();
4514 if ( $pageLang->getCode() !== $variant ) {
4515 $pageLang = Language
::factory( $variant );
4521 // @note Can't be cached persistently, depends on user settings.
4522 // @note ContentHandler::getPageViewLanguage() may need to load the
4523 // content to determine the page language!
4524 $contentHandler = ContentHandler
::getForTitle( $this );
4525 $pageLang = $contentHandler->getPageViewLanguage( $this );
4530 * Get a list of rendered edit notices for this page.
4532 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4533 * they will already be wrapped in paragraphs.
4536 * @param int $oldid Revision ID that's being edited
4539 public function getEditNotices( $oldid = 0 ) {
4542 // Optional notice for the entire namespace
4543 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4544 $msg = wfMessage( $editnotice_ns );
4545 if ( $msg->exists() ) {
4546 $html = $msg->parseAsBlock();
4547 // Edit notices may have complex logic, but output nothing (T91715)
4548 if ( trim( $html ) !== '' ) {
4549 $notices[$editnotice_ns] = Html
::rawElement(
4553 'mw-editnotice-namespace',
4554 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4561 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4562 // Optional notice for page itself and any parent page
4563 $editnotice_base = $editnotice_ns;
4564 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4565 $editnotice_base .= '-' . $part;
4566 $msg = wfMessage( $editnotice_base );
4567 if ( $msg->exists() ) {
4568 $html = $msg->parseAsBlock();
4569 if ( trim( $html ) !== '' ) {
4570 $notices[$editnotice_base] = Html
::rawElement(
4574 'mw-editnotice-base',
4575 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4583 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4584 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4585 $msg = wfMessage( $editnoticeText );
4586 if ( $msg->exists() ) {
4587 $html = $msg->parseAsBlock();
4588 if ( trim( $html ) !== '' ) {
4589 $notices[$editnoticeText] = Html
::rawElement(
4593 'mw-editnotice-page',
4594 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4602 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4609 public function __sleep() {
4617 'mDefaultNamespace',
4621 public function __wakeup() {
4622 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4623 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4624 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );