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 * @param TitleValue $titleValue Assumed to be safe.
250 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
254 public static function newFromTitleValue( TitleValue
$titleValue, $forceClone = '' ) {
255 return self
::newFromLinkTarget( $titleValue, $forceClone );
259 * Returns a Title given a LinkTarget.
260 * If the given LinkTarget is already a Title instance, that instance is returned,
261 * unless $forceClone is "clone". If $forceClone is "clone" and the given LinkTarget
262 * is already a Title instance, that instance is copied using the clone operator.
264 * @param LinkTarget $linkTarget Assumed to be safe.
265 * @param string $forceClone set to NEW_CLONE to ensure a fresh instance is returned.
269 public static function newFromLinkTarget( LinkTarget
$linkTarget, $forceClone = '' ) {
270 if ( $linkTarget instanceof Title
) {
271 // Special case if it's already a Title object
272 if ( $forceClone === self
::NEW_CLONE
) {
273 return clone $linkTarget;
278 return self
::makeTitle(
279 $linkTarget->getNamespace(),
280 $linkTarget->getText(),
281 $linkTarget->getFragment(),
282 $linkTarget->getInterwiki()
287 * Create a new Title from text, such as what one would find in a link. De-
288 * codes any HTML entities in the text.
290 * Title objects returned by this method are guaranteed to be valid, and
291 * thus return true from the isValid() method.
293 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
294 * It may instead be a cached instance created previously, with references to it remaining
297 * @param string|int|null $text The link text; spaces, prefixes, and an
298 * initial ':' indicating the main namespace are accepted.
299 * @param int $defaultNamespace The namespace to use if none is specified
300 * by a prefix. If you want to force a specific namespace even if
301 * $text might begin with a namespace prefix, use makeTitle() or
303 * @throws InvalidArgumentException
304 * @return Title|null Title or null on an error.
306 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
307 // DWIM: Integers can be passed in here when page titles are used as array keys.
308 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
309 throw new InvalidArgumentException( '$text must be a string.' );
311 if ( $text === null ) {
316 return self
::newFromTextThrow( (string)$text, $defaultNamespace );
317 } catch ( MalformedTitleException
$ex ) {
323 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
324 * rather than returning null.
326 * The exception subclasses encode detailed information about why the title is invalid.
328 * Title objects returned by this method are guaranteed to be valid, and
329 * thus return true from the isValid() method.
331 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
332 * It may instead be a cached instance created previously, with references to it remaining
335 * @see Title::newFromText
338 * @param string $text Title text to check
339 * @param int $defaultNamespace
340 * @throws MalformedTitleException If the title is invalid
343 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
344 if ( is_object( $text ) ) {
345 throw new MWException( '$text must be a string, given an object' );
346 } elseif ( $text === null ) {
347 // Legacy code relies on MalformedTitleException being thrown in this case
348 // (happens when URL with no title in it is parsed). TODO fix
349 throw new MalformedTitleException( 'title-invalid-empty' );
352 $titleCache = self
::getTitleCache();
354 // Wiki pages often contain multiple links to the same page.
355 // Title normalization and parsing can become expensive on pages with many
356 // links, so we can save a little time by caching them.
357 // In theory these are value objects and won't get changed...
358 if ( $defaultNamespace == NS_MAIN
) {
359 $t = $titleCache->get( $text );
365 // Convert things like é ā or 〗 into normalized (T16952) text
366 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
369 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
370 $t->mDefaultNamespace
= (int)$defaultNamespace;
372 $t->secureAndSplit();
373 if ( $defaultNamespace == NS_MAIN
) {
374 $titleCache->set( $text, $t );
380 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
382 * Example of wrong and broken code:
383 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
385 * Example of right code:
386 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
388 * Create a new Title from URL-encoded text. Ensures that
389 * the given title's length does not exceed the maximum.
391 * @param string $url The title, as might be taken from a URL
392 * @return Title|null The new object, or null on an error
394 public static function newFromURL( $url ) {
397 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
398 # but some URLs used it as a space replacement and they still come
399 # from some external search tools.
400 if ( strpos( self
::legalChars(), '+' ) === false ) {
401 $url = strtr( $url, '+', ' ' );
404 $t->mDbkeyform
= strtr( $url, ' ', '_' );
407 $t->secureAndSplit();
409 } catch ( MalformedTitleException
$ex ) {
415 * @return MapCacheLRU
417 private static function getTitleCache() {
418 if ( self
::$titleCache === null ) {
419 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
421 return self
::$titleCache;
425 * Returns a list of fields that are to be selected for initializing Title
426 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
427 * whether to include page_content_model.
431 protected static function getSelectFields() {
432 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
435 'page_namespace', 'page_title', 'page_id',
436 'page_len', 'page_is_redirect', 'page_latest',
439 if ( $wgContentHandlerUseDB ) {
440 $fields[] = 'page_content_model';
443 if ( $wgPageLanguageUseDB ) {
444 $fields[] = 'page_lang';
451 * Create a new Title from an article ID
453 * @param int $id The page_id corresponding to the Title to create
454 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
455 * @return Title|null The new object, or null on an error
457 public static function newFromID( $id, $flags = 0 ) {
458 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
459 $row = $db->selectRow(
461 self
::getSelectFields(),
462 [ 'page_id' => $id ],
465 if ( $row !== false ) {
466 $title = self
::newFromRow( $row );
475 * Make an array of titles from an array of IDs
477 * @param int[] $ids Array of IDs
478 * @return Title[] Array of Titles
480 public static function newFromIDs( $ids ) {
481 if ( !count( $ids ) ) {
484 $dbr = wfGetDB( DB_REPLICA
);
488 self
::getSelectFields(),
489 [ 'page_id' => $ids ],
494 foreach ( $res as $row ) {
495 $titles[] = self
::newFromRow( $row );
501 * Make a Title object from a DB row
503 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
504 * @return Title Corresponding Title
506 public static function newFromRow( $row ) {
507 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
508 $t->loadFromRow( $row );
513 * Load Title object fields from a DB row.
514 * If false is given, the title will be treated as non-existing.
516 * @param stdClass|bool $row Database row
518 public function loadFromRow( $row ) {
519 if ( $row ) { // page found
520 if ( isset( $row->page_id
) ) {
521 $this->mArticleID
= (int)$row->page_id
;
523 if ( isset( $row->page_len
) ) {
524 $this->mLength
= (int)$row->page_len
;
526 if ( isset( $row->page_is_redirect
) ) {
527 $this->mRedirect
= (bool)$row->page_is_redirect
;
529 if ( isset( $row->page_latest
) ) {
530 $this->mLatestID
= (int)$row->page_latest
;
532 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
533 $this->mContentModel
= (string)$row->page_content_model
;
534 } elseif ( !$this->mForcedContentModel
) {
535 $this->mContentModel
= false; # initialized lazily in getContentModel()
537 if ( isset( $row->page_lang
) ) {
538 $this->mDbPageLanguage
= (string)$row->page_lang
;
540 if ( isset( $row->page_restrictions
) ) {
541 $this->mOldRestrictions
= $row->page_restrictions
;
543 } else { // page not found
544 $this->mArticleID
= 0;
546 $this->mRedirect
= false;
547 $this->mLatestID
= 0;
548 if ( !$this->mForcedContentModel
) {
549 $this->mContentModel
= false; # initialized lazily in getContentModel()
555 * Create a new Title from a namespace index and a DB key.
557 * It's assumed that $ns and $title are safe, for instance when
558 * they came directly from the database or a special page name,
559 * not from user input.
561 * No validation is applied. For convenience, spaces are normalized
562 * to underscores, so that e.g. user_text fields can be used directly.
564 * @note This method may return Title objects that are "invalid"
565 * according to the isValid() method. This is usually caused by
566 * configuration changes: e.g. a namespace that was once defined is
567 * no longer configured, or a character that was once allowed in
568 * titles is now forbidden.
570 * @param int $ns The namespace of the article
571 * @param string $title The unprefixed database key form
572 * @param string $fragment The link fragment (after the "#")
573 * @param string $interwiki The interwiki prefix
574 * @return Title The new object
576 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
578 $t->mInterwiki
= $interwiki;
579 $t->mFragment
= $fragment;
580 $t->mNamespace
= $ns = (int)$ns;
581 $t->mDbkeyform
= strtr( $title, ' ', '_' );
582 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
583 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
584 $t->mTextform
= strtr( $title, '_', ' ' );
585 $t->mContentModel
= false; # initialized lazily in getContentModel()
590 * Create a new Title from a namespace index and a DB key.
591 * The parameters will be checked for validity, which is a bit slower
592 * than makeTitle() but safer for user-provided data.
594 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
595 * that is, they return true from the isValid() method. If no valid Title
596 * can be constructed from the input, this method returns null.
598 * @param int $ns The namespace of the article
599 * @param string $title Database key form
600 * @param string $fragment The link fragment (after the "#")
601 * @param string $interwiki Interwiki prefix
602 * @return Title|null The new object, or null on an error
604 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
605 // NOTE: ideally, this would just call makeTitle() and then isValid(),
606 // but presently, that means more overhead on a potential performance hotspot.
608 if ( !MWNamespace
::exists( $ns ) ) {
613 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
616 $t->secureAndSplit();
618 } catch ( MalformedTitleException
$ex ) {
624 * Create a new Title for the Main Page
626 * This uses the 'mainpage' interface message, which could be specified in
627 * `$wgForceUIMsgAsContentMsg`. If that is the case, then calling this method
628 * will use the user language, which would involve initialising the session
629 * via `RequestContext::getMain()->getLanguage()`. For session-less endpoints,
630 * be sure to pass in a MessageLocalizer (such as your own RequestContext,
631 * or ResourceloaderContext) to prevent an error.
633 * @note The Title instance returned by this method is not guaranteed to be a fresh instance.
634 * It may instead be a cached instance created previously, with references to it remaining
637 * @param MessageLocalizer|null $localizer An optional context to use (since 1.34)
640 public static function newMainPage( MessageLocalizer
$localizer = null ) {
642 $msg = $localizer->msg( 'mainpage' );
644 $msg = wfMessage( 'mainpage' );
647 $title = self
::newFromText( $msg->inContentLanguage()->text() );
649 // Every page renders at least one link to the Main Page (e.g. sidebar).
650 // If the localised value is invalid, don't produce fatal errors that
651 // would make the wiki inaccessible (and hard to fix the invalid message).
652 // Gracefully fallback...
654 $title = self
::newFromText( 'Main Page' );
660 * Get the prefixed DB key associated with an ID
662 * @param int $id The page_id of the article
663 * @return Title|null An object representing the article, or null if no such article was found
665 public static function nameOf( $id ) {
666 $dbr = wfGetDB( DB_REPLICA
);
668 $s = $dbr->selectRow(
670 [ 'page_namespace', 'page_title' ],
671 [ 'page_id' => $id ],
674 if ( $s === false ) {
678 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
683 * Get a regex character class describing the legal characters in a link
685 * @return string The list of characters, not delimited
687 public static function legalChars() {
688 global $wgLegalTitleChars;
689 return $wgLegalTitleChars;
693 * Utility method for converting a character sequence from bytes to Unicode.
695 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
696 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
698 * @param string $byteClass
701 public static function convertByteClassToUnicodeClass( $byteClass ) {
702 $length = strlen( $byteClass );
704 $x0 = $x1 = $x2 = '';
706 $d0 = $d1 = $d2 = '';
707 // Decoded integer codepoints
708 $ord0 = $ord1 = $ord2 = 0;
710 $r0 = $r1 = $r2 = '';
714 $allowUnicode = false;
715 for ( $pos = 0; $pos < $length; $pos++
) {
716 // Shift the queues down
725 // Load the current input token and decoded values
726 $inChar = $byteClass[$pos];
727 if ( $inChar == '\\' ) {
728 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
729 $x0 = $inChar . $m[0];
730 $d0 = chr( hexdec( $m[1] ) );
731 $pos +
= strlen( $m[0] );
732 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
733 $x0 = $inChar . $m[0];
734 $d0 = chr( octdec( $m[0] ) );
735 $pos +
= strlen( $m[0] );
736 } elseif ( $pos +
1 >= $length ) {
739 $d0 = $byteClass[$pos +
1];
747 // Load the current re-encoded value
748 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
749 $r0 = sprintf( '\x%02x', $ord0 );
750 } elseif ( $ord0 >= 0x80 ) {
751 // Allow unicode if a single high-bit character appears
752 $r0 = sprintf( '\x%02x', $ord0 );
753 $allowUnicode = true;
754 // @phan-suppress-next-line PhanParamSuspiciousOrder false positive
755 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
761 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
763 if ( $ord2 > $ord0 ) {
765 } elseif ( $ord0 >= 0x80 ) {
767 $allowUnicode = true;
768 if ( $ord2 < 0x80 ) {
769 // Keep the non-unicode section of the range
776 // Reset state to the initial value
777 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
778 } elseif ( $ord2 < 0x80 ) {
783 if ( $ord1 < 0x80 ) {
786 if ( $ord0 < 0x80 ) {
789 if ( $allowUnicode ) {
790 $out .= '\u0080-\uFFFF';
796 * Make a prefixed DB key from a DB key and a namespace index
798 * @param int $ns Numerical representation of the namespace
799 * @param string $title The DB key form the title
800 * @param string $fragment The link fragment (after the "#")
801 * @param string $interwiki The interwiki prefix
802 * @param bool $canonicalNamespace If true, use the canonical name for
803 * $ns instead of the localized version.
804 * @return string The prefixed form of the title
806 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
807 $canonicalNamespace = false
809 if ( $canonicalNamespace ) {
810 $namespace = MWNamespace
::getCanonicalName( $ns );
812 $namespace = MediaWikiServices
::getInstance()->getContentLanguage()->getNsText( $ns );
814 $name = $namespace == '' ?
$title : "$namespace:$title";
815 if ( strval( $interwiki ) != '' ) {
816 $name = "$interwiki:$name";
818 if ( strval( $fragment ) != '' ) {
819 $name .= '#' . $fragment;
825 * Callback for usort() to do title sorts by (namespace, title)
827 * @param LinkTarget $a
828 * @param LinkTarget $b
830 * @return int Result of string comparison, or namespace comparison
832 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
833 return $a->getNamespace() <=> $b->getNamespace()
834 ?
: strcmp( $a->getText(), $b->getText() );
838 * Returns true if the title is valid, false if it is invalid.
840 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
841 * Invalid titles may get returned from makeTitle(), and it may be useful to
842 * allow them to exist, e.g. in order to process log entries about pages in
843 * namespaces that belong to extensions that are no longer installed.
845 * @note This method is relatively expensive. When constructing Title
846 * objects that need to be valid, use an instantiator method that is guaranteed
847 * to return valid titles, such as makeTitleSafe() or newFromText().
851 public function isValid() {
852 if ( !MWNamespace
::exists( $this->mNamespace
) ) {
857 $parser = MediaWikiServices
::getInstance()->getTitleParser();
858 $parser->parseTitle( $this->mDbkeyform
, $this->mNamespace
);
860 } catch ( MalformedTitleException
$ex ) {
866 * Determine whether the object refers to a page within
867 * this project (either this wiki or a wiki with a local
868 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
870 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
872 public function isLocal() {
873 if ( $this->isExternal() ) {
874 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
876 return $iw->isLocal();
883 * Is this Title interwiki?
887 public function isExternal() {
888 return $this->mInterwiki
!== '';
892 * Get the interwiki prefix
894 * Use Title::isExternal to check if a interwiki is set
896 * @return string Interwiki prefix
898 public function getInterwiki() {
899 return $this->mInterwiki
;
903 * Was this a local interwiki link?
907 public function wasLocalInterwiki() {
908 return $this->mLocalInterwiki
;
912 * Determine whether the object refers to a page within
913 * this project and is transcludable.
915 * @return bool True if this is transcludable
917 public function isTrans() {
918 if ( !$this->isExternal() ) {
922 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
926 * Returns the DB name of the distant wiki which owns the object.
928 * @return string|false The DB name
930 public function getTransWikiID() {
931 if ( !$this->isExternal() ) {
935 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
939 * Get a TitleValue object representing this Title.
941 * @note Not all valid Titles have a corresponding valid TitleValue
942 * (e.g. TitleValues cannot represent page-local links that have a
943 * fragment but no title text).
945 * @return TitleValue|null
947 public function getTitleValue() {
948 if ( $this->mTitleValue
=== null ) {
950 $this->mTitleValue
= new TitleValue(
956 } catch ( InvalidArgumentException
$ex ) {
957 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
958 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
962 return $this->mTitleValue
;
966 * Get the text form (spaces not underscores) of the main part
968 * @return string Main part of the title
970 public function getText() {
971 return $this->mTextform
;
975 * Get the URL-encoded form of the main part
977 * @return string Main part of the title, URL-encoded
979 public function getPartialURL() {
980 return $this->mUrlform
;
984 * Get the main part with underscores
986 * @return string Main part of the title, with underscores
988 public function getDBkey() {
989 return $this->mDbkeyform
;
993 * Get the DB key with the initial letter case as specified by the user
994 * @deprecated since 1.33; please use Title::getDBKey() instead
996 * @return string DB key
998 function getUserCaseDBKey() {
999 if ( !is_null( $this->mUserCaseDBKey
) ) {
1000 return $this->mUserCaseDBKey
;
1002 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
1003 return $this->mDbkeyform
;
1008 * Get the namespace index, i.e. one of the NS_xxxx constants.
1010 * @return int Namespace index
1012 public function getNamespace() {
1013 return $this->mNamespace
;
1017 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
1019 * @todo Deprecate this in favor of SlotRecord::getModel()
1021 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
1022 * @return string Content model id
1024 public function getContentModel( $flags = 0 ) {
1025 if ( !$this->mForcedContentModel
1026 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
1027 && $this->getArticleID( $flags )
1029 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
1030 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1031 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1034 if ( !$this->mContentModel
) {
1035 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1038 return $this->mContentModel
;
1042 * Convenience method for checking a title's content model name
1044 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1045 * @return bool True if $this->getContentModel() == $id
1047 public function hasContentModel( $id ) {
1048 return $this->getContentModel() == $id;
1052 * Set a proposed content model for the page for permissions
1053 * checking. This does not actually change the content model
1056 * Additionally, you should make sure you've checked
1057 * ContentHandler::canBeUsedOn() first.
1060 * @param string $model CONTENT_MODEL_XXX constant
1062 public function setContentModel( $model ) {
1063 $this->mContentModel
= $model;
1064 $this->mForcedContentModel
= true;
1068 * Get the namespace text
1070 * @return string|false Namespace text
1072 public function getNsText() {
1073 if ( $this->isExternal() ) {
1074 // This probably shouldn't even happen, except for interwiki transclusion.
1075 // If possible, use the canonical name for the foreign namespace.
1076 $nsText = MWNamespace
::getCanonicalName( $this->mNamespace
);
1077 if ( $nsText !== false ) {
1083 $formatter = self
::getTitleFormatter();
1084 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1085 } catch ( InvalidArgumentException
$ex ) {
1086 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1092 * Get the namespace text of the subject (rather than talk) page
1094 * @return string Namespace text
1096 public function getSubjectNsText() {
1097 return MediaWikiServices
::getInstance()->getContentLanguage()->
1098 getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1102 * Get the namespace text of the talk page
1104 * @return string Namespace text
1106 public function getTalkNsText() {
1107 return MediaWikiServices
::getInstance()->getContentLanguage()->
1108 getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1112 * Can this title have a corresponding talk page?
1114 * @see MWNamespace::hasTalkNamespace
1117 * @return bool True if this title either is a talk page or can have a talk page associated.
1119 public function canHaveTalkPage() {
1120 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1124 * Is this in a namespace that allows actual pages?
1128 public function canExist() {
1129 return $this->mNamespace
>= NS_MAIN
;
1133 * Can this title be added to a user's watchlist?
1137 public function isWatchable() {
1138 return !$this->isExternal() && MWNamespace
::isWatchable( $this->mNamespace
);
1142 * Returns true if this is a special page.
1146 public function isSpecialPage() {
1147 return $this->mNamespace
== NS_SPECIAL
;
1151 * Returns true if this title resolves to the named special page
1153 * @param string $name The special page name
1156 public function isSpecial( $name ) {
1157 if ( $this->isSpecialPage() ) {
1158 list( $thisName, /* $subpage */ ) =
1159 MediaWikiServices
::getInstance()->getSpecialPageFactory()->
1160 resolveAlias( $this->mDbkeyform
);
1161 if ( $name == $thisName ) {
1169 * If the Title refers to a special page alias which is not the local default, resolve
1170 * the alias, and localise the name as necessary. Otherwise, return $this
1174 public function fixSpecialName() {
1175 if ( $this->isSpecialPage() ) {
1176 $spFactory = MediaWikiServices
::getInstance()->getSpecialPageFactory();
1177 list( $canonicalName, $par ) = $spFactory->resolveAlias( $this->mDbkeyform
);
1178 if ( $canonicalName ) {
1179 $localName = $spFactory->getLocalNameFor( $canonicalName, $par );
1180 if ( $localName != $this->mDbkeyform
) {
1181 return self
::makeTitle( NS_SPECIAL
, $localName );
1189 * Returns true if the title is inside the specified namespace.
1191 * Please make use of this instead of comparing to getNamespace()
1192 * This function is much more resistant to changes we may make
1193 * to namespaces than code that makes direct comparisons.
1194 * @param int $ns The namespace
1198 public function inNamespace( $ns ) {
1199 return MWNamespace
::equals( $this->mNamespace
, $ns );
1203 * Returns true if the title is inside one of the specified namespaces.
1205 * @param int|int[] $namespaces,... The namespaces to check for
1209 public function inNamespaces( /* ... */ ) {
1210 $namespaces = func_get_args();
1211 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1212 $namespaces = $namespaces[0];
1215 foreach ( $namespaces as $ns ) {
1216 if ( $this->inNamespace( $ns ) ) {
1225 * Returns true if the title has the same subject namespace as the
1226 * namespace specified.
1227 * For example this method will take NS_USER and return true if namespace
1228 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1229 * as their subject namespace.
1231 * This is MUCH simpler than individually testing for equivalence
1232 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1237 public function hasSubjectNamespace( $ns ) {
1238 return MWNamespace
::subjectEquals( $this->mNamespace
, $ns );
1242 * Is this Title in a namespace which contains content?
1243 * In other words, is this a content page, for the purposes of calculating
1248 public function isContentPage() {
1249 return MWNamespace
::isContent( $this->mNamespace
);
1253 * Would anybody with sufficient privileges be able to move this page?
1254 * Some pages just aren't movable.
1258 public function isMovable() {
1259 if ( !MWNamespace
::isMovable( $this->mNamespace
) ||
$this->isExternal() ) {
1260 // Interwiki title or immovable namespace. Hooks don't get to override here
1265 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1270 * Is this the mainpage?
1271 * @note Title::newFromText seems to be sufficiently optimized by the title
1272 * cache that we don't need to over-optimize by doing direct comparisons and
1273 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1274 * ends up reporting something differently than $title->isMainPage();
1279 public function isMainPage() {
1280 return $this->equals( self
::newMainPage() );
1284 * Is this a subpage?
1288 public function isSubpage() {
1289 return MWNamespace
::hasSubpages( $this->mNamespace
)
1290 ?
strpos( $this->getText(), '/' ) !== false
1295 * Is this a conversion table for the LanguageConverter?
1299 public function isConversionTable() {
1300 // @todo ConversionTable should become a separate content model.
1302 return $this->mNamespace
== NS_MEDIAWIKI
&&
1303 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1307 * Does that page contain wikitext, or it is JS, CSS or whatever?
1311 public function isWikitextPage() {
1312 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1316 * Could this MediaWiki namespace page contain custom CSS, JSON, or JavaScript for the
1317 * global UI. This is generally true for pages in the MediaWiki namespace having
1318 * CONTENT_MODEL_CSS, CONTENT_MODEL_JSON, or CONTENT_MODEL_JAVASCRIPT.
1320 * This method does *not* return true for per-user JS/JSON/CSS. Use isUserConfigPage()
1323 * Note that this method should not return true for pages that contain and show
1324 * "inactive" CSS, JSON, or JS.
1329 public function isSiteConfigPage() {
1331 $this->isSiteCssConfigPage()
1332 ||
$this->isSiteJsonConfigPage()
1333 ||
$this->isSiteJsConfigPage()
1338 * Is this a "config" (.css, .json, or .js) sub-page of a user page?
1343 public function isUserConfigPage() {
1345 $this->isUserCssConfigPage()
1346 ||
$this->isUserJsonConfigPage()
1347 ||
$this->isUserJsConfigPage()
1352 * Trim down a .css, .json, or .js subpage title to get the corresponding skin name
1354 * @return string Containing skin name from .css, .json, or .js subpage title
1357 public function getSkinFromConfigSubpage() {
1358 $subpage = explode( '/', $this->mTextform
);
1359 $subpage = $subpage[count( $subpage ) - 1];
1360 $lastdot = strrpos( $subpage, '.' );
1361 if ( $lastdot === false ) {
1362 return $subpage; # Never happens: only called for names ending in '.css'/'.json'/'.js'
1364 return substr( $subpage, 0, $lastdot );
1368 * Is this a CSS "config" sub-page of a user page?
1373 public function isUserCssConfigPage() {
1375 NS_USER
== $this->mNamespace
1376 && $this->isSubpage()
1377 && $this->hasContentModel( CONTENT_MODEL_CSS
)
1382 * Is this a JSON "config" sub-page of a user page?
1387 public function isUserJsonConfigPage() {
1389 NS_USER
== $this->mNamespace
1390 && $this->isSubpage()
1391 && $this->hasContentModel( CONTENT_MODEL_JSON
)
1396 * Is this a JS "config" sub-page of a user page?
1401 public function isUserJsConfigPage() {
1403 NS_USER
== $this->mNamespace
1404 && $this->isSubpage()
1405 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1410 * Is this a sitewide CSS "config" page?
1415 public function isSiteCssConfigPage() {
1417 NS_MEDIAWIKI
== $this->mNamespace
1419 $this->hasContentModel( CONTENT_MODEL_CSS
)
1420 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1421 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1422 ||
substr( $this->mDbkeyform
, -4 ) === '.css'
1428 * Is this a sitewide JSON "config" page?
1433 public function isSiteJsonConfigPage() {
1435 NS_MEDIAWIKI
== $this->mNamespace
1437 $this->hasContentModel( CONTENT_MODEL_JSON
)
1438 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1439 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1440 ||
substr( $this->mDbkeyform
, -5 ) === '.json'
1446 * Is this a sitewide JS "config" page?
1451 public function isSiteJsConfigPage() {
1453 NS_MEDIAWIKI
== $this->mNamespace
1455 $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
)
1456 // paranoia - a MediaWiki: namespace page with mismatching extension and content
1457 // model is probably by mistake and might get handled incorrectly (see e.g. T112937)
1458 ||
substr( $this->mDbkeyform
, -3 ) === '.js'
1464 * Is this a message which can contain raw HTML?
1469 public function isRawHtmlMessage() {
1470 global $wgRawHtmlMessages;
1472 if ( !$this->inNamespace( NS_MEDIAWIKI
) ) {
1475 $message = lcfirst( $this->getRootTitle()->getDBkey() );
1476 return in_array( $message, $wgRawHtmlMessages, true );
1480 * Is this a talk page of some sort?
1484 public function isTalkPage() {
1485 return MWNamespace
::isTalk( $this->mNamespace
);
1489 * Get a Title object associated with the talk page of this article
1491 * @return Title The object for the talk page
1493 public function getTalkPage() {
1494 return self
::makeTitle( MWNamespace
::getTalk( $this->mNamespace
), $this->mDbkeyform
);
1498 * Get a Title object associated with the talk page of this article,
1499 * if such a talk page can exist.
1503 * @return Title|null The object for the talk page,
1504 * or null if no associated talk page can exist, according to canHaveTalkPage().
1506 public function getTalkPageIfDefined() {
1507 if ( !$this->canHaveTalkPage() ) {
1511 return $this->getTalkPage();
1515 * Get a title object associated with the subject page of this
1518 * @return Title The object for the subject page
1520 public function getSubjectPage() {
1521 // Is this the same title?
1522 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
1523 if ( $this->mNamespace
== $subjectNS ) {
1526 return self
::makeTitle( $subjectNS, $this->mDbkeyform
);
1530 * Get the other title for this page, if this is a subject page
1531 * get the talk page, if it is a subject page get the talk page
1534 * @throws MWException If the page doesn't have an other page
1537 public function getOtherPage() {
1538 if ( $this->isSpecialPage() ) {
1539 throw new MWException( 'Special pages cannot have other pages' );
1541 if ( $this->isTalkPage() ) {
1542 return $this->getSubjectPage();
1544 if ( !$this->canHaveTalkPage() ) {
1545 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1547 return $this->getTalkPage();
1552 * Get the default namespace index, for when there is no namespace
1554 * @return int Default namespace index
1556 public function getDefaultNamespace() {
1557 return $this->mDefaultNamespace
;
1561 * Get the Title fragment (i.e.\ the bit after the #) in text form
1563 * Use Title::hasFragment to check for a fragment
1565 * @return string Title fragment
1567 public function getFragment() {
1568 return $this->mFragment
;
1572 * Check if a Title fragment is set
1577 public function hasFragment() {
1578 return $this->mFragment
!== '';
1582 * Get the fragment in URL form, including the "#" character if there is one
1584 * @return string Fragment in URL form
1586 public function getFragmentForURL() {
1587 if ( !$this->hasFragment() ) {
1589 } elseif ( $this->isExternal() ) {
1590 // Note: If the interwiki is unknown, it's treated as a namespace on the local wiki,
1591 // so we treat it like a local interwiki.
1592 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1593 if ( $interwiki && !$interwiki->isLocal() ) {
1594 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->mFragment
);
1598 return '#' . Sanitizer
::escapeIdForLink( $this->mFragment
);
1602 * Set the fragment for this title. Removes the first character from the
1603 * specified fragment before setting, so it assumes you're passing it with
1606 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1607 * or Title::createFragmentTarget().
1608 * Still in active use privately.
1611 * @param string $fragment Text
1613 public function setFragment( $fragment ) {
1614 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1618 * Creates a new Title for a different fragment of the same page.
1621 * @param string $fragment
1624 public function createFragmentTarget( $fragment ) {
1625 return self
::makeTitle(
1634 * Prefix some arbitrary text with the namespace or interwiki prefix
1637 * @param string $name The text
1638 * @return string The prefixed text
1640 private function prefix( $name ) {
1642 if ( $this->isExternal() ) {
1643 $p = $this->mInterwiki
. ':';
1646 if ( $this->mNamespace
!= 0 ) {
1647 $nsText = $this->getNsText();
1649 if ( $nsText === false ) {
1650 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1651 $nsText = MediaWikiServices
::getInstance()->getContentLanguage()->
1652 getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1655 $p .= $nsText . ':';
1661 * Get the prefixed database key form
1663 * @return string The prefixed title, with underscores and
1664 * any interwiki and namespace prefixes
1666 public function getPrefixedDBkey() {
1667 $s = $this->prefix( $this->mDbkeyform
);
1668 $s = strtr( $s, ' ', '_' );
1673 * Get the prefixed title with spaces.
1674 * This is the form usually used for display
1676 * @return string The prefixed title, with spaces
1678 public function getPrefixedText() {
1679 if ( $this->prefixedText
=== null ) {
1680 $s = $this->prefix( $this->mTextform
);
1681 $s = strtr( $s, '_', ' ' );
1682 $this->prefixedText
= $s;
1684 return $this->prefixedText
;
1688 * Return a string representation of this title
1690 * @return string Representation of this title
1692 public function __toString() {
1693 return $this->getPrefixedText();
1697 * Get the prefixed title with spaces, plus any fragment
1698 * (part beginning with '#')
1700 * @return string The prefixed title, with spaces and the fragment, including '#'
1702 public function getFullText() {
1703 $text = $this->getPrefixedText();
1704 if ( $this->hasFragment() ) {
1705 $text .= '#' . $this->mFragment
;
1711 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1715 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1719 * @return string Root name
1722 public function getRootText() {
1723 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1724 return $this->getText();
1727 return strtok( $this->getText(), '/' );
1731 * Get the root page name title, i.e. the leftmost part before any slashes
1735 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1736 * # returns: Title{User:Foo}
1739 * @return Title Root title
1742 public function getRootTitle() {
1743 return self
::makeTitle( $this->mNamespace
, $this->getRootText() );
1747 * Get the base page name without a namespace, i.e. the part before the subpage name
1751 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1752 * # returns: 'Foo/Bar'
1755 * @return string Base name
1757 public function getBaseText() {
1758 $text = $this->getText();
1759 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1763 $lastSlashPos = strrpos( $text, '/' );
1764 // Don't discard the real title if there's no subpage involved
1765 if ( $lastSlashPos === false ) {
1769 return substr( $text, 0, $lastSlashPos );
1773 * Get the base page name title, i.e. the part before the subpage name
1777 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1778 * # returns: Title{User:Foo/Bar}
1781 * @return Title Base title
1784 public function getBaseTitle() {
1785 return self
::makeTitle( $this->mNamespace
, $this->getBaseText() );
1789 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1793 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1797 * @return string Subpage name
1799 public function getSubpageText() {
1800 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1801 return $this->mTextform
;
1803 $parts = explode( '/', $this->mTextform
);
1804 return $parts[count( $parts ) - 1];
1808 * Get the title for a subpage of the current page
1812 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1813 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1816 * @param string $text The subpage name to add to the title
1817 * @return Title|null Subpage title, or null on an error
1820 public function getSubpage( $text ) {
1821 return self
::makeTitleSafe( $this->mNamespace
, $this->getText() . '/' . $text );
1825 * Get a URL-encoded form of the subpage text
1827 * @return string URL-encoded subpage name
1829 public function getSubpageUrlForm() {
1830 $text = $this->getSubpageText();
1831 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1836 * Get a URL-encoded title (not an actual URL) including interwiki
1838 * @return string The URL-encoded form
1840 public function getPrefixedURL() {
1841 $s = $this->prefix( $this->mDbkeyform
);
1842 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1847 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1848 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1849 * second argument named variant. This was deprecated in favor
1850 * of passing an array of option with a "variant" key
1851 * Once $query2 is removed for good, this helper can be dropped
1852 * and the wfArrayToCgi moved to getLocalURL();
1854 * @since 1.19 (r105919)
1855 * @param array|string $query
1856 * @param string|string[]|bool $query2
1859 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1860 if ( $query2 !== false ) {
1861 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1862 "method called with a second parameter is deprecated. Add your " .
1863 "parameter to an array passed as the first parameter.", "1.19" );
1865 if ( is_array( $query ) ) {
1866 $query = wfArrayToCgi( $query );
1869 if ( is_string( $query2 ) ) {
1870 // $query2 is a string, we will consider this to be
1871 // a deprecated $variant argument and add it to the query
1872 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1874 $query2 = wfArrayToCgi( $query2 );
1876 // If we have $query content add a & to it first
1880 // Now append the queries together
1887 * Get a real URL referring to this title, with interwiki link and
1890 * @see self::getLocalURL for the arguments.
1892 * @param string|string[] $query
1893 * @param string|string[]|bool $query2
1894 * @param string|int|null $proto Protocol type to use in URL
1895 * @return string The URL
1897 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1898 $query = self
::fixUrlQueryArgs( $query, $query2 );
1900 # Hand off all the decisions on urls to getLocalURL
1901 $url = $this->getLocalURL( $query );
1903 # Expand the url to make it a full url. Note that getLocalURL has the
1904 # potential to output full urls for a variety of reasons, so we use
1905 # wfExpandUrl instead of simply prepending $wgServer
1906 $url = wfExpandUrl( $url, $proto );
1908 # Finally, add the fragment.
1909 $url .= $this->getFragmentForURL();
1910 // Avoid PHP 7.1 warning from passing $this by reference
1912 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1917 * Get a url appropriate for making redirects based on an untrusted url arg
1919 * This is basically the same as getFullUrl(), but in the case of external
1920 * interwikis, we send the user to a landing page, to prevent possible
1921 * phishing attacks and the like.
1923 * @note Uses current protocol by default, since technically relative urls
1924 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1925 * places where the url gets cached, as might pollute between
1926 * https and non-https users.
1927 * @see self::getLocalURL for the arguments.
1928 * @param array|string $query
1929 * @param string $proto Protocol type to use in URL
1930 * @return string A url suitable to use in an HTTP location header.
1932 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1934 if ( $this->isExternal() ) {
1935 $target = SpecialPage
::getTitleFor(
1937 $this->getPrefixedDBkey()
1940 return $target->getFullURL( $query, false, $proto );
1944 * Get a URL with no fragment or server name (relative URL) from a Title object.
1945 * If this page is generated with action=render, however,
1946 * $wgServer is prepended to make an absolute URL.
1948 * @see self::getFullURL to always get an absolute URL.
1949 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1950 * valid to link, locally, to the current Title.
1951 * @see self::newFromText to produce a Title object.
1953 * @param string|string[] $query An optional query string,
1954 * not used for interwiki links. Can be specified as an associative array as well,
1955 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1956 * Some query patterns will trigger various shorturl path replacements.
1957 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1958 * be an array. If a string is passed it will be interpreted as a deprecated
1959 * variant argument and urlencoded into a variant= argument.
1960 * This second query argument will be added to the $query
1961 * The second parameter is deprecated since 1.19. Pass it as a key,value
1962 * pair in the first parameter array instead.
1964 * @return string String of the URL.
1966 public function getLocalURL( $query = '', $query2 = false ) {
1967 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1969 $query = self
::fixUrlQueryArgs( $query, $query2 );
1971 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1973 $namespace = $this->getNsText();
1974 if ( $namespace != '' ) {
1975 # Can this actually happen? Interwikis shouldn't be parsed.
1976 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1979 $url = $interwiki->getURL( $namespace . $this->mDbkeyform
);
1980 $url = wfAppendQuery( $url, $query );
1982 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1983 if ( $query == '' ) {
1984 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1985 // Avoid PHP 7.1 warning from passing $this by reference
1987 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1989 global $wgVariantArticlePath, $wgActionPaths;
1993 if ( !empty( $wgActionPaths )
1994 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1996 $action = urldecode( $matches[2] );
1997 if ( isset( $wgActionPaths[$action] ) ) {
1998 $query = $matches[1];
1999 if ( isset( $matches[4] ) ) {
2000 $query .= $matches[4];
2002 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
2003 if ( $query != '' ) {
2004 $url = wfAppendQuery( $url, $query );
2010 && $wgVariantArticlePath
2011 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
2012 && $this->getPageLanguage()->equals(
2013 MediaWikiServices
::getInstance()->getContentLanguage() )
2014 && $this->getPageLanguage()->hasVariants()
2016 $variant = urldecode( $matches[1] );
2017 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
2018 // Only do the variant replacement if the given variant is a valid
2019 // variant for the page's language.
2020 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
2021 $url = str_replace( '$1', $dbkey, $url );
2025 if ( $url === false ) {
2026 if ( $query == '-' ) {
2029 $url = "{$wgScript}?title={$dbkey}&{$query}";
2032 // Avoid PHP 7.1 warning from passing $this by reference
2034 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
2036 // @todo FIXME: This causes breakage in various places when we
2037 // actually expected a local URL and end up with dupe prefixes.
2038 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
2039 $url = $wgServer . $url;
2042 // Avoid PHP 7.1 warning from passing $this by reference
2044 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
2049 * Get a URL that's the simplest URL that will be valid to link, locally,
2050 * to the current Title. It includes the fragment, but does not include
2051 * the server unless action=render is used (or the link is external). If
2052 * there's a fragment but the prefixed text is empty, we just return a link
2055 * The result obviously should not be URL-escaped, but does need to be
2056 * HTML-escaped if it's being output in HTML.
2058 * @param string|string[] $query
2059 * @param bool $query2
2060 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
2061 * or false (default) for no expansion
2062 * @see self::getLocalURL for the arguments.
2063 * @return string The URL
2065 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
2066 if ( $this->isExternal() ||
$proto !== false ) {
2067 $ret = $this->getFullURL( $query, $query2, $proto );
2068 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
2069 $ret = $this->getFragmentForURL();
2071 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
2077 * Get the URL form for an internal link.
2078 * - Used in various CDN-related code, in case we have a different
2079 * internal hostname for the server from the exposed one.
2081 * This uses $wgInternalServer to qualify the path, or $wgServer
2082 * if $wgInternalServer is not set. If the server variable used is
2083 * protocol-relative, the URL will be expanded to http://
2085 * @see self::getLocalURL for the arguments.
2086 * @param string|string[] $query
2087 * @param string|bool $query2 Deprecated
2088 * @return string The URL
2090 public function getInternalURL( $query = '', $query2 = false ) {
2091 global $wgInternalServer, $wgServer;
2092 $query = self
::fixUrlQueryArgs( $query, $query2 );
2093 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
2094 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
2095 // Avoid PHP 7.1 warning from passing $this by reference
2097 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
2102 * Get the URL for a canonical link, for use in things like IRC and
2103 * e-mail notifications. Uses $wgCanonicalServer and the
2104 * GetCanonicalURL hook.
2106 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
2108 * @see self::getLocalURL for the arguments.
2109 * @param string|string[] $query
2110 * @param string|bool $query2 Deprecated
2111 * @return string The URL
2114 public function getCanonicalURL( $query = '', $query2 = false ) {
2115 $query = self
::fixUrlQueryArgs( $query, $query2 );
2116 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
2117 // Avoid PHP 7.1 warning from passing $this by reference
2119 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2124 * Get the edit URL for this Title
2126 * @return string The URL, or a null string if this is an interwiki link
2128 public function getEditURL() {
2129 if ( $this->isExternal() ) {
2132 $s = $this->getLocalURL( 'action=edit' );
2138 * Can $user perform $action on this page?
2139 * This skips potentially expensive cascading permission checks
2140 * as well as avoids expensive error formatting
2142 * Suitable for use for nonessential UI controls in common cases, but
2143 * _not_ for functional access control.
2145 * May provide false positives, but should never provide a false negative.
2147 * @param string $action Action that permission needs to be checked for
2148 * @param User|null $user User to check (since 1.19); $wgUser will be used if not provided.
2153 * @deprecated since 1.33,
2154 * use MediaWikiServices::getInstance()->getPermissionManager()->quickUserCan(..) instead
2157 public function quickUserCan( $action, $user = null ) {
2158 return $this->userCan( $action, $user, false );
2162 * Can $user perform $action on this page?
2164 * @param string $action Action that permission needs to be checked for
2165 * @param User|null $user User to check (since 1.19); $wgUser will be used if not
2167 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2172 * @deprecated since 1.33,
2173 * use MediaWikiServices::getInstance()->getPermissionManager()->userCan(..) instead
2176 public function userCan( $action, $user = null, $rigor = PermissionManager
::RIGOR_SECURE
) {
2177 if ( !$user instanceof User
) {
2182 // TODO: this is for b/c, eventually will be removed
2183 if ( $rigor === true ) {
2184 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2185 } elseif ( $rigor === false ) {
2186 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2189 return MediaWikiServices
::getInstance()->getPermissionManager()
2190 ->userCan( $action, $user, $this, $rigor );
2194 * Can $user perform $action on this page?
2196 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2198 * @param string $action Action that permission needs to be checked for
2199 * @param User $user User to check
2200 * @param string $rigor One of (quick,full,secure)
2201 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2202 * - full : does cheap and expensive checks possibly from a replica DB
2203 * - secure : does cheap and expensive checks, using the master as needed
2204 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2205 * whose corresponding errors may be ignored.
2207 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2210 * @deprecated since 1.33,
2211 * use MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissionsErrors()
2214 public function getUserPermissionsErrors(
2215 $action, $user, $rigor = PermissionManager
::RIGOR_SECURE
, $ignoreErrors = []
2217 // TODO: this is for b/c, eventually will be removed
2218 if ( $rigor === true ) {
2219 $rigor = PermissionManager
::RIGOR_SECURE
; // b/c
2220 } elseif ( $rigor === false ) {
2221 $rigor = PermissionManager
::RIGOR_QUICK
; // b/c
2224 return MediaWikiServices
::getInstance()->getPermissionManager()
2225 ->getPermissionErrors( $action, $user, $this, $rigor, $ignoreErrors );
2229 * Add the resulting error code to the errors array
2231 * @param array $errors List of current errors
2232 * @param array $result Result of errors
2234 * @return array List of errors
2236 private function resultToError( $errors, $result ) {
2237 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2238 // A single array representing an error
2239 $errors[] = $result;
2240 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2241 // A nested array representing multiple errors
2242 $errors = array_merge( $errors, $result );
2243 } elseif ( $result !== '' && is_string( $result ) ) {
2244 // A string representing a message-id
2245 $errors[] = [ $result ];
2246 } elseif ( $result instanceof MessageSpecifier
) {
2247 // A message specifier representing an error
2248 $errors[] = [ $result ];
2249 } elseif ( $result === false ) {
2250 // a generic "We don't want them to do that"
2251 $errors[] = [ 'badaccess-group0' ];
2257 * Get a filtered list of all restriction types supported by this wiki.
2258 * @param bool $exists True to get all restriction types that apply to
2259 * titles that do exist, False for all restriction types that apply to
2260 * titles that do not exist
2263 public static function getFilteredRestrictionTypes( $exists = true ) {
2264 global $wgRestrictionTypes;
2265 $types = $wgRestrictionTypes;
2267 # Remove the create restriction for existing titles
2268 $types = array_diff( $types, [ 'create' ] );
2270 # Only the create and upload restrictions apply to non-existing titles
2271 $types = array_intersect( $types, [ 'create', 'upload' ] );
2277 * Returns restriction types for the current Title
2279 * @return array Applicable restriction types
2281 public function getRestrictionTypes() {
2282 if ( $this->isSpecialPage() ) {
2286 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2288 if ( $this->mNamespace
!= NS_FILE
) {
2289 # Remove the upload restriction for non-file titles
2290 $types = array_diff( $types, [ 'upload' ] );
2293 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2295 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2296 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2302 * Is this title subject to title protection?
2303 * Title protection is the one applied against creation of such title.
2305 * @return array|bool An associative array representing any existent title
2306 * protection, or false if there's none.
2308 public function getTitleProtection() {
2309 $protection = $this->getTitleProtectionInternal();
2310 if ( $protection ) {
2311 if ( $protection['permission'] == 'sysop' ) {
2312 $protection['permission'] = 'editprotected'; // B/C
2314 if ( $protection['permission'] == 'autoconfirmed' ) {
2315 $protection['permission'] = 'editsemiprotected'; // B/C
2322 * Fetch title protection settings
2324 * To work correctly, $this->loadRestrictions() needs to have access to the
2325 * actual protections in the database without munging 'sysop' =>
2326 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2327 * callers probably want $this->getTitleProtection() instead.
2329 * @return array|bool
2331 protected function getTitleProtectionInternal() {
2332 // Can't protect pages in special namespaces
2333 if ( $this->mNamespace
< 0 ) {
2337 // Can't protect pages that exist.
2338 if ( $this->exists() ) {
2342 if ( $this->mTitleProtection
=== null ) {
2343 $dbr = wfGetDB( DB_REPLICA
);
2344 $commentStore = CommentStore
::getStore();
2345 $commentQuery = $commentStore->getJoin( 'pt_reason' );
2346 $res = $dbr->select(
2347 [ 'protected_titles' ] +
$commentQuery['tables'],
2349 'user' => 'pt_user',
2350 'expiry' => 'pt_expiry',
2351 'permission' => 'pt_create_perm'
2352 ] +
$commentQuery['fields'],
2353 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2356 $commentQuery['joins']
2359 // fetchRow returns false if there are no rows.
2360 $row = $dbr->fetchRow( $res );
2362 $this->mTitleProtection
= [
2363 'user' => $row['user'],
2364 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2365 'permission' => $row['permission'],
2366 'reason' => $commentStore->getComment( 'pt_reason', $row )->text
,
2369 $this->mTitleProtection
= false;
2372 return $this->mTitleProtection
;
2376 * Remove any title protection due to page existing
2378 public function deleteTitleProtection() {
2379 $dbw = wfGetDB( DB_MASTER
);
2383 [ 'pt_namespace' => $this->mNamespace
, 'pt_title' => $this->mDbkeyform
],
2386 $this->mTitleProtection
= false;
2390 * Is this page "semi-protected" - the *only* protection levels are listed
2391 * in $wgSemiprotectedRestrictionLevels?
2393 * @param string $action Action to check (default: edit)
2396 public function isSemiProtected( $action = 'edit' ) {
2397 global $wgSemiprotectedRestrictionLevels;
2399 $restrictions = $this->getRestrictions( $action );
2400 $semi = $wgSemiprotectedRestrictionLevels;
2401 if ( !$restrictions ||
!$semi ) {
2402 // Not protected, or all protection is full protection
2406 // Remap autoconfirmed to editsemiprotected for BC
2407 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2408 $semi[$key] = 'editsemiprotected';
2410 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2411 $restrictions[$key] = 'editsemiprotected';
2414 return !array_diff( $restrictions, $semi );
2418 * Does the title correspond to a protected article?
2420 * @param string $action The action the page is protected from,
2421 * by default checks all actions.
2424 public function isProtected( $action = '' ) {
2425 global $wgRestrictionLevels;
2427 $restrictionTypes = $this->getRestrictionTypes();
2429 # Special pages have inherent protection
2430 if ( $this->isSpecialPage() ) {
2434 # Check regular protection levels
2435 foreach ( $restrictionTypes as $type ) {
2436 if ( $action == $type ||
$action == '' ) {
2437 $r = $this->getRestrictions( $type );
2438 foreach ( $wgRestrictionLevels as $level ) {
2439 if ( in_array( $level, $r ) && $level != '' ) {
2450 * Determines if $user is unable to edit this page because it has been protected
2451 * by $wgNamespaceProtection.
2453 * @param User $user User object to check permissions
2456 public function isNamespaceProtected( User
$user ) {
2457 global $wgNamespaceProtection;
2459 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2460 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2461 if ( $right != '' && !$user->isAllowed( $right ) ) {
2470 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2472 * @return bool If the page is subject to cascading restrictions.
2474 public function isCascadeProtected() {
2475 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2476 return ( $sources > 0 );
2480 * Determines whether cascading protection sources have already been loaded from
2483 * @param bool $getPages True to check if the pages are loaded, or false to check
2484 * if the status is loaded.
2485 * @return bool Whether or not the specified information has been loaded
2488 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2489 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2493 * Cascading protection: Get the source of any cascading restrictions on this page.
2495 * @param bool $getPages Whether or not to retrieve the actual pages
2496 * that the restrictions have come from and the actual restrictions
2498 * @return array Two elements: First is an array of Title objects of the
2499 * pages from which cascading restrictions have come, false for
2500 * none, or true if such restrictions exist but $getPages was not
2501 * set. Second is an array like that returned by
2502 * Title::getAllRestrictions(), or an empty array if $getPages is
2505 public function getCascadeProtectionSources( $getPages = true ) {
2506 $pagerestrictions = [];
2508 if ( $this->mCascadeSources
!== null && $getPages ) {
2509 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2510 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2511 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2514 $dbr = wfGetDB( DB_REPLICA
);
2516 if ( $this->mNamespace
== NS_FILE
) {
2517 $tables = [ 'imagelinks', 'page_restrictions' ];
2519 'il_to' => $this->mDbkeyform
,
2524 $tables = [ 'templatelinks', 'page_restrictions' ];
2526 'tl_namespace' => $this->mNamespace
,
2527 'tl_title' => $this->mDbkeyform
,
2534 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2535 'pr_expiry', 'pr_type', 'pr_level' ];
2536 $where_clauses[] = 'page_id=pr_page';
2539 $cols = [ 'pr_expiry' ];
2542 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2544 $sources = $getPages ?
[] : false;
2545 $now = wfTimestampNow();
2547 foreach ( $res as $row ) {
2548 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2549 if ( $expiry > $now ) {
2551 $page_id = $row->pr_page
;
2552 $page_ns = $row->page_namespace
;
2553 $page_title = $row->page_title
;
2554 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2555 # Add groups needed for each restriction type if its not already there
2556 # Make sure this restriction type still exists
2558 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2559 $pagerestrictions[$row->pr_type
] = [];
2563 isset( $pagerestrictions[$row->pr_type
] )
2564 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2566 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2575 $this->mCascadeSources
= $sources;
2576 $this->mCascadingRestrictions
= $pagerestrictions;
2578 $this->mHasCascadingRestrictions
= $sources;
2581 return [ $sources, $pagerestrictions ];
2585 * Accessor for mRestrictionsLoaded
2587 * @return bool Whether or not the page's restrictions have already been
2588 * loaded from the database
2591 public function areRestrictionsLoaded() {
2592 return $this->mRestrictionsLoaded
;
2596 * Accessor/initialisation for mRestrictions
2598 * @param string $action Action that permission needs to be checked for
2599 * @return array Restriction levels needed to take the action. All levels are
2600 * required. Note that restriction levels are normally user rights, but 'sysop'
2601 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2602 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2604 public function getRestrictions( $action ) {
2605 if ( !$this->mRestrictionsLoaded
) {
2606 $this->loadRestrictions();
2608 return $this->mRestrictions
[$action] ??
[];
2612 * Accessor/initialisation for mRestrictions
2614 * @return array Keys are actions, values are arrays as returned by
2615 * Title::getRestrictions()
2618 public function getAllRestrictions() {
2619 if ( !$this->mRestrictionsLoaded
) {
2620 $this->loadRestrictions();
2622 return $this->mRestrictions
;
2626 * Get the expiry time for the restriction against a given action
2628 * @param string $action
2629 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2630 * or not protected at all, or false if the action is not recognised.
2632 public function getRestrictionExpiry( $action ) {
2633 if ( !$this->mRestrictionsLoaded
) {
2634 $this->loadRestrictions();
2636 return $this->mRestrictionsExpiry
[$action] ??
false;
2640 * Returns cascading restrictions for the current article
2644 function areRestrictionsCascading() {
2645 if ( !$this->mRestrictionsLoaded
) {
2646 $this->loadRestrictions();
2649 return $this->mCascadeRestriction
;
2653 * Compiles list of active page restrictions from both page table (pre 1.10)
2654 * and page_restrictions table for this existing page.
2655 * Public for usage by LiquidThreads.
2657 * @param array $rows Array of db result objects
2658 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2659 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2660 * Edit and move sections are separated by a colon
2661 * Example: "edit=autoconfirmed,sysop:move=sysop"
2663 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2664 // This function will only read rows from a table that we migrated away
2665 // from before adding READ_LATEST support to loadRestrictions, so we
2666 // don't need to support reading from DB_MASTER here.
2667 $dbr = wfGetDB( DB_REPLICA
);
2669 $restrictionTypes = $this->getRestrictionTypes();
2671 foreach ( $restrictionTypes as $type ) {
2672 $this->mRestrictions
[$type] = [];
2673 $this->mRestrictionsExpiry
[$type] = 'infinity';
2676 $this->mCascadeRestriction
= false;
2678 # Backwards-compatibility: also load the restrictions from the page record (old format).
2679 if ( $oldFashionedRestrictions !== null ) {
2680 $this->mOldRestrictions
= $oldFashionedRestrictions;
2683 if ( $this->mOldRestrictions
=== false ) {
2684 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2685 $linkCache->addLinkObj( $this ); # in case we already had an article ID
2686 $this->mOldRestrictions
= $linkCache->getGoodLinkFieldObj( $this, 'restrictions' );
2689 if ( $this->mOldRestrictions
!= '' ) {
2690 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
2691 $temp = explode( '=', trim( $restrict ) );
2692 if ( count( $temp ) == 1 ) {
2693 // old old format should be treated as edit/move restriction
2694 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2695 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2697 $restriction = trim( $temp[1] );
2698 if ( $restriction != '' ) { // some old entries are empty
2699 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2705 if ( count( $rows ) ) {
2706 # Current system - load second to make them override.
2707 $now = wfTimestampNow();
2709 # Cycle through all the restrictions.
2710 foreach ( $rows as $row ) {
2711 // Don't take care of restrictions types that aren't allowed
2712 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2716 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2718 // Only apply the restrictions if they haven't expired!
2719 if ( !$expiry ||
$expiry > $now ) {
2720 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2721 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2723 $this->mCascadeRestriction |
= $row->pr_cascade
;
2728 $this->mRestrictionsLoaded
= true;
2732 * Load restrictions from the page_restrictions table
2734 * @param string|null $oldFashionedRestrictions Comma-separated set of permission keys
2735 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
2736 * Edit and move sections are separated by a colon
2737 * Example: "edit=autoconfirmed,sysop:move=sysop"
2738 * @param int $flags A bit field. If self::READ_LATEST is set, skip replicas and read
2739 * from the master DB.
2741 public function loadRestrictions( $oldFashionedRestrictions = null, $flags = 0 ) {
2742 $readLatest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
2743 if ( $this->mRestrictionsLoaded
&& !$readLatest ) {
2747 // TODO: should probably pass $flags into getArticleID, but it seems hacky
2748 // to mix READ_LATEST and GAID_FOR_UPDATE, even if they have the same value.
2749 // Maybe deprecate GAID_FOR_UPDATE now that we implement IDBAccessObject?
2750 $id = $this->getArticleID();
2752 $fname = __METHOD__
;
2753 $loadRestrictionsFromDb = function ( IDatabase
$dbr ) use ( $fname, $id ) {
2754 return iterator_to_array(
2756 'page_restrictions',
2757 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
2758 [ 'pr_page' => $id ],
2764 if ( $readLatest ) {
2765 $dbr = wfGetDB( DB_MASTER
);
2766 $rows = $loadRestrictionsFromDb( $dbr );
2768 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2769 $rows = $cache->getWithSetCallback(
2770 // Page protections always leave a new null revision
2771 $cache->makeKey( 'page-restrictions', 'v1', $id, $this->getLatestRevID() ),
2773 function ( $curValue, &$ttl, array &$setOpts ) use ( $loadRestrictionsFromDb ) {
2774 $dbr = wfGetDB( DB_REPLICA
);
2776 $setOpts +
= Database
::getCacheSetOptions( $dbr );
2777 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2778 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2779 // @TODO: cleanup Title cache and caller assumption mess in general
2780 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2783 return $loadRestrictionsFromDb( $dbr );
2788 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2790 $title_protection = $this->getTitleProtectionInternal();
2792 if ( $title_protection ) {
2793 $now = wfTimestampNow();
2794 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
2796 if ( !$expiry ||
$expiry > $now ) {
2797 // Apply the restrictions
2798 $this->mRestrictionsExpiry
['create'] = $expiry;
2799 $this->mRestrictions
['create'] =
2800 explode( ',', trim( $title_protection['permission'] ) );
2801 } else { // Get rid of the old restrictions
2802 $this->mTitleProtection
= false;
2805 $this->mRestrictionsExpiry
['create'] = 'infinity';
2807 $this->mRestrictionsLoaded
= true;
2812 * Flush the protection cache in this object and force reload from the database.
2813 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2815 public function flushRestrictions() {
2816 $this->mRestrictionsLoaded
= false;
2817 $this->mTitleProtection
= null;
2821 * Purge expired restrictions from the page_restrictions table
2823 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
2825 static function purgeExpiredRestrictions() {
2826 if ( wfReadOnly() ) {
2830 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2831 wfGetDB( DB_MASTER
),
2833 function ( IDatabase
$dbw, $fname ) {
2834 $config = MediaWikiServices
::getInstance()->getMainConfig();
2835 $ids = $dbw->selectFieldValues(
2836 'page_restrictions',
2838 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2840 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
2843 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
2848 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
2849 wfGetDB( DB_MASTER
),
2851 function ( IDatabase
$dbw, $fname ) {
2854 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
2862 * Does this have subpages? (Warning, usually requires an extra DB query.)
2866 public function hasSubpages() {
2867 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2872 # We dynamically add a member variable for the purpose of this method
2873 # alone to cache the result. There's no point in having it hanging
2874 # around uninitialized in every Title object; therefore we only add it
2875 # if needed and don't declare it statically.
2876 if ( $this->mHasSubpages
=== null ) {
2877 $this->mHasSubpages
= false;
2878 $subpages = $this->getSubpages( 1 );
2879 if ( $subpages instanceof TitleArray
) {
2880 $this->mHasSubpages
= (bool)$subpages->count();
2884 return $this->mHasSubpages
;
2888 * Get all subpages of this page.
2890 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
2891 * @return TitleArray|array TitleArray, or empty array if this page's namespace
2892 * doesn't allow subpages
2894 public function getSubpages( $limit = -1 ) {
2895 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2899 $dbr = wfGetDB( DB_REPLICA
);
2900 $conds['page_namespace'] = $this->mNamespace
;
2901 $conds[] = 'page_title ' . $dbr->buildLike( $this->mDbkeyform
. '/', $dbr->anyString() );
2903 if ( $limit > -1 ) {
2904 $options['LIMIT'] = $limit;
2906 return TitleArray
::newFromResult(
2907 $dbr->select( 'page',
2908 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
2917 * Is there a version of this page in the deletion archive?
2919 * @return int The number of archived revisions
2921 public function isDeleted() {
2922 if ( $this->mNamespace
< 0 ) {
2925 $dbr = wfGetDB( DB_REPLICA
);
2927 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2928 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2931 if ( $this->mNamespace
== NS_FILE
) {
2932 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2933 [ 'fa_name' => $this->mDbkeyform
],
2942 * Is there a version of this page in the deletion archive?
2946 public function isDeletedQuick() {
2947 if ( $this->mNamespace
< 0 ) {
2950 $dbr = wfGetDB( DB_REPLICA
);
2951 $deleted = (bool)$dbr->selectField( 'archive', '1',
2952 [ 'ar_namespace' => $this->mNamespace
, 'ar_title' => $this->mDbkeyform
],
2955 if ( !$deleted && $this->mNamespace
== NS_FILE
) {
2956 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2957 [ 'fa_name' => $this->mDbkeyform
],
2965 * Get the article ID for this Title from the link cache,
2966 * adding it if necessary
2968 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
2970 * @return int The ID
2972 public function getArticleID( $flags = 0 ) {
2973 if ( $this->mNamespace
< 0 ) {
2974 $this->mArticleID
= 0;
2975 return $this->mArticleID
;
2977 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
2978 if ( $flags & self
::GAID_FOR_UPDATE
) {
2979 $oldUpdate = $linkCache->forUpdate( true );
2980 $linkCache->clearLink( $this );
2981 $this->mArticleID
= $linkCache->addLinkObj( $this );
2982 $linkCache->forUpdate( $oldUpdate );
2983 } elseif ( $this->mArticleID
== -1 ) {
2984 $this->mArticleID
= $linkCache->addLinkObj( $this );
2986 return $this->mArticleID
;
2990 * Is this an article that is a redirect page?
2991 * Uses link cache, adding it if necessary
2993 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
2996 public function isRedirect( $flags = 0 ) {
2997 if ( !is_null( $this->mRedirect
) ) {
2998 return $this->mRedirect
;
3000 if ( !$this->getArticleID( $flags ) ) {
3001 $this->mRedirect
= false;
3002 return $this->mRedirect
;
3005 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3006 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3007 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3008 if ( $cached === null ) {
3009 # Trust LinkCache's state over our own
3010 # LinkCache is telling us that the page doesn't exist, despite there being cached
3011 # data relating to an existing page in $this->mArticleID. Updaters should clear
3012 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3013 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3014 # LinkCache to refresh its data from the master.
3015 $this->mRedirect
= false;
3016 return $this->mRedirect
;
3019 $this->mRedirect
= (bool)$cached;
3021 return $this->mRedirect
;
3025 * What is the length of this page?
3026 * Uses link cache, adding it if necessary
3028 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3031 public function getLength( $flags = 0 ) {
3032 if ( $this->mLength
!= -1 ) {
3033 return $this->mLength
;
3035 if ( !$this->getArticleID( $flags ) ) {
3037 return $this->mLength
;
3039 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3040 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3041 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3042 if ( $cached === null ) {
3043 # Trust LinkCache's state over our own, as for isRedirect()
3045 return $this->mLength
;
3048 $this->mLength
= intval( $cached );
3050 return $this->mLength
;
3054 * What is the page_latest field for this page?
3056 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3057 * @return int Int or 0 if the page doesn't exist
3059 public function getLatestRevID( $flags = 0 ) {
3060 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3061 return intval( $this->mLatestID
);
3063 if ( !$this->getArticleID( $flags ) ) {
3064 $this->mLatestID
= 0;
3065 return $this->mLatestID
;
3067 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3068 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3069 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3070 if ( $cached === null ) {
3071 # Trust LinkCache's state over our own, as for isRedirect()
3072 $this->mLatestID
= 0;
3073 return $this->mLatestID
;
3076 $this->mLatestID
= intval( $cached );
3078 return $this->mLatestID
;
3082 * This clears some fields in this object, and clears any associated
3083 * keys in the "bad links" section of the link cache.
3085 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3086 * loading of the new page_id. It's also called from
3087 * WikiPage::doDeleteArticleReal()
3089 * @param int $newid The new Article ID
3091 public function resetArticleID( $newid ) {
3092 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3093 $linkCache->clearLink( $this );
3095 if ( $newid === false ) {
3096 $this->mArticleID
= -1;
3098 $this->mArticleID
= intval( $newid );
3100 $this->mRestrictionsLoaded
= false;
3101 $this->mRestrictions
= [];
3102 $this->mOldRestrictions
= false;
3103 $this->mRedirect
= null;
3104 $this->mLength
= -1;
3105 $this->mLatestID
= false;
3106 $this->mContentModel
= false;
3107 $this->mEstimateRevisions
= null;
3108 $this->mPageLanguage
= false;
3109 $this->mDbPageLanguage
= false;
3110 $this->mIsBigDeletion
= null;
3113 public static function clearCaches() {
3114 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3115 $linkCache->clear();
3117 $titleCache = self
::getTitleCache();
3118 $titleCache->clear();
3122 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3124 * @param string $text Containing title to capitalize
3125 * @param int $ns Namespace index, defaults to NS_MAIN
3126 * @return string Containing capitalized title
3128 public static function capitalize( $text, $ns = NS_MAIN
) {
3129 if ( MWNamespace
::isCapitalized( $ns ) ) {
3130 return MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $text );
3137 * Secure and split - main initialisation function for this object
3139 * Assumes that mDbkeyform has been set, and is urldecoded
3140 * and uses underscores, but not otherwise munged. This function
3141 * removes illegal characters, splits off the interwiki and
3142 * namespace prefixes, sets the other forms, and canonicalizes
3145 * @throws MalformedTitleException On invalid titles
3146 * @return bool True on success
3148 private function secureAndSplit() {
3149 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3150 // the parsing code with Title, while avoiding massive refactoring.
3151 // @todo: get rid of secureAndSplit, refactor parsing code.
3152 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3153 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3154 /** @var MediaWikiTitleCodec $titleCodec */
3155 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3156 // MalformedTitleException can be thrown here
3157 $parts = $titleCodec->splitTitleString( $this->mDbkeyform
, $this->mDefaultNamespace
);
3160 $this->setFragment( '#' . $parts['fragment'] );
3161 $this->mInterwiki
= $parts['interwiki'];
3162 $this->mLocalInterwiki
= $parts['local_interwiki'];
3163 $this->mNamespace
= $parts['namespace'];
3164 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3166 $this->mDbkeyform
= $parts['dbkey'];
3167 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3168 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3170 # We already know that some pages won't be in the database!
3171 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3172 $this->mArticleID
= 0;
3179 * Get an array of Title objects linking to this Title
3180 * Also stores the IDs in the link cache.
3182 * WARNING: do not use this function on arbitrary user-supplied titles!
3183 * On heavily-used templates it will max out the memory.
3185 * @param array $options May be FOR UPDATE
3186 * @param string $table Table name
3187 * @param string $prefix Fields prefix
3188 * @return Title[] Array of Title objects linking here
3190 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3191 if ( count( $options ) > 0 ) {
3192 $db = wfGetDB( DB_MASTER
);
3194 $db = wfGetDB( DB_REPLICA
);
3199 self
::getSelectFields(),
3201 "{$prefix}_from=page_id",
3202 "{$prefix}_namespace" => $this->mNamespace
,
3203 "{$prefix}_title" => $this->mDbkeyform
],
3209 if ( $res->numRows() ) {
3210 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3211 foreach ( $res as $row ) {
3212 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3214 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3215 $retVal[] = $titleObj;
3223 * Get an array of Title objects using this Title as a template
3224 * Also stores the IDs in the link cache.
3226 * WARNING: do not use this function on arbitrary user-supplied titles!
3227 * On heavily-used templates it will max out the memory.
3229 * @param array $options Query option to Database::select()
3230 * @return Title[] Array of Title the Title objects linking here
3232 public function getTemplateLinksTo( $options = [] ) {
3233 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3237 * Get an array of Title objects linked from this Title
3238 * Also stores the IDs in the link cache.
3240 * WARNING: do not use this function on arbitrary user-supplied titles!
3241 * On heavily-used templates it will max out the memory.
3243 * @param array $options Query option to Database::select()
3244 * @param string $table Table name
3245 * @param string $prefix Fields prefix
3246 * @return array Array of Title objects linking here
3248 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3249 $id = $this->getArticleID();
3251 # If the page doesn't exist; there can't be any link from this page
3256 $db = wfGetDB( DB_REPLICA
);
3258 $blNamespace = "{$prefix}_namespace";
3259 $blTitle = "{$prefix}_title";
3261 $pageQuery = WikiPage
::getQueryInfo();
3263 [ $table, 'nestpage' => $pageQuery['tables'] ],
3265 [ $blNamespace, $blTitle ],
3266 $pageQuery['fields']
3268 [ "{$prefix}_from" => $id ],
3273 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3274 ] ] +
$pageQuery['joins']
3278 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
3279 foreach ( $res as $row ) {
3280 if ( $row->page_id
) {
3281 $titleObj = self
::newFromRow( $row );
3283 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3284 $linkCache->addBadLinkObj( $titleObj );
3286 $retVal[] = $titleObj;
3293 * Get an array of Title objects used on this Title as a template
3294 * Also stores the IDs in the link cache.
3296 * WARNING: do not use this function on arbitrary user-supplied titles!
3297 * On heavily-used templates it will max out the memory.
3299 * @param array $options May be FOR UPDATE
3300 * @return Title[] Array of Title the Title objects used here
3302 public function getTemplateLinksFrom( $options = [] ) {
3303 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3307 * Get an array of Title objects referring to non-existent articles linked
3310 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3311 * should use redirect table in this case).
3312 * @return Title[] Array of Title the Title objects
3314 public function getBrokenLinksFrom() {
3315 if ( $this->getArticleID() == 0 ) {
3316 # All links from article ID 0 are false positives
3320 $dbr = wfGetDB( DB_REPLICA
);
3321 $res = $dbr->select(
3322 [ 'page', 'pagelinks' ],
3323 [ 'pl_namespace', 'pl_title' ],
3325 'pl_from' => $this->getArticleID(),
3326 'page_namespace IS NULL'
3332 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3338 foreach ( $res as $row ) {
3339 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3345 * Get a list of URLs to purge from the CDN cache when this
3348 * @return string[] Array of String the URLs
3350 public function getCdnUrls() {
3352 $this->getInternalURL(),
3353 $this->getInternalURL( 'action=history' )
3356 $pageLang = $this->getPageLanguage();
3357 if ( $pageLang->hasVariants() ) {
3358 $variants = $pageLang->getVariants();
3359 foreach ( $variants as $vCode ) {
3360 $urls[] = $this->getInternalURL( $vCode );
3364 // If we are looking at a css/js user subpage, purge the action=raw.
3365 if ( $this->isUserJsConfigPage() ) {
3366 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3367 } elseif ( $this->isUserJsonConfigPage() ) {
3368 $urls[] = $this->getInternalURL( 'action=raw&ctype=application/json' );
3369 } elseif ( $this->isUserCssConfigPage() ) {
3370 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3373 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3378 * Purge all applicable CDN URLs
3380 public function purgeSquid() {
3381 DeferredUpdates
::addUpdate(
3382 new CdnCacheUpdate( $this->getCdnUrls() ),
3383 DeferredUpdates
::PRESEND
3388 * Check whether a given move operation would be valid.
3389 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3391 * @deprecated since 1.25, use MovePage's methods instead
3392 * @param Title &$nt The new title
3393 * @param bool $auth Whether to check user permissions (uses $wgUser)
3394 * @param string $reason Is the log summary of the move, used for spam checking
3395 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3397 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3400 if ( !( $nt instanceof Title
) ) {
3401 // Normally we'd add this to $errors, but we'll get
3402 // lots of syntax errors if $nt is not an object
3403 return [ [ 'badtitletext' ] ];
3406 $mp = new MovePage( $this, $nt );
3407 $errors = $mp->isValidMove()->getErrorsArray();
3409 $errors = wfMergeErrorArrays(
3411 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3415 return $errors ?
: true;
3419 * Move a title to a new location
3421 * @deprecated since 1.25, use the MovePage class instead
3422 * @param Title &$nt The new title
3423 * @param bool $auth Indicates whether $wgUser's permissions
3425 * @param string $reason The reason for the move
3426 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3427 * Ignored if the user doesn't have the suppressredirect right.
3428 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3429 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3431 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3432 array $changeTags = []
3435 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3436 if ( is_array( $err ) ) {
3437 // Auto-block user's IP if the account was "hard" blocked
3438 $wgUser->spreadAnyEditBlock();
3441 // Check suppressredirect permission
3442 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3443 $createRedirect = true;
3446 $mp = new MovePage( $this, $nt );
3447 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3448 if ( $status->isOK() ) {
3451 return $status->getErrorsArray();
3456 * Move this page's subpages to be subpages of $nt
3458 * @param Title $nt Move target
3459 * @param bool $auth Whether $wgUser's permissions should be checked
3460 * @param string $reason The reason for the move
3461 * @param bool $createRedirect Whether to create redirects from the old subpages to
3462 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3463 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3464 * @return array Array with old page titles as keys, and strings (new page titles) or
3465 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3466 * getUserPermissionsErrors()-like error array with numeric indices if
3467 * no pages were moved
3469 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3470 array $changeTags = []
3472 global $wgMaximumMovedPages;
3473 // Check permissions
3474 if ( !$this->userCan( 'move-subpages' ) ) {
3476 [ 'cant-move-subpages' ],
3479 // Do the source and target namespaces support subpages?
3480 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3482 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->mNamespace
) ],
3485 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3487 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3491 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3494 foreach ( $subpages as $oldSubpage ) {
3496 if ( $count > $wgMaximumMovedPages ) {
3497 $retval[$oldSubpage->getPrefixedText()] = [
3498 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3503 // We don't know whether this function was called before
3504 // or after moving the root page, so check both
3506 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3507 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3509 // When moving a page to a subpage of itself,
3510 // don't move it twice
3513 $newPageName = preg_replace(
3514 '#^' . preg_quote( $this->mDbkeyform
, '#' ) . '#',
3515 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3516 $oldSubpage->getDBkey() );
3517 if ( $oldSubpage->isTalkPage() ) {
3518 $newNs = $nt->getTalkPage()->getNamespace();
3520 $newNs = $nt->getSubjectPage()->getNamespace();
3522 # T16385: we need makeTitleSafe because the new page names may
3523 # be longer than 255 characters.
3524 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3526 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3527 if ( $success === true ) {
3528 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3530 $retval[$oldSubpage->getPrefixedText()] = $success;
3537 * Checks if this page is just a one-rev redirect.
3538 * Adds lock, so don't use just for light purposes.
3542 public function isSingleRevRedirect() {
3543 global $wgContentHandlerUseDB;
3545 $dbw = wfGetDB( DB_MASTER
);
3548 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3549 if ( $wgContentHandlerUseDB ) {
3550 $fields[] = 'page_content_model';
3553 $row = $dbw->selectRow( 'page',
3559 # Cache some fields we may want
3560 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3561 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3562 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3563 $this->mContentModel
= $row && isset( $row->page_content_model
)
3564 ?
strval( $row->page_content_model
)
3567 if ( !$this->mRedirect
) {
3570 # Does the article have a history?
3571 $row = $dbw->selectField( [ 'page', 'revision' ],
3573 [ 'page_namespace' => $this->mNamespace
,
3574 'page_title' => $this->mDbkeyform
,
3576 'page_latest != rev_id'
3581 # Return true if there was no history
3582 return ( $row === false );
3586 * Checks if $this can be moved to a given Title
3587 * - Selects for update, so don't call it unless you mean business
3589 * @deprecated since 1.25, use MovePage's methods instead
3590 * @param Title $nt The new title to check
3593 public function isValidMoveTarget( $nt ) {
3594 # Is it an existing file?
3595 if ( $nt->getNamespace() == NS_FILE
) {
3596 $file = wfLocalFile( $nt );
3597 $file->load( File
::READ_LATEST
);
3598 if ( $file->exists() ) {
3599 wfDebug( __METHOD__
. ": file exists\n" );
3603 # Is it a redirect with no history?
3604 if ( !$nt->isSingleRevRedirect() ) {
3605 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3608 # Get the article text
3609 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3610 if ( !is_object( $rev ) ) {
3613 $content = $rev->getContent();
3614 # Does the redirect point to the source?
3615 # Or is it a broken self-redirect, usually caused by namespace collisions?
3616 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3618 if ( $redirTitle ) {
3619 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3620 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3621 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3627 # Fail safe (not a redirect after all. strange.)
3628 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3629 " is a redirect, but it doesn't contain a valid redirect.\n" );
3635 * Get categories to which this Title belongs and return an array of
3636 * categories' names.
3638 * @return array Array of parents in the form:
3639 * $parent => $currentarticle
3641 public function getParentCategories() {
3644 $titleKey = $this->getArticleID();
3646 if ( $titleKey === 0 ) {
3650 $dbr = wfGetDB( DB_REPLICA
);
3652 $res = $dbr->select(
3655 [ 'cl_from' => $titleKey ],
3659 if ( $res->numRows() > 0 ) {
3660 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
3661 foreach ( $res as $row ) {
3662 // $data[] = Title::newFromText( $contLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3663 $data[$contLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] =
3664 $this->getFullText();
3671 * Get a tree of parent categories
3673 * @param array $children Array with the children in the keys, to check for circular refs
3674 * @return array Tree of parent categories
3676 public function getParentCategoryTree( $children = [] ) {
3678 $parents = $this->getParentCategories();
3681 foreach ( $parents as $parent => $current ) {
3682 if ( array_key_exists( $parent, $children ) ) {
3683 # Circular reference
3684 $stack[$parent] = [];
3686 $nt = self
::newFromText( $parent );
3688 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
3698 * Get an associative array for selecting this title from
3701 * @return array Array suitable for the $where parameter of DB::select()
3703 public function pageCond() {
3704 if ( $this->mArticleID
> 0 ) {
3705 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3706 return [ 'page_id' => $this->mArticleID
];
3708 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
3713 * Get next/previous revision ID relative to another revision ID
3714 * @param int $revId Revision ID. Get the revision that was before this one.
3715 * @param int $flags Title::GAID_FOR_UPDATE
3716 * @param string $dir 'next' or 'prev'
3717 * @return int|bool New revision ID, or false if none exists
3719 private function getRelativeRevisionID( $revId, $flags, $dir ) {
3720 $revId = (int)$revId;
3721 if ( $dir === 'next' ) {
3724 } elseif ( $dir === 'prev' ) {
3728 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
3731 if ( $flags & self
::GAID_FOR_UPDATE
) {
3732 $db = wfGetDB( DB_MASTER
);
3734 $db = wfGetDB( DB_REPLICA
, 'contributions' );
3737 // Intentionally not caring if the specified revision belongs to this
3738 // page. We only care about the timestamp.
3739 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
3740 if ( $ts === false ) {
3741 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
3742 if ( $ts === false ) {
3743 // Or should this throw an InvalidArgumentException or something?
3747 $ts = $db->addQuotes( $ts );
3749 $revId = $db->selectField( 'revision', 'rev_id',
3751 'rev_page' => $this->getArticleID( $flags ),
3752 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
3756 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
3757 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
3761 if ( $revId === false ) {
3764 return intval( $revId );
3769 * Get the revision ID of the previous revision
3771 * @param int $revId Revision ID. Get the revision that was before this one.
3772 * @param int $flags Title::GAID_FOR_UPDATE
3773 * @return int|bool Old revision ID, or false if none exists
3775 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3776 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
3780 * Get the revision ID of the next revision
3782 * @param int $revId Revision ID. Get the revision that was after this one.
3783 * @param int $flags Title::GAID_FOR_UPDATE
3784 * @return int|bool Next revision ID, or false if none exists
3786 public function getNextRevisionID( $revId, $flags = 0 ) {
3787 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
3791 * Get the first revision of the page
3793 * @param int $flags Title::GAID_FOR_UPDATE
3794 * @return Revision|null If page doesn't exist
3796 public function getFirstRevision( $flags = 0 ) {
3797 $pageId = $this->getArticleID( $flags );
3799 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
3800 $revQuery = Revision
::getQueryInfo();
3801 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
3802 [ 'rev_page' => $pageId ],
3805 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
3806 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
3811 return new Revision( $row, 0, $this );
3818 * Get the oldest revision timestamp of this page
3820 * @param int $flags Title::GAID_FOR_UPDATE
3821 * @return string|null MW timestamp
3823 public function getEarliestRevTime( $flags = 0 ) {
3824 $rev = $this->getFirstRevision( $flags );
3825 return $rev ?
$rev->getTimestamp() : null;
3829 * Check if this is a new page
3833 public function isNewPage() {
3834 $dbr = wfGetDB( DB_REPLICA
);
3835 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3839 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
3843 public function isBigDeletion() {
3844 global $wgDeleteRevisionsLimit;
3846 if ( !$wgDeleteRevisionsLimit ) {
3850 if ( $this->mIsBigDeletion
=== null ) {
3851 $dbr = wfGetDB( DB_REPLICA
);
3853 $revCount = $dbr->selectRowCount(
3856 [ 'rev_page' => $this->getArticleID() ],
3858 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
3861 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
3864 return $this->mIsBigDeletion
;
3868 * Get the approximate revision count of this page.
3872 public function estimateRevisionCount() {
3873 if ( !$this->exists() ) {
3877 if ( $this->mEstimateRevisions
=== null ) {
3878 $dbr = wfGetDB( DB_REPLICA
);
3879 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
3880 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
3883 return $this->mEstimateRevisions
;
3887 * Get the number of revisions between the given revision.
3888 * Used for diffs and other things that really need it.
3890 * @param int|Revision $old Old revision or rev ID (first before range)
3891 * @param int|Revision $new New revision or rev ID (first after range)
3892 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
3893 * @return int Number of revisions between these revisions.
3895 public function countRevisionsBetween( $old, $new, $max = null ) {
3896 if ( !( $old instanceof Revision
) ) {
3897 $old = Revision
::newFromTitle( $this, (int)$old );
3899 if ( !( $new instanceof Revision
) ) {
3900 $new = Revision
::newFromTitle( $this, (int)$new );
3902 if ( !$old ||
!$new ) {
3903 return 0; // nothing to compare
3905 $dbr = wfGetDB( DB_REPLICA
);
3907 'rev_page' => $this->getArticleID(),
3908 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3909 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3911 if ( $max !== null ) {
3912 return $dbr->selectRowCount( 'revision', '1',
3915 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
3918 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
3923 * Get the authors between the given revisions or revision IDs.
3924 * Used for diffs and other things that really need it.
3928 * @param int|Revision $old Old revision or rev ID (first before range by default)
3929 * @param int|Revision $new New revision or rev ID (first after range by default)
3930 * @param int $limit Maximum number of authors
3931 * @param string|array $options (Optional): Single option, or an array of options:
3932 * 'include_old' Include $old in the range; $new is excluded.
3933 * 'include_new' Include $new in the range; $old is excluded.
3934 * 'include_both' Include both $old and $new in the range.
3935 * Unknown option values are ignored.
3936 * @return array|null Names of revision authors in the range; null if not both revisions exist
3938 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
3939 if ( !( $old instanceof Revision
) ) {
3940 $old = Revision
::newFromTitle( $this, (int)$old );
3942 if ( !( $new instanceof Revision
) ) {
3943 $new = Revision
::newFromTitle( $this, (int)$new );
3945 // XXX: what if Revision objects are passed in, but they don't refer to this title?
3946 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
3947 // in the sanity check below?
3948 if ( !$old ||
!$new ) {
3949 return null; // nothing to compare
3954 $options = (array)$options;
3955 if ( in_array( 'include_old', $options ) ) {
3958 if ( in_array( 'include_new', $options ) ) {
3961 if ( in_array( 'include_both', $options ) ) {
3965 // No DB query needed if $old and $new are the same or successive revisions:
3966 if ( $old->getId() === $new->getId() ) {
3967 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
3969 [ $old->getUserText( Revision
::RAW
) ];
3970 } elseif ( $old->getId() === $new->getParentId() ) {
3971 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
3972 $authors[] = $old->getUserText( Revision
::RAW
);
3973 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
3974 $authors[] = $new->getUserText( Revision
::RAW
);
3976 } elseif ( $old_cmp === '>=' ) {
3977 $authors[] = $old->getUserText( Revision
::RAW
);
3978 } elseif ( $new_cmp === '<=' ) {
3979 $authors[] = $new->getUserText( Revision
::RAW
);
3983 $dbr = wfGetDB( DB_REPLICA
);
3984 $revQuery = Revision
::getQueryInfo();
3985 $authors = $dbr->selectFieldValues(
3986 $revQuery['tables'],
3987 $revQuery['fields']['rev_user_text'],
3989 'rev_page' => $this->getArticleID(),
3990 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3991 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3993 [ 'DISTINCT', 'LIMIT' => $limit +
1 ], // add one so caller knows it was truncated
4000 * Get the number of authors between the given revisions or revision IDs.
4001 * Used for diffs and other things that really need it.
4003 * @param int|Revision $old Old revision or rev ID (first before range by default)
4004 * @param int|Revision $new New revision or rev ID (first after range by default)
4005 * @param int $limit Maximum number of authors
4006 * @param string|array $options (Optional): Single option, or an array of options:
4007 * 'include_old' Include $old in the range; $new is excluded.
4008 * 'include_new' Include $new in the range; $old is excluded.
4009 * 'include_both' Include both $old and $new in the range.
4010 * Unknown option values are ignored.
4011 * @return int Number of revision authors in the range; zero if not both revisions exist
4013 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4014 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4015 return $authors ?
count( $authors ) : 0;
4019 * Compare with another title.
4021 * @param Title $title
4024 public function equals( Title
$title ) {
4025 // Note: === is necessary for proper matching of number-like titles.
4026 return $this->mInterwiki
=== $title->mInterwiki
4027 && $this->mNamespace
== $title->mNamespace
4028 && $this->mDbkeyform
=== $title->mDbkeyform
;
4032 * Check if this title is a subpage of another title
4034 * @param Title $title
4037 public function isSubpageOf( Title
$title ) {
4038 return $this->mInterwiki
=== $title->mInterwiki
4039 && $this->mNamespace
== $title->mNamespace
4040 && strpos( $this->mDbkeyform
, $title->mDbkeyform
. '/' ) === 0;
4044 * Check if page exists. For historical reasons, this function simply
4045 * checks for the existence of the title in the page table, and will
4046 * thus return false for interwiki links, special pages and the like.
4047 * If you want to know if a title can be meaningfully viewed, you should
4048 * probably call the isKnown() method instead.
4050 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4051 * from master/for update
4054 public function exists( $flags = 0 ) {
4055 $exists = $this->getArticleID( $flags ) != 0;
4056 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4061 * Should links to this title be shown as potentially viewable (i.e. as
4062 * "bluelinks"), even if there's no record by this title in the page
4065 * This function is semi-deprecated for public use, as well as somewhat
4066 * misleadingly named. You probably just want to call isKnown(), which
4067 * calls this function internally.
4069 * (ISSUE: Most of these checks are cheap, but the file existence check
4070 * can potentially be quite expensive. Including it here fixes a lot of
4071 * existing code, but we might want to add an optional parameter to skip
4072 * it and any other expensive checks.)
4076 public function isAlwaysKnown() {
4080 * Allows overriding default behavior for determining if a page exists.
4081 * If $isKnown is kept as null, regular checks happen. If it's
4082 * a boolean, this value is returned by the isKnown method.
4086 * @param Title $title
4087 * @param bool|null $isKnown
4089 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4091 if ( !is_null( $isKnown ) ) {
4095 if ( $this->isExternal() ) {
4096 return true; // any interwiki link might be viewable, for all we know
4099 switch ( $this->mNamespace
) {
4102 // file exists, possibly in a foreign repo
4103 return (bool)wfFindFile( $this );
4105 // valid special page
4106 return MediaWikiServices
::getInstance()->getSpecialPageFactory()->
4107 exists( $this->mDbkeyform
);
4109 // selflink, possibly with fragment
4110 return $this->mDbkeyform
== '';
4112 // known system message
4113 return $this->hasSourceText() !== false;
4120 * Does this title refer to a page that can (or might) be meaningfully
4121 * viewed? In particular, this function may be used to determine if
4122 * links to the title should be rendered as "bluelinks" (as opposed to
4123 * "redlinks" to non-existent pages).
4124 * Adding something else to this function will cause inconsistency
4125 * since LinkHolderArray calls isAlwaysKnown() and does its own
4126 * page existence check.
4130 public function isKnown() {
4131 return $this->isAlwaysKnown() ||
$this->exists();
4135 * Does this page have source text?
4139 public function hasSourceText() {
4140 if ( $this->exists() ) {
4144 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4145 // If the page doesn't exist but is a known system message, default
4146 // message content will be displayed, same for language subpages-
4147 // Use always content language to avoid loading hundreds of languages
4148 // to get the link color.
4149 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
4150 list( $name, ) = MessageCache
::singleton()->figureMessage(
4151 $contLang->lcfirst( $this->getText() )
4153 $message = wfMessage( $name )->inLanguage( $contLang )->useDatabase( false );
4154 return $message->exists();
4161 * Get the default (plain) message contents for an page that overrides an
4162 * interface message key.
4164 * Primary use cases:
4167 * - Show default when viewing the page. The Article::getSubstituteContent
4168 * method displays the default message content, instead of the
4169 * 'noarticletext' placeholder message normally used.
4172 * - Title of edit page. When creating an interface message override,
4173 * the editor is told they are "Editing the page", instead of
4174 * "Creating the page". (EditPage::setHeaders)
4175 * - Edit notice. The 'translateinterface' edit notice is shown when creating
4176 * or editing a an interface message override. (EditPage::showIntro)
4177 * - Opening the editor. The contents of the localisation message are used
4178 * as contents of the editor when creating a new page in the MediaWiki
4179 * namespace. This simplifies the process for editors when "changing"
4180 * an interface message by creating an override. (EditPage::getContentObject)
4181 * - Showing a diff. The left-hand side of a diff when an editor is
4182 * previewing their changes before saving the creation of a page in the
4183 * MediaWiki namespace. (EditPage::showDiff)
4184 * - Disallowing a save. When attempting to create a a MediaWiki-namespace
4185 * page with the proposed content matching the interface message default,
4186 * the save is rejected, the same way we disallow blank pages from being
4187 * created. (EditPage::internalAttemptSave)
4190 * - Default content, when using the 'prepend' or 'append' feature.
4193 * - Label the create action as "Edit", if the page can be an override.
4195 * @return string|bool
4197 public function getDefaultMessageText() {
4198 if ( $this->mNamespace
!= NS_MEDIAWIKI
) { // Just in case
4202 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4203 MediaWikiServices
::getInstance()->getContentLanguage()->lcfirst( $this->getText() )
4205 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4207 if ( $message->exists() ) {
4208 return $message->plain();
4215 * Updates page_touched for this page; called from LinksUpdate.php
4217 * @param string|null $purgeTime [optional] TS_MW timestamp
4218 * @return bool True if the update succeeded
4220 public function invalidateCache( $purgeTime = null ) {
4221 if ( wfReadOnly() ) {
4223 } elseif ( $this->mArticleID
=== 0 ) {
4224 return true; // avoid gap locking if we know it's not there
4227 $dbw = wfGetDB( DB_MASTER
);
4228 $dbw->onTransactionPreCommitOrIdle(
4229 function () use ( $dbw ) {
4230 ResourceLoaderWikiModule
::invalidateModuleCache(
4231 $this, null, null, $dbw->getDomainID() );
4236 $conds = $this->pageCond();
4237 DeferredUpdates
::addUpdate(
4238 new AutoCommitUpdate(
4241 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4242 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4245 [ 'page_touched' => $dbTimestamp ],
4246 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4249 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4252 DeferredUpdates
::PRESEND
4259 * Update page_touched timestamps and send CDN purge messages for
4260 * pages linking to this title. May be sent to the job queue depending
4261 * on the number of links. Typically called on create and delete.
4263 public function touchLinks() {
4264 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4265 if ( $this->mNamespace
== NS_CATEGORY
) {
4266 DeferredUpdates
::addUpdate(
4267 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4273 * Get the last touched timestamp
4275 * @param IDatabase|null $db
4276 * @return string|false Last-touched timestamp
4278 public function getTouched( $db = null ) {
4279 if ( $db === null ) {
4280 $db = wfGetDB( DB_REPLICA
);
4282 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4287 * Get the timestamp when this page was updated since the user last saw it.
4289 * @param User|null $user
4290 * @return string|null
4292 public function getNotificationTimestamp( $user = null ) {
4295 // Assume current user if none given
4299 // Check cache first
4300 $uid = $user->getId();
4304 // avoid isset here, as it'll return false for null entries
4305 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4306 return $this->mNotificationTimestamp
[$uid];
4308 // Don't cache too much!
4309 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4310 $this->mNotificationTimestamp
= [];
4313 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4314 $watchedItem = $store->getWatchedItem( $user, $this );
4315 if ( $watchedItem ) {
4316 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4318 $this->mNotificationTimestamp
[$uid] = false;
4321 return $this->mNotificationTimestamp
[$uid];
4325 * Generate strings used for xml 'id' names in monobook tabs
4327 * @param string $prepend Defaults to 'nstab-'
4328 * @return string XML 'id' name
4330 public function getNamespaceKey( $prepend = 'nstab-' ) {
4331 // Gets the subject namespace of this title
4332 $subjectNS = MWNamespace
::getSubject( $this->mNamespace
);
4333 // Prefer canonical namespace name for HTML IDs
4334 $namespaceKey = MWNamespace
::getCanonicalName( $subjectNS );
4335 if ( $namespaceKey === false ) {
4336 // Fallback to localised text
4337 $namespaceKey = $this->getSubjectNsText();
4339 // Makes namespace key lowercase
4340 $namespaceKey = MediaWikiServices
::getInstance()->getContentLanguage()->lc( $namespaceKey );
4342 if ( $namespaceKey == '' ) {
4343 $namespaceKey = 'main';
4345 // Changes file to image for backwards compatibility
4346 if ( $namespaceKey == 'file' ) {
4347 $namespaceKey = 'image';
4349 return $prepend . $namespaceKey;
4353 * Get all extant redirects to this Title
4355 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4356 * @return Title[] Array of Title redirects to this title
4358 public function getRedirectsHere( $ns = null ) {
4361 $dbr = wfGetDB( DB_REPLICA
);
4363 'rd_namespace' => $this->mNamespace
,
4364 'rd_title' => $this->mDbkeyform
,
4367 if ( $this->isExternal() ) {
4368 $where['rd_interwiki'] = $this->mInterwiki
;
4370 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4372 if ( !is_null( $ns ) ) {
4373 $where['page_namespace'] = $ns;
4376 $res = $dbr->select(
4377 [ 'redirect', 'page' ],
4378 [ 'page_namespace', 'page_title' ],
4383 foreach ( $res as $row ) {
4384 $redirs[] = self
::newFromRow( $row );
4390 * Check if this Title is a valid redirect target
4394 public function isValidRedirectTarget() {
4395 global $wgInvalidRedirectTargets;
4397 if ( $this->isSpecialPage() ) {
4398 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4399 if ( $this->isSpecial( 'Userlogout' ) ) {
4403 foreach ( $wgInvalidRedirectTargets as $target ) {
4404 if ( $this->isSpecial( $target ) ) {
4414 * Get a backlink cache object
4416 * @return BacklinkCache
4418 public function getBacklinkCache() {
4419 return BacklinkCache
::get( $this );
4423 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4427 public function canUseNoindex() {
4428 global $wgExemptFromUserRobotsControl;
4430 $bannedNamespaces = $wgExemptFromUserRobotsControl ?? MWNamespace
::getContentNamespaces();
4432 return !in_array( $this->mNamespace
, $bannedNamespaces );
4436 * Returns the raw sort key to be used for categories, with the specified
4437 * prefix. This will be fed to Collation::getSortKey() to get a
4438 * binary sortkey that can be used for actual sorting.
4440 * @param string $prefix The prefix to be used, specified using
4441 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4445 public function getCategorySortkey( $prefix = '' ) {
4446 $unprefixed = $this->getText();
4448 // Anything that uses this hook should only depend
4449 // on the Title object passed in, and should probably
4450 // tell the users to run updateCollations.php --force
4451 // in order to re-sort existing category relations.
4452 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4453 if ( $prefix !== '' ) {
4454 # Separate with a line feed, so the unprefixed part is only used as
4455 # a tiebreaker when two pages have the exact same prefix.
4456 # In UCA, tab is the only character that can sort above LF
4457 # so we strip both of them from the original prefix.
4458 $prefix = strtr( $prefix, "\n\t", ' ' );
4459 return "$prefix\n$unprefixed";
4465 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4466 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4467 * the db, it will return NULL.
4469 * @return string|null|bool
4471 private function getDbPageLanguageCode() {
4472 global $wgPageLanguageUseDB;
4474 // check, if the page language could be saved in the database, and if so and
4475 // the value is not requested already, lookup the page language using LinkCache
4476 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4477 $linkCache = MediaWikiServices
::getInstance()->getLinkCache();
4478 $linkCache->addLinkObj( $this );
4479 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4482 return $this->mDbPageLanguage
;
4486 * Get the language in which the content of this page is written in
4487 * wikitext. Defaults to content language, but in certain cases it can be
4488 * e.g. $wgLang (such as special pages, which are in the user language).
4493 public function getPageLanguage() {
4494 global $wgLang, $wgLanguageCode;
4495 if ( $this->isSpecialPage() ) {
4496 // special pages are in the user language
4500 // Checking if DB language is set
4501 $dbPageLanguage = $this->getDbPageLanguageCode();
4502 if ( $dbPageLanguage ) {
4503 return wfGetLangObj( $dbPageLanguage );
4506 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4507 // Note that this may depend on user settings, so the cache should
4508 // be only per-request.
4509 // NOTE: ContentHandler::getPageLanguage() may need to load the
4510 // content to determine the page language!
4511 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4513 $contentHandler = ContentHandler
::getForTitle( $this );
4514 $langObj = $contentHandler->getPageLanguage( $this );
4515 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4517 $langObj = Language
::factory( $this->mPageLanguage
[0] );
4524 * Get the language in which the content of this page is written when
4525 * viewed by user. Defaults to content language, but in certain cases it can be
4526 * e.g. $wgLang (such as special pages, which are in the user language).
4531 public function getPageViewLanguage() {
4534 if ( $this->isSpecialPage() ) {
4535 // If the user chooses a variant, the content is actually
4536 // in a language whose code is the variant code.
4537 $variant = $wgLang->getPreferredVariant();
4538 if ( $wgLang->getCode() !== $variant ) {
4539 return Language
::factory( $variant );
4545 // Checking if DB language is set
4546 $dbPageLanguage = $this->getDbPageLanguageCode();
4547 if ( $dbPageLanguage ) {
4548 $pageLang = wfGetLangObj( $dbPageLanguage );
4549 $variant = $pageLang->getPreferredVariant();
4550 if ( $pageLang->getCode() !== $variant ) {
4551 $pageLang = Language
::factory( $variant );
4557 // @note Can't be cached persistently, depends on user settings.
4558 // @note ContentHandler::getPageViewLanguage() may need to load the
4559 // content to determine the page language!
4560 $contentHandler = ContentHandler
::getForTitle( $this );
4561 $pageLang = $contentHandler->getPageViewLanguage( $this );
4566 * Get a list of rendered edit notices for this page.
4568 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4569 * they will already be wrapped in paragraphs.
4572 * @param int $oldid Revision ID that's being edited
4575 public function getEditNotices( $oldid = 0 ) {
4578 // Optional notice for the entire namespace
4579 $editnotice_ns = 'editnotice-' . $this->mNamespace
;
4580 $msg = wfMessage( $editnotice_ns );
4581 if ( $msg->exists() ) {
4582 $html = $msg->parseAsBlock();
4583 // Edit notices may have complex logic, but output nothing (T91715)
4584 if ( trim( $html ) !== '' ) {
4585 $notices[$editnotice_ns] = Html
::rawElement(
4589 'mw-editnotice-namespace',
4590 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4597 if ( MWNamespace
::hasSubpages( $this->mNamespace
) ) {
4598 // Optional notice for page itself and any parent page
4599 $editnotice_base = $editnotice_ns;
4600 foreach ( explode( '/', $this->mDbkeyform
) as $part ) {
4601 $editnotice_base .= '-' . $part;
4602 $msg = wfMessage( $editnotice_base );
4603 if ( $msg->exists() ) {
4604 $html = $msg->parseAsBlock();
4605 if ( trim( $html ) !== '' ) {
4606 $notices[$editnotice_base] = Html
::rawElement(
4610 'mw-editnotice-base',
4611 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4619 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4620 $editnoticeText = $editnotice_ns . '-' . strtr( $this->mDbkeyform
, '/', '-' );
4621 $msg = wfMessage( $editnoticeText );
4622 if ( $msg->exists() ) {
4623 $html = $msg->parseAsBlock();
4624 if ( trim( $html ) !== '' ) {
4625 $notices[$editnoticeText] = Html
::rawElement(
4629 'mw-editnotice-page',
4630 Sanitizer
::escapeClass( "mw-$editnoticeText" )
4638 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
4645 public function __sleep() {
4653 'mDefaultNamespace',
4657 public function __wakeup() {
4658 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
4659 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
4660 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );