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 Wikimedia\Rdbms\Database
;
26 use Wikimedia\Rdbms\IDatabase
;
27 use MediaWiki\Linker\LinkTarget
;
28 use MediaWiki\Interwiki\InterwikiLookup
;
29 use MediaWiki\MediaWikiServices
;
32 * Represents a title within MediaWiki.
33 * Optionally may contain an interwiki designation or namespace.
34 * @note This class can fetch various kinds of data from the database;
35 * however, it does so inefficiently.
36 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
37 * and does not rely on global state or the database.
39 class Title
implements LinkTarget
{
40 /** @var HashBagOStuff */
41 static private $titleCache = null;
44 * Title::newFromText maintains a cache to avoid expensive re-normalization of
45 * commonly used titles. On a batch operation this can become a memory leak
46 * if not bounded. After hitting this many titles reset the cache.
48 const CACHE_MAX
= 1000;
51 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
52 * to use the master DB
54 const GAID_FOR_UPDATE
= 1;
57 * @name Private member variables
58 * Please use the accessor functions instead.
63 /** @var string Text form (spaces not underscores) of the main part */
64 public $mTextform = '';
66 /** @var string URL-encoded form of the main part */
67 public $mUrlform = '';
69 /** @var string Main part with underscores */
70 public $mDbkeyform = '';
72 /** @var string Database key with the initial letter in the case specified by the user */
73 protected $mUserCaseDBKey;
75 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
76 public $mNamespace = NS_MAIN
;
78 /** @var string Interwiki prefix */
79 public $mInterwiki = '';
81 /** @var bool Was this Title created from a string with a local interwiki prefix? */
82 private $mLocalInterwiki = false;
84 /** @var string Title fragment (i.e. the bit after the #) */
85 public $mFragment = '';
87 /** @var int Article ID, fetched from the link cache on demand */
88 public $mArticleID = -1;
90 /** @var bool|int ID of most recent revision */
91 protected $mLatestID = false;
94 * @var bool|string ID of the page's content model, i.e. one of the
95 * CONTENT_MODEL_XXX constants
97 private $mContentModel = false;
100 * @var bool If a content model was forced via setContentModel()
101 * this will be true to avoid having other code paths reset it
103 private $mForcedContentModel = false;
105 /** @var int Estimated number of revisions; null of not loaded */
106 private $mEstimateRevisions;
108 /** @var array Array of groups allowed to edit this article */
109 public $mRestrictions = [];
112 * @var string|bool Comma-separated set of permission keys
113 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
114 * Edit and move sections are separated by a colon
115 * Example: "edit=autoconfirmed,sysop:move=sysop"
117 protected $mOldRestrictions = false;
119 /** @var bool Cascade restrictions on this page to included templates and images? */
120 public $mCascadeRestriction;
122 /** Caching the results of getCascadeProtectionSources */
123 public $mCascadingRestrictions;
125 /** @var array When do the restrictions on this page expire? */
126 protected $mRestrictionsExpiry = [];
128 /** @var bool Are cascading restrictions in effect on this page? */
129 protected $mHasCascadingRestrictions;
131 /** @var array Where are the cascading restrictions coming from on this page? */
132 public $mCascadeSources;
134 /** @var bool Boolean for initialisation on demand */
135 public $mRestrictionsLoaded = false;
137 /** @var string Text form including namespace/interwiki, initialised on demand */
138 protected $mPrefixedText = null;
140 /** @var mixed Cached value for getTitleProtection (create protection) */
141 public $mTitleProtection;
144 * @var int Namespace index when there is no namespace. Don't change the
145 * following default, NS_MAIN is hardcoded in several places. See T2696.
146 * Zero except in {{transclusion}} tags.
148 public $mDefaultNamespace = NS_MAIN
;
150 /** @var int The page length, 0 for special pages */
151 protected $mLength = -1;
153 /** @var null Is the article at this title a redirect? */
154 public $mRedirect = null;
156 /** @var array Associative array of user ID -> timestamp/false */
157 private $mNotificationTimestamp = [];
159 /** @var bool Whether a page has any subpages */
160 private $mHasSubpages;
162 /** @var bool The (string) language code of the page's language and content code. */
163 private $mPageLanguage = false;
165 /** @var string|bool|null The page language code from the database, null if not saved in
166 * the database or false if not loaded, yet. */
167 private $mDbPageLanguage = false;
169 /** @var TitleValue A corresponding TitleValue object */
170 private $mTitleValue = null;
172 /** @var bool Would deleting this page be a big deletion? */
173 private $mIsBigDeletion = null;
177 * B/C kludge: provide a TitleParser for use by Title.
178 * Ideally, Title would have no methods that need this.
179 * Avoid usage of this singleton by using TitleValue
180 * and the associated services when possible.
182 * @return TitleFormatter
184 private static function getTitleFormatter() {
185 return MediaWikiServices
::getInstance()->getTitleFormatter();
189 * B/C kludge: provide an InterwikiLookup for use by Title.
190 * Ideally, Title would have no methods that need this.
191 * Avoid usage of this singleton by using TitleValue
192 * and the associated services when possible.
194 * @return InterwikiLookup
196 private static function getInterwikiLookup() {
197 return MediaWikiServices
::getInstance()->getInterwikiLookup();
203 function __construct() {
207 * Create a new Title from a prefixed DB key
209 * @param string $key The database key, which has underscores
210 * instead of spaces, possibly including namespace and
212 * @return Title|null Title, or null on an error
214 public static function newFromDBkey( $key ) {
216 $t->mDbkeyform
= $key;
219 $t->secureAndSplit();
221 } catch ( MalformedTitleException
$ex ) {
227 * Create a new Title from a TitleValue
229 * @param TitleValue $titleValue Assumed to be safe.
233 public static function newFromTitleValue( TitleValue
$titleValue ) {
234 return self
::newFromLinkTarget( $titleValue );
238 * Create a new Title from a LinkTarget
240 * @param LinkTarget $linkTarget Assumed to be safe.
244 public static function newFromLinkTarget( LinkTarget
$linkTarget ) {
245 if ( $linkTarget instanceof Title
) {
246 // Special case if it's already a Title object
249 return self
::makeTitle(
250 $linkTarget->getNamespace(),
251 $linkTarget->getText(),
252 $linkTarget->getFragment(),
253 $linkTarget->getInterwiki()
258 * Create a new Title from text, such as what one would find in a link. De-
259 * codes any HTML entities in the text.
261 * Title objects returned by this method are guaranteed to be valid, and
262 * thus return true from the isValid() method.
264 * @param string|int|null $text The link text; spaces, prefixes, and an
265 * initial ':' indicating the main namespace are accepted.
266 * @param int $defaultNamespace The namespace to use if none is specified
267 * by a prefix. If you want to force a specific namespace even if
268 * $text might begin with a namespace prefix, use makeTitle() or
270 * @throws InvalidArgumentException
271 * @return Title|null Title or null on an error.
273 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
274 // DWIM: Integers can be passed in here when page titles are used as array keys.
275 if ( $text !== null && !is_string( $text ) && !is_int( $text ) ) {
276 throw new InvalidArgumentException( '$text must be a string.' );
278 if ( $text === null ) {
283 return self
::newFromTextThrow( strval( $text ), $defaultNamespace );
284 } catch ( MalformedTitleException
$ex ) {
290 * Like Title::newFromText(), but throws MalformedTitleException when the title is invalid,
291 * rather than returning null.
293 * The exception subclasses encode detailed information about why the title is invalid.
295 * Title objects returned by this method are guaranteed to be valid, and
296 * thus return true from the isValid() method.
298 * @see Title::newFromText
301 * @param string $text Title text to check
302 * @param int $defaultNamespace
303 * @throws MalformedTitleException If the title is invalid
306 public static function newFromTextThrow( $text, $defaultNamespace = NS_MAIN
) {
307 if ( is_object( $text ) ) {
308 throw new MWException( '$text must be a string, given an object' );
311 $titleCache = self
::getTitleCache();
313 // Wiki pages often contain multiple links to the same page.
314 // Title normalization and parsing can become expensive on pages with many
315 // links, so we can save a little time by caching them.
316 // In theory these are value objects and won't get changed...
317 if ( $defaultNamespace == NS_MAIN
) {
318 $t = $titleCache->get( $text );
324 // Convert things like é ā or 〗 into normalized (T16952) text
325 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
328 $t->mDbkeyform
= strtr( $filteredText, ' ', '_' );
329 $t->mDefaultNamespace
= intval( $defaultNamespace );
331 $t->secureAndSplit();
332 if ( $defaultNamespace == NS_MAIN
) {
333 $titleCache->set( $text, $t );
339 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
341 * Example of wrong and broken code:
342 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
344 * Example of right code:
345 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
347 * Create a new Title from URL-encoded text. Ensures that
348 * the given title's length does not exceed the maximum.
350 * @param string $url The title, as might be taken from a URL
351 * @return Title|null The new object, or null on an error
353 public static function newFromURL( $url ) {
356 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
357 # but some URLs used it as a space replacement and they still come
358 # from some external search tools.
359 if ( strpos( self
::legalChars(), '+' ) === false ) {
360 $url = strtr( $url, '+', ' ' );
363 $t->mDbkeyform
= strtr( $url, ' ', '_' );
366 $t->secureAndSplit();
368 } catch ( MalformedTitleException
$ex ) {
374 * @return HashBagOStuff
376 private static function getTitleCache() {
377 if ( self
::$titleCache == null ) {
378 self
::$titleCache = new HashBagOStuff( [ 'maxKeys' => self
::CACHE_MAX
] );
380 return self
::$titleCache;
384 * Returns a list of fields that are to be selected for initializing Title
385 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
386 * whether to include page_content_model.
390 protected static function getSelectFields() {
391 global $wgContentHandlerUseDB, $wgPageLanguageUseDB;
394 'page_namespace', 'page_title', 'page_id',
395 'page_len', 'page_is_redirect', 'page_latest',
398 if ( $wgContentHandlerUseDB ) {
399 $fields[] = 'page_content_model';
402 if ( $wgPageLanguageUseDB ) {
403 $fields[] = 'page_lang';
410 * Create a new Title from an article ID
412 * @param int $id The page_id corresponding to the Title to create
413 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
414 * @return Title|null The new object, or null on an error
416 public static function newFromID( $id, $flags = 0 ) {
417 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
418 $row = $db->selectRow(
420 self
::getSelectFields(),
421 [ 'page_id' => $id ],
424 if ( $row !== false ) {
425 $title = self
::newFromRow( $row );
433 * Make an array of titles from an array of IDs
435 * @param int[] $ids Array of IDs
436 * @return Title[] Array of Titles
438 public static function newFromIDs( $ids ) {
439 if ( !count( $ids ) ) {
442 $dbr = wfGetDB( DB_REPLICA
);
446 self
::getSelectFields(),
447 [ 'page_id' => $ids ],
452 foreach ( $res as $row ) {
453 $titles[] = self
::newFromRow( $row );
459 * Make a Title object from a DB row
461 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
462 * @return Title Corresponding Title
464 public static function newFromRow( $row ) {
465 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
466 $t->loadFromRow( $row );
471 * Load Title object fields from a DB row.
472 * If false is given, the title will be treated as non-existing.
474 * @param stdClass|bool $row Database row
476 public function loadFromRow( $row ) {
477 if ( $row ) { // page found
478 if ( isset( $row->page_id
) ) {
479 $this->mArticleID
= (int)$row->page_id
;
481 if ( isset( $row->page_len
) ) {
482 $this->mLength
= (int)$row->page_len
;
484 if ( isset( $row->page_is_redirect
) ) {
485 $this->mRedirect
= (bool)$row->page_is_redirect
;
487 if ( isset( $row->page_latest
) ) {
488 $this->mLatestID
= (int)$row->page_latest
;
490 if ( !$this->mForcedContentModel
&& isset( $row->page_content_model
) ) {
491 $this->mContentModel
= strval( $row->page_content_model
);
492 } elseif ( !$this->mForcedContentModel
) {
493 $this->mContentModel
= false; # initialized lazily in getContentModel()
495 if ( isset( $row->page_lang
) ) {
496 $this->mDbPageLanguage
= (string)$row->page_lang
;
498 if ( isset( $row->page_restrictions
) ) {
499 $this->mOldRestrictions
= $row->page_restrictions
;
501 } else { // page not found
502 $this->mArticleID
= 0;
504 $this->mRedirect
= false;
505 $this->mLatestID
= 0;
506 if ( !$this->mForcedContentModel
) {
507 $this->mContentModel
= false; # initialized lazily in getContentModel()
513 * Create a new Title from a namespace index and a DB key.
515 * It's assumed that $ns and $title are safe, for instance when
516 * they came directly from the database or a special page name,
517 * not from user input.
519 * No validation is applied. For convenience, spaces are normalized
520 * to underscores, so that e.g. user_text fields can be used directly.
522 * @note This method may return Title objects that are "invalid"
523 * according to the isValid() method. This is usually caused by
524 * configuration changes: e.g. a namespace that was once defined is
525 * no longer configured, or a character that was once allowed in
526 * titles is now forbidden.
528 * @param int $ns The namespace of the article
529 * @param string $title The unprefixed database key form
530 * @param string $fragment The link fragment (after the "#")
531 * @param string $interwiki The interwiki prefix
532 * @return Title The new object
534 public static function makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
536 $t->mInterwiki
= $interwiki;
537 $t->mFragment
= $fragment;
538 $t->mNamespace
= $ns = intval( $ns );
539 $t->mDbkeyform
= strtr( $title, ' ', '_' );
540 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
541 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
542 $t->mTextform
= strtr( $title, '_', ' ' );
543 $t->mContentModel
= false; # initialized lazily in getContentModel()
548 * Create a new Title from a namespace index and a DB key.
549 * The parameters will be checked for validity, which is a bit slower
550 * than makeTitle() but safer for user-provided data.
552 * Title objects returned by makeTitleSafe() are guaranteed to be valid,
553 * that is, they return true from the isValid() method. If no valid Title
554 * can be constructed from the input, this method returns null.
556 * @param int $ns The namespace of the article
557 * @param string $title Database key form
558 * @param string $fragment The link fragment (after the "#")
559 * @param string $interwiki Interwiki prefix
560 * @return Title|null The new object, or null on an error
562 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
563 // NOTE: ideally, this would just call makeTitle() and then isValid(),
564 // but presently, that means more overhead on a potential performance hotspot.
566 if ( !MWNamespace
::exists( $ns ) ) {
571 $t->mDbkeyform
= self
::makeName( $ns, $title, $fragment, $interwiki, true );
574 $t->secureAndSplit();
576 } catch ( MalformedTitleException
$ex ) {
582 * Create a new Title for the Main Page
584 * @return Title The new object
586 public static function newMainPage() {
587 $title = self
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
588 // Don't give fatal errors if the message is broken
590 $title = self
::newFromText( 'Main Page' );
596 * Get the prefixed DB key associated with an ID
598 * @param int $id The page_id of the article
599 * @return Title|null An object representing the article, or null if no such article was found
601 public static function nameOf( $id ) {
602 $dbr = wfGetDB( DB_REPLICA
);
604 $s = $dbr->selectRow(
606 [ 'page_namespace', 'page_title' ],
607 [ 'page_id' => $id ],
610 if ( $s === false ) {
614 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
619 * Get a regex character class describing the legal characters in a link
621 * @return string The list of characters, not delimited
623 public static function legalChars() {
624 global $wgLegalTitleChars;
625 return $wgLegalTitleChars;
629 * Returns a simple regex that will match on characters and sequences invalid in titles.
630 * Note that this doesn't pick up many things that could be wrong with titles, but that
631 * replacing this regex with something valid will make many titles valid.
633 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
635 * @return string Regex string
637 static function getTitleInvalidRegex() {
638 wfDeprecated( __METHOD__
, '1.25' );
639 return MediaWikiTitleCodec
::getTitleInvalidRegex();
643 * Utility method for converting a character sequence from bytes to Unicode.
645 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
646 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
648 * @param string $byteClass
651 public static function convertByteClassToUnicodeClass( $byteClass ) {
652 $length = strlen( $byteClass );
654 $x0 = $x1 = $x2 = '';
656 $d0 = $d1 = $d2 = '';
657 // Decoded integer codepoints
658 $ord0 = $ord1 = $ord2 = 0;
660 $r0 = $r1 = $r2 = '';
664 $allowUnicode = false;
665 for ( $pos = 0; $pos < $length; $pos++
) {
666 // Shift the queues down
675 // Load the current input token and decoded values
676 $inChar = $byteClass[$pos];
677 if ( $inChar == '\\' ) {
678 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
679 $x0 = $inChar . $m[0];
680 $d0 = chr( hexdec( $m[1] ) );
681 $pos +
= strlen( $m[0] );
682 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
683 $x0 = $inChar . $m[0];
684 $d0 = chr( octdec( $m[0] ) );
685 $pos +
= strlen( $m[0] );
686 } elseif ( $pos +
1 >= $length ) {
689 $d0 = $byteClass[$pos +
1];
697 // Load the current re-encoded value
698 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
699 $r0 = sprintf( '\x%02x', $ord0 );
700 } elseif ( $ord0 >= 0x80 ) {
701 // Allow unicode if a single high-bit character appears
702 $r0 = sprintf( '\x%02x', $ord0 );
703 $allowUnicode = true;
704 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
710 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
712 if ( $ord2 > $ord0 ) {
714 } elseif ( $ord0 >= 0x80 ) {
716 $allowUnicode = true;
717 if ( $ord2 < 0x80 ) {
718 // Keep the non-unicode section of the range
725 // Reset state to the initial value
726 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
727 } elseif ( $ord2 < 0x80 ) {
732 if ( $ord1 < 0x80 ) {
735 if ( $ord0 < 0x80 ) {
738 if ( $allowUnicode ) {
739 $out .= '\u0080-\uFFFF';
745 * Make a prefixed DB key from a DB key and a namespace index
747 * @param int $ns Numerical representation of the namespace
748 * @param string $title The DB key form the title
749 * @param string $fragment The link fragment (after the "#")
750 * @param string $interwiki The interwiki prefix
751 * @param bool $canonicalNamespace If true, use the canonical name for
752 * $ns instead of the localized version.
753 * @return string The prefixed form of the title
755 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
756 $canonicalNamespace = false
760 if ( $canonicalNamespace ) {
761 $namespace = MWNamespace
::getCanonicalName( $ns );
763 $namespace = $wgContLang->getNsText( $ns );
765 $name = $namespace == '' ?
$title : "$namespace:$title";
766 if ( strval( $interwiki ) != '' ) {
767 $name = "$interwiki:$name";
769 if ( strval( $fragment ) != '' ) {
770 $name .= '#' . $fragment;
776 * Escape a text fragment, say from a link, for a URL
778 * @deprecated since 1.30, use Sanitizer::escapeIdForLink() or escapeIdForExternalInterwiki()
780 * @param string $fragment Containing a URL or link fragment (after the "#")
781 * @return string Escaped string
783 static function escapeFragmentForURL( $fragment ) {
784 wfDeprecated( __METHOD__
, '1.30' );
785 # Note that we don't urlencode the fragment. urlencoded Unicode
786 # fragments appear not to work in IE (at least up to 7) or in at least
787 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
788 # to care if they aren't encoded.
789 return Sanitizer
::escapeId( $fragment, 'noninitial' );
793 * Callback for usort() to do title sorts by (namespace, title)
795 * @param LinkTarget $a
796 * @param LinkTarget $b
798 * @return int Result of string comparison, or namespace comparison
800 public static function compare( LinkTarget
$a, LinkTarget
$b ) {
801 if ( $a->getNamespace() == $b->getNamespace() ) {
802 return strcmp( $a->getText(), $b->getText() );
804 return $a->getNamespace() - $b->getNamespace();
809 * Returns true if the title is valid, false if it is invalid.
811 * Valid titles can be round-tripped via makeTitleSafe() and newFromText().
812 * Invalid titles may get returned from makeTitle(), and it may be useful to
813 * allow them to exist, e.g. in order to process log entries about pages in
814 * namespaces that belong to extensions that are no longer installed.
816 * @note This method is relatively expensive. When constructing Title
817 * objects that need to be valid, use an instantiator method that is guaranteed
818 * to return valid titles, such as makeTitleSafe() or newFromText().
822 public function isValid() {
823 $ns = $this->getNamespace();
825 if ( !MWNamespace
::exists( $ns ) ) {
830 $parser = MediaWikiServices
::getInstance()->getTitleParser();
831 $parser->parseTitle( $this->getDBkey(), $ns );
833 } catch ( MalformedTitleException
$ex ) {
839 * Determine whether the object refers to a page within
840 * this project (either this wiki or a wiki with a local
841 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
843 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
845 public function isLocal() {
846 if ( $this->isExternal() ) {
847 $iw = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
849 return $iw->isLocal();
856 * Is this Title interwiki?
860 public function isExternal() {
861 return $this->mInterwiki
!== '';
865 * Get the interwiki prefix
867 * Use Title::isExternal to check if a interwiki is set
869 * @return string Interwiki prefix
871 public function getInterwiki() {
872 return $this->mInterwiki
;
876 * Was this a local interwiki link?
880 public function wasLocalInterwiki() {
881 return $this->mLocalInterwiki
;
885 * Determine whether the object refers to a page within
886 * this project and is transcludable.
888 * @return bool True if this is transcludable
890 public function isTrans() {
891 if ( !$this->isExternal() ) {
895 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isTranscludable();
899 * Returns the DB name of the distant wiki which owns the object.
901 * @return string|false The DB name
903 public function getTransWikiID() {
904 if ( !$this->isExternal() ) {
908 return self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->getWikiID();
912 * Get a TitleValue object representing this Title.
914 * @note Not all valid Titles have a corresponding valid TitleValue
915 * (e.g. TitleValues cannot represent page-local links that have a
916 * fragment but no title text).
918 * @return TitleValue|null
920 public function getTitleValue() {
921 if ( $this->mTitleValue
=== null ) {
923 $this->mTitleValue
= new TitleValue(
924 $this->getNamespace(),
926 $this->getFragment(),
927 $this->getInterwiki()
929 } catch ( InvalidArgumentException
$ex ) {
930 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
931 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
935 return $this->mTitleValue
;
939 * Get the text form (spaces not underscores) of the main part
941 * @return string Main part of the title
943 public function getText() {
944 return $this->mTextform
;
948 * Get the URL-encoded form of the main part
950 * @return string Main part of the title, URL-encoded
952 public function getPartialURL() {
953 return $this->mUrlform
;
957 * Get the main part with underscores
959 * @return string Main part of the title, with underscores
961 public function getDBkey() {
962 return $this->mDbkeyform
;
966 * Get the DB key with the initial letter case as specified by the user
968 * @return string DB key
970 function getUserCaseDBKey() {
971 if ( !is_null( $this->mUserCaseDBKey
) ) {
972 return $this->mUserCaseDBKey
;
974 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
975 return $this->mDbkeyform
;
980 * Get the namespace index, i.e. one of the NS_xxxx constants.
982 * @return int Namespace index
984 public function getNamespace() {
985 return $this->mNamespace
;
989 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
991 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
992 * @return string Content model id
994 public function getContentModel( $flags = 0 ) {
995 if ( !$this->mForcedContentModel
996 && ( !$this->mContentModel ||
$flags === self
::GAID_FOR_UPDATE
)
997 && $this->getArticleID( $flags )
999 $linkCache = LinkCache
::singleton();
1000 $linkCache->addLinkObj( $this ); # in case we already had an article ID
1001 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
1004 if ( !$this->mContentModel
) {
1005 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
1008 return $this->mContentModel
;
1012 * Convenience method for checking a title's content model name
1014 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
1015 * @return bool True if $this->getContentModel() == $id
1017 public function hasContentModel( $id ) {
1018 return $this->getContentModel() == $id;
1022 * Set a proposed content model for the page for permissions
1023 * checking. This does not actually change the content model
1026 * Additionally, you should make sure you've checked
1027 * ContentHandler::canBeUsedOn() first.
1030 * @param string $model CONTENT_MODEL_XXX constant
1032 public function setContentModel( $model ) {
1033 $this->mContentModel
= $model;
1034 $this->mForcedContentModel
= true;
1038 * Get the namespace text
1040 * @return string|false Namespace text
1042 public function getNsText() {
1043 if ( $this->isExternal() ) {
1044 // This probably shouldn't even happen,
1045 // but for interwiki transclusion it sometimes does.
1046 // Use the canonical namespaces if possible to try to
1047 // resolve a foreign namespace.
1048 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1049 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1054 $formatter = self
::getTitleFormatter();
1055 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1056 } catch ( InvalidArgumentException
$ex ) {
1057 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1063 * Get the namespace text of the subject (rather than talk) page
1065 * @return string Namespace text
1067 public function getSubjectNsText() {
1069 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1073 * Get the namespace text of the talk page
1075 * @return string Namespace text
1077 public function getTalkNsText() {
1079 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1083 * Can this title have a corresponding talk page?
1085 * @deprecated since 1.30, use canHaveTalkPage() instead.
1087 * @return bool True if this title either is a talk page or can have a talk page associated.
1089 public function canTalk() {
1090 return $this->canHaveTalkPage();
1094 * Can this title have a corresponding talk page?
1096 * @see MWNamespace::hasTalkNamespace
1099 * @return bool True if this title either is a talk page or can have a talk page associated.
1101 public function canHaveTalkPage() {
1102 return MWNamespace
::hasTalkNamespace( $this->mNamespace
);
1106 * Is this in a namespace that allows actual pages?
1110 public function canExist() {
1111 return $this->mNamespace
>= NS_MAIN
;
1115 * Can this title be added to a user's watchlist?
1119 public function isWatchable() {
1120 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1124 * Returns true if this is a special page.
1128 public function isSpecialPage() {
1129 return $this->getNamespace() == NS_SPECIAL
;
1133 * Returns true if this title resolves to the named special page
1135 * @param string $name The special page name
1138 public function isSpecial( $name ) {
1139 if ( $this->isSpecialPage() ) {
1140 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1141 if ( $name == $thisName ) {
1149 * If the Title refers to a special page alias which is not the local default, resolve
1150 * the alias, and localise the name as necessary. Otherwise, return $this
1154 public function fixSpecialName() {
1155 if ( $this->isSpecialPage() ) {
1156 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1157 if ( $canonicalName ) {
1158 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1159 if ( $localName != $this->mDbkeyform
) {
1160 return self
::makeTitle( NS_SPECIAL
, $localName );
1168 * Returns true if the title is inside the specified namespace.
1170 * Please make use of this instead of comparing to getNamespace()
1171 * This function is much more resistant to changes we may make
1172 * to namespaces than code that makes direct comparisons.
1173 * @param int $ns The namespace
1177 public function inNamespace( $ns ) {
1178 return MWNamespace
::equals( $this->getNamespace(), $ns );
1182 * Returns true if the title is inside one of the specified namespaces.
1184 * @param int|int[] $namespaces,... The namespaces to check for
1188 public function inNamespaces( /* ... */ ) {
1189 $namespaces = func_get_args();
1190 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1191 $namespaces = $namespaces[0];
1194 foreach ( $namespaces as $ns ) {
1195 if ( $this->inNamespace( $ns ) ) {
1204 * Returns true if the title has the same subject namespace as the
1205 * namespace specified.
1206 * For example this method will take NS_USER and return true if namespace
1207 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1208 * as their subject namespace.
1210 * This is MUCH simpler than individually testing for equivalence
1211 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1216 public function hasSubjectNamespace( $ns ) {
1217 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1221 * Is this Title in a namespace which contains content?
1222 * In other words, is this a content page, for the purposes of calculating
1227 public function isContentPage() {
1228 return MWNamespace
::isContent( $this->getNamespace() );
1232 * Would anybody with sufficient privileges be able to move this page?
1233 * Some pages just aren't movable.
1237 public function isMovable() {
1238 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1239 // Interwiki title or immovable namespace. Hooks don't get to override here
1244 Hooks
::run( 'TitleIsMovable', [ $this, &$result ] );
1249 * Is this the mainpage?
1250 * @note Title::newFromText seems to be sufficiently optimized by the title
1251 * cache that we don't need to over-optimize by doing direct comparisons and
1252 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1253 * ends up reporting something differently than $title->isMainPage();
1258 public function isMainPage() {
1259 return $this->equals( self
::newMainPage() );
1263 * Is this a subpage?
1267 public function isSubpage() {
1268 return MWNamespace
::hasSubpages( $this->mNamespace
)
1269 ?
strpos( $this->getText(), '/' ) !== false
1274 * Is this a conversion table for the LanguageConverter?
1278 public function isConversionTable() {
1279 // @todo ConversionTable should become a separate content model.
1281 return $this->getNamespace() == NS_MEDIAWIKI
&&
1282 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1286 * Does that page contain wikitext, or it is JS, CSS or whatever?
1290 public function isWikitextPage() {
1291 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1295 * Could this page contain custom CSS or JavaScript for the global UI.
1296 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1297 * or CONTENT_MODEL_JAVASCRIPT.
1299 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1302 * Note that this method should not return true for pages that contain and
1303 * show "inactive" CSS or JS.
1306 * @todo FIXME: Rename to isSiteConfigPage() and remove deprecated hook
1308 public function isCssOrJsPage() {
1309 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1310 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1311 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1313 return $isCssOrJsPage;
1317 * Is this a .css or .js subpage of a user page?
1319 * @todo FIXME: Rename to isUserConfigPage()
1321 public function isCssJsSubpage() {
1322 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1323 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1324 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1328 * Trim down a .css or .js subpage title to get the corresponding skin name
1330 * @return string Containing skin name from .css or .js subpage title
1332 public function getSkinFromCssJsSubpage() {
1333 $subpage = explode( '/', $this->mTextform
);
1334 $subpage = $subpage[count( $subpage ) - 1];
1335 $lastdot = strrpos( $subpage, '.' );
1336 if ( $lastdot === false ) {
1337 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1339 return substr( $subpage, 0, $lastdot );
1343 * Is this a .css subpage of a user page?
1347 public function isCssSubpage() {
1348 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1349 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1353 * Is this a .js subpage of a user page?
1357 public function isJsSubpage() {
1358 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1359 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1363 * Is this a talk page of some sort?
1367 public function isTalkPage() {
1368 return MWNamespace
::isTalk( $this->getNamespace() );
1372 * Get a Title object associated with the talk page of this article
1374 * @return Title The object for the talk page
1376 public function getTalkPage() {
1377 return self
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1381 * Get a Title object associated with the talk page of this article,
1382 * if such a talk page can exist.
1386 * @return Title|null The object for the talk page,
1387 * or null if no associated talk page can exist, according to canHaveTalkPage().
1389 public function getTalkPageIfDefined() {
1390 if ( !$this->canHaveTalkPage() ) {
1394 return $this->getTalkPage();
1398 * Get a title object associated with the subject page of this
1401 * @return Title The object for the subject page
1403 public function getSubjectPage() {
1404 // Is this the same title?
1405 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1406 if ( $this->getNamespace() == $subjectNS ) {
1409 return self
::makeTitle( $subjectNS, $this->getDBkey() );
1413 * Get the other title for this page, if this is a subject page
1414 * get the talk page, if it is a subject page get the talk page
1417 * @throws MWException If the page doesn't have an other page
1420 public function getOtherPage() {
1421 if ( $this->isSpecialPage() ) {
1422 throw new MWException( 'Special pages cannot have other pages' );
1424 if ( $this->isTalkPage() ) {
1425 return $this->getSubjectPage();
1427 if ( !$this->canHaveTalkPage() ) {
1428 throw new MWException( "{$this->getPrefixedText()} does not have an other page" );
1430 return $this->getTalkPage();
1435 * Get the default namespace index, for when there is no namespace
1437 * @return int Default namespace index
1439 public function getDefaultNamespace() {
1440 return $this->mDefaultNamespace
;
1444 * Get the Title fragment (i.e.\ the bit after the #) in text form
1446 * Use Title::hasFragment to check for a fragment
1448 * @return string Title fragment
1450 public function getFragment() {
1451 return $this->mFragment
;
1455 * Check if a Title fragment is set
1460 public function hasFragment() {
1461 return $this->mFragment
!== '';
1465 * Get the fragment in URL form, including the "#" character if there is one
1467 * @return string Fragment in URL form
1469 public function getFragmentForURL() {
1470 if ( !$this->hasFragment() ) {
1472 } elseif ( $this->isExternal()
1473 && !self
::getInterwikiLookup()->fetch( $this->mInterwiki
)->isLocal()
1475 return '#' . Sanitizer
::escapeIdForExternalInterwiki( $this->getFragment() );
1477 return '#' . Sanitizer
::escapeIdForLink( $this->getFragment() );
1481 * Set the fragment for this title. Removes the first character from the
1482 * specified fragment before setting, so it assumes you're passing it with
1485 * Deprecated for public use, use Title::makeTitle() with fragment parameter,
1486 * or Title::createFragmentTarget().
1487 * Still in active use privately.
1490 * @param string $fragment Text
1492 public function setFragment( $fragment ) {
1493 $this->mFragment
= strtr( substr( $fragment, 1 ), '_', ' ' );
1497 * Creates a new Title for a different fragment of the same page.
1500 * @param string $fragment
1503 public function createFragmentTarget( $fragment ) {
1504 return self
::makeTitle(
1505 $this->getNamespace(),
1508 $this->getInterwiki()
1513 * Prefix some arbitrary text with the namespace or interwiki prefix
1516 * @param string $name The text
1517 * @return string The prefixed text
1519 private function prefix( $name ) {
1523 if ( $this->isExternal() ) {
1524 $p = $this->mInterwiki
. ':';
1527 if ( 0 != $this->mNamespace
) {
1528 $nsText = $this->getNsText();
1530 if ( $nsText === false ) {
1531 // See T165149. Awkward, but better than erroneously linking to the main namespace.
1532 $nsText = $wgContLang->getNsText( NS_SPECIAL
) . ":Badtitle/NS{$this->mNamespace}";
1535 $p .= $nsText . ':';
1541 * Get the prefixed database key form
1543 * @return string The prefixed title, with underscores and
1544 * any interwiki and namespace prefixes
1546 public function getPrefixedDBkey() {
1547 $s = $this->prefix( $this->mDbkeyform
);
1548 $s = strtr( $s, ' ', '_' );
1553 * Get the prefixed title with spaces.
1554 * This is the form usually used for display
1556 * @return string The prefixed title, with spaces
1558 public function getPrefixedText() {
1559 if ( $this->mPrefixedText
=== null ) {
1560 $s = $this->prefix( $this->mTextform
);
1561 $s = strtr( $s, '_', ' ' );
1562 $this->mPrefixedText
= $s;
1564 return $this->mPrefixedText
;
1568 * Return a string representation of this title
1570 * @return string Representation of this title
1572 public function __toString() {
1573 return $this->getPrefixedText();
1577 * Get the prefixed title with spaces, plus any fragment
1578 * (part beginning with '#')
1580 * @return string The prefixed title, with spaces and the fragment, including '#'
1582 public function getFullText() {
1583 $text = $this->getPrefixedText();
1584 if ( $this->hasFragment() ) {
1585 $text .= '#' . $this->getFragment();
1591 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1595 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1599 * @return string Root name
1602 public function getRootText() {
1603 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1604 return $this->getText();
1607 return strtok( $this->getText(), '/' );
1611 * Get the root page name title, i.e. the leftmost part before any slashes
1615 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1616 * # returns: Title{User:Foo}
1619 * @return Title Root title
1622 public function getRootTitle() {
1623 return self
::makeTitle( $this->getNamespace(), $this->getRootText() );
1627 * Get the base page name without a namespace, i.e. the part before the subpage name
1631 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1632 * # returns: 'Foo/Bar'
1635 * @return string Base name
1637 public function getBaseText() {
1638 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1639 return $this->getText();
1642 $parts = explode( '/', $this->getText() );
1643 # Don't discard the real title if there's no subpage involved
1644 if ( count( $parts ) > 1 ) {
1645 unset( $parts[count( $parts ) - 1] );
1647 return implode( '/', $parts );
1651 * Get the base page name title, i.e. the part before the subpage name
1655 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1656 * # returns: Title{User:Foo/Bar}
1659 * @return Title Base title
1662 public function getBaseTitle() {
1663 return self
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1667 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1671 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1675 * @return string Subpage name
1677 public function getSubpageText() {
1678 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1679 return $this->mTextform
;
1681 $parts = explode( '/', $this->mTextform
);
1682 return $parts[count( $parts ) - 1];
1686 * Get the title for a subpage of the current page
1690 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1691 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1694 * @param string $text The subpage name to add to the title
1695 * @return Title Subpage title
1698 public function getSubpage( $text ) {
1699 return self
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1703 * Get a URL-encoded form of the subpage text
1705 * @return string URL-encoded subpage name
1707 public function getSubpageUrlForm() {
1708 $text = $this->getSubpageText();
1709 $text = wfUrlencode( strtr( $text, ' ', '_' ) );
1714 * Get a URL-encoded title (not an actual URL) including interwiki
1716 * @return string The URL-encoded form
1718 public function getPrefixedURL() {
1719 $s = $this->prefix( $this->mDbkeyform
);
1720 $s = wfUrlencode( strtr( $s, ' ', '_' ) );
1725 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1726 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1727 * second argument named variant. This was deprecated in favor
1728 * of passing an array of option with a "variant" key
1729 * Once $query2 is removed for good, this helper can be dropped
1730 * and the wfArrayToCgi moved to getLocalURL();
1732 * @since 1.19 (r105919)
1733 * @param array|string $query
1734 * @param string|string[]|bool $query2
1737 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1738 if ( $query2 !== false ) {
1739 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1740 "method called with a second parameter is deprecated. Add your " .
1741 "parameter to an array passed as the first parameter.", "1.19" );
1743 if ( is_array( $query ) ) {
1744 $query = wfArrayToCgi( $query );
1747 if ( is_string( $query2 ) ) {
1748 // $query2 is a string, we will consider this to be
1749 // a deprecated $variant argument and add it to the query
1750 $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
1752 $query2 = wfArrayToCgi( $query2 );
1754 // If we have $query content add a & to it first
1758 // Now append the queries together
1765 * Get a real URL referring to this title, with interwiki link and
1768 * @see self::getLocalURL for the arguments.
1770 * @param string|string[] $query
1771 * @param string|string[]|bool $query2
1772 * @param string $proto Protocol type to use in URL
1773 * @return string The URL
1775 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1776 $query = self
::fixUrlQueryArgs( $query, $query2 );
1778 # Hand off all the decisions on urls to getLocalURL
1779 $url = $this->getLocalURL( $query );
1781 # Expand the url to make it a full url. Note that getLocalURL has the
1782 # potential to output full urls for a variety of reasons, so we use
1783 # wfExpandUrl instead of simply prepending $wgServer
1784 $url = wfExpandUrl( $url, $proto );
1786 # Finally, add the fragment.
1787 $url .= $this->getFragmentForURL();
1788 // Avoid PHP 7.1 warning from passing $this by reference
1790 Hooks
::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
1795 * Get a url appropriate for making redirects based on an untrusted url arg
1797 * This is basically the same as getFullUrl(), but in the case of external
1798 * interwikis, we send the user to a landing page, to prevent possible
1799 * phishing attacks and the like.
1801 * @note Uses current protocol by default, since technically relative urls
1802 * aren't allowed in redirects per HTTP spec, so this is not suitable for
1803 * places where the url gets cached, as might pollute between
1804 * https and non-https users.
1805 * @see self::getLocalURL for the arguments.
1806 * @param array|string $query
1807 * @param string $proto Protocol type to use in URL
1808 * @return string A url suitable to use in an HTTP location header.
1810 public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT
) {
1812 if ( $this->isExternal() ) {
1813 $target = SpecialPage
::getTitleFor(
1815 $this->getPrefixedDBKey()
1818 return $target->getFullUrl( $query, false, $proto );
1822 * Get a URL with no fragment or server name (relative URL) from a Title object.
1823 * If this page is generated with action=render, however,
1824 * $wgServer is prepended to make an absolute URL.
1826 * @see self::getFullURL to always get an absolute URL.
1827 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1828 * valid to link, locally, to the current Title.
1829 * @see self::newFromText to produce a Title object.
1831 * @param string|string[] $query An optional query string,
1832 * not used for interwiki links. Can be specified as an associative array as well,
1833 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1834 * Some query patterns will trigger various shorturl path replacements.
1835 * @param string|string[]|bool $query2 An optional secondary query array. This one MUST
1836 * be an array. If a string is passed it will be interpreted as a deprecated
1837 * variant argument and urlencoded into a variant= argument.
1838 * This second query argument will be added to the $query
1839 * The second parameter is deprecated since 1.19. Pass it as a key,value
1840 * pair in the first parameter array instead.
1842 * @return string String of the URL.
1844 public function getLocalURL( $query = '', $query2 = false ) {
1845 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1847 $query = self
::fixUrlQueryArgs( $query, $query2 );
1849 $interwiki = self
::getInterwikiLookup()->fetch( $this->mInterwiki
);
1851 $namespace = $this->getNsText();
1852 if ( $namespace != '' ) {
1853 # Can this actually happen? Interwikis shouldn't be parsed.
1854 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1857 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1858 $url = wfAppendQuery( $url, $query );
1860 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1861 if ( $query == '' ) {
1862 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1863 // Avoid PHP 7.1 warning from passing $this by reference
1865 Hooks
::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
1867 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1871 if ( !empty( $wgActionPaths )
1872 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1874 $action = urldecode( $matches[2] );
1875 if ( isset( $wgActionPaths[$action] ) ) {
1876 $query = $matches[1];
1877 if ( isset( $matches[4] ) ) {
1878 $query .= $matches[4];
1880 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1881 if ( $query != '' ) {
1882 $url = wfAppendQuery( $url, $query );
1888 && $wgVariantArticlePath
1889 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1890 && $this->getPageLanguage()->equals( $wgContLang )
1891 && $this->getPageLanguage()->hasVariants()
1893 $variant = urldecode( $matches[1] );
1894 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1895 // Only do the variant replacement if the given variant is a valid
1896 // variant for the page's language.
1897 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1898 $url = str_replace( '$1', $dbkey, $url );
1902 if ( $url === false ) {
1903 if ( $query == '-' ) {
1906 $url = "{$wgScript}?title={$dbkey}&{$query}";
1909 // Avoid PHP 7.1 warning from passing $this by reference
1911 Hooks
::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
1913 // @todo FIXME: This causes breakage in various places when we
1914 // actually expected a local URL and end up with dupe prefixes.
1915 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1916 $url = $wgServer . $url;
1919 // Avoid PHP 7.1 warning from passing $this by reference
1921 Hooks
::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
1926 * Get a URL that's the simplest URL that will be valid to link, locally,
1927 * to the current Title. It includes the fragment, but does not include
1928 * the server unless action=render is used (or the link is external). If
1929 * there's a fragment but the prefixed text is empty, we just return a link
1932 * The result obviously should not be URL-escaped, but does need to be
1933 * HTML-escaped if it's being output in HTML.
1935 * @param string|string[] $query
1936 * @param bool $query2
1937 * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
1938 * or false (default) for no expansion
1939 * @see self::getLocalURL for the arguments.
1940 * @return string The URL
1942 public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
1943 if ( $this->isExternal() ||
$proto !== false ) {
1944 $ret = $this->getFullURL( $query, $query2, $proto );
1945 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1946 $ret = $this->getFragmentForURL();
1948 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1954 * Get the URL form for an internal link.
1955 * - Used in various CDN-related code, in case we have a different
1956 * internal hostname for the server from the exposed one.
1958 * This uses $wgInternalServer to qualify the path, or $wgServer
1959 * if $wgInternalServer is not set. If the server variable used is
1960 * protocol-relative, the URL will be expanded to http://
1962 * @see self::getLocalURL for the arguments.
1963 * @param string $query
1964 * @param string|bool $query2
1965 * @return string The URL
1967 public function getInternalURL( $query = '', $query2 = false ) {
1968 global $wgInternalServer, $wgServer;
1969 $query = self
::fixUrlQueryArgs( $query, $query2 );
1970 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1971 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1972 // Avoid PHP 7.1 warning from passing $this by reference
1974 Hooks
::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
1979 * Get the URL for a canonical link, for use in things like IRC and
1980 * e-mail notifications. Uses $wgCanonicalServer and the
1981 * GetCanonicalURL hook.
1983 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1985 * @see self::getLocalURL for the arguments.
1986 * @param string $query
1987 * @param string|bool $query2
1988 * @return string The URL
1991 public function getCanonicalURL( $query = '', $query2 = false ) {
1992 $query = self
::fixUrlQueryArgs( $query, $query2 );
1993 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1994 // Avoid PHP 7.1 warning from passing $this by reference
1996 Hooks
::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
2001 * Get the edit URL for this Title
2003 * @return string The URL, or a null string if this is an interwiki link
2005 public function getEditURL() {
2006 if ( $this->isExternal() ) {
2009 $s = $this->getLocalURL( 'action=edit' );
2015 * Can $user perform $action on this page?
2016 * This skips potentially expensive cascading permission checks
2017 * as well as avoids expensive error formatting
2019 * Suitable for use for nonessential UI controls in common cases, but
2020 * _not_ for functional access control.
2022 * May provide false positives, but should never provide a false negative.
2024 * @param string $action Action that permission needs to be checked for
2025 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
2028 public function quickUserCan( $action, $user = null ) {
2029 return $this->userCan( $action, $user, false );
2033 * Can $user perform $action on this page?
2035 * @param string $action Action that permission needs to be checked for
2036 * @param User $user User to check (since 1.19); $wgUser will be used if not
2038 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2041 public function userCan( $action, $user = null, $rigor = 'secure' ) {
2042 if ( !$user instanceof User
) {
2047 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
2051 * Can $user perform $action on this page?
2053 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
2055 * @param string $action Action that permission needs to be checked for
2056 * @param User $user User to check
2057 * @param string $rigor One of (quick,full,secure)
2058 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2059 * - full : does cheap and expensive checks possibly from a replica DB
2060 * - secure : does cheap and expensive checks, using the master as needed
2061 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
2062 * whose corresponding errors may be ignored.
2063 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2065 public function getUserPermissionsErrors(
2066 $action, $user, $rigor = 'secure', $ignoreErrors = []
2068 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
2070 // Remove the errors being ignored.
2071 foreach ( $errors as $index => $error ) {
2072 $errKey = is_array( $error ) ?
$error[0] : $error;
2074 if ( in_array( $errKey, $ignoreErrors ) ) {
2075 unset( $errors[$index] );
2077 if ( $errKey instanceof MessageSpecifier
&& in_array( $errKey->getKey(), $ignoreErrors ) ) {
2078 unset( $errors[$index] );
2086 * Permissions checks that fail most often, and which are easiest to test.
2088 * @param string $action The action to check
2089 * @param User $user User to check
2090 * @param array $errors List of current errors
2091 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2092 * @param bool $short Short circuit on first error
2094 * @return array List of errors
2096 private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
2097 if ( !Hooks
::run( 'TitleQuickPermissions',
2098 [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
2103 if ( $action == 'create' ) {
2105 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
2106 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
2108 $errors[] = $user->isAnon() ?
[ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
2110 } elseif ( $action == 'move' ) {
2111 if ( !$user->isAllowed( 'move-rootuserpages' )
2112 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2113 // Show user page-specific message only if the user can move other pages
2114 $errors[] = [ 'cant-move-user-page' ];
2117 // Check if user is allowed to move files if it's a file
2118 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
2119 $errors[] = [ 'movenotallowedfile' ];
2122 // Check if user is allowed to move category pages if it's a category page
2123 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
2124 $errors[] = [ 'cant-move-category-page' ];
2127 if ( !$user->isAllowed( 'move' ) ) {
2128 // User can't move anything
2129 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2130 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2131 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2132 // custom message if logged-in users without any special rights can move
2133 $errors[] = [ 'movenologintext' ];
2135 $errors[] = [ 'movenotallowed' ];
2138 } elseif ( $action == 'move-target' ) {
2139 if ( !$user->isAllowed( 'move' ) ) {
2140 // User can't move anything
2141 $errors[] = [ 'movenotallowed' ];
2142 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2143 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2144 // Show user page-specific message only if the user can move other pages
2145 $errors[] = [ 'cant-move-to-user-page' ];
2146 } elseif ( !$user->isAllowed( 'move-categorypages' )
2147 && $this->mNamespace
== NS_CATEGORY
) {
2148 // Show category page-specific message only if the user can move other pages
2149 $errors[] = [ 'cant-move-to-category-page' ];
2151 } elseif ( !$user->isAllowed( $action ) ) {
2152 $errors[] = $this->missingPermissionError( $action, $short );
2159 * Add the resulting error code to the errors array
2161 * @param array $errors List of current errors
2162 * @param array $result Result of errors
2164 * @return array List of errors
2166 private function resultToError( $errors, $result ) {
2167 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2168 // A single array representing an error
2169 $errors[] = $result;
2170 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2171 // A nested array representing multiple errors
2172 $errors = array_merge( $errors, $result );
2173 } elseif ( $result !== '' && is_string( $result ) ) {
2174 // A string representing a message-id
2175 $errors[] = [ $result ];
2176 } elseif ( $result instanceof MessageSpecifier
) {
2177 // A message specifier representing an error
2178 $errors[] = [ $result ];
2179 } elseif ( $result === false ) {
2180 // a generic "We don't want them to do that"
2181 $errors[] = [ 'badaccess-group0' ];
2187 * Check various permission hooks
2189 * @param string $action The action to check
2190 * @param User $user User to check
2191 * @param array $errors List of current errors
2192 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2193 * @param bool $short Short circuit on first error
2195 * @return array List of errors
2197 private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
2198 // Use getUserPermissionsErrors instead
2200 // Avoid PHP 7.1 warning from passing $this by reference
2202 if ( !Hooks
::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
2203 return $result ?
[] : [ [ 'badaccess-group0' ] ];
2205 // Check getUserPermissionsErrors hook
2206 // Avoid PHP 7.1 warning from passing $this by reference
2208 if ( !Hooks
::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
2209 $errors = $this->resultToError( $errors, $result );
2211 // Check getUserPermissionsErrorsExpensive hook
2214 && !( $short && count( $errors ) > 0 )
2215 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
2217 $errors = $this->resultToError( $errors, $result );
2224 * Check permissions on special pages & namespaces
2226 * @param string $action The action to check
2227 * @param User $user User to check
2228 * @param array $errors List of current errors
2229 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2230 * @param bool $short Short circuit on first error
2232 * @return array List of errors
2234 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
2235 # Only 'createaccount' can be performed on special pages,
2236 # which don't actually exist in the DB.
2237 if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
2238 $errors[] = [ 'ns-specialprotected' ];
2241 # Check $wgNamespaceProtection for restricted namespaces
2242 if ( $this->isNamespaceProtected( $user ) ) {
2243 $ns = $this->mNamespace
== NS_MAIN ?
2244 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2245 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2246 [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
2253 * Check CSS/JS sub-page permissions
2255 * @param string $action The action to check
2256 * @param User $user User to check
2257 * @param array $errors List of current errors
2258 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2259 * @param bool $short Short circuit on first error
2261 * @return array List of errors
2263 private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
2264 # Protect css/js subpages of user pages
2265 # XXX: this might be better using restrictions
2266 if ( $action != 'patrol' ) {
2267 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2268 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2269 $errors[] = [ 'mycustomcssprotected', $action ];
2270 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2271 $errors[] = [ 'mycustomjsprotected', $action ];
2274 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2275 $errors[] = [ 'customcssprotected', $action ];
2276 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2277 $errors[] = [ 'customjsprotected', $action ];
2286 * Check against page_restrictions table requirements on this
2287 * page. The user must possess all required rights for this
2290 * @param string $action The action to check
2291 * @param User $user User to check
2292 * @param array $errors List of current errors
2293 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2294 * @param bool $short Short circuit on first error
2296 * @return array List of errors
2298 private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
2299 foreach ( $this->getRestrictions( $action ) as $right ) {
2300 // Backwards compatibility, rewrite sysop -> editprotected
2301 if ( $right == 'sysop' ) {
2302 $right = 'editprotected';
2304 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2305 if ( $right == 'autoconfirmed' ) {
2306 $right = 'editsemiprotected';
2308 if ( $right == '' ) {
2311 if ( !$user->isAllowed( $right ) ) {
2312 $errors[] = [ 'protectedpagetext', $right, $action ];
2313 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2314 $errors[] = [ 'protectedpagetext', 'protect', $action ];
2322 * Check restrictions on cascading pages.
2324 * @param string $action The action to check
2325 * @param User $user User to check
2326 * @param array $errors List of current errors
2327 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2328 * @param bool $short Short circuit on first error
2330 * @return array List of errors
2332 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
2333 if ( $rigor !== 'quick' && !$this->isCssJsSubpage() ) {
2334 # We /could/ use the protection level on the source page, but it's
2335 # fairly ugly as we have to establish a precedence hierarchy for pages
2336 # included by multiple cascade-protected pages. So just restrict
2337 # it to people with 'protect' permission, as they could remove the
2338 # protection anyway.
2339 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2340 # Cascading protection depends on more than this page...
2341 # Several cascading protected pages may include this page...
2342 # Check each cascading level
2343 # This is only for protection restrictions, not for all actions
2344 if ( isset( $restrictions[$action] ) ) {
2345 foreach ( $restrictions[$action] as $right ) {
2346 // Backwards compatibility, rewrite sysop -> editprotected
2347 if ( $right == 'sysop' ) {
2348 $right = 'editprotected';
2350 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2351 if ( $right == 'autoconfirmed' ) {
2352 $right = 'editsemiprotected';
2354 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2356 foreach ( $cascadingSources as $page ) {
2357 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2359 $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
2369 * Check action permissions not already checked in checkQuickPermissions
2371 * @param string $action The action to check
2372 * @param User $user User to check
2373 * @param array $errors List of current errors
2374 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2375 * @param bool $short Short circuit on first error
2377 * @return array List of errors
2379 private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
2380 global $wgDeleteRevisionsLimit, $wgLang;
2382 if ( $action == 'protect' ) {
2383 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2384 // If they can't edit, they shouldn't protect.
2385 $errors[] = [ 'protect-cantedit' ];
2387 } elseif ( $action == 'create' ) {
2388 $title_protection = $this->getTitleProtection();
2389 if ( $title_protection ) {
2390 if ( $title_protection['permission'] == ''
2391 ||
!$user->isAllowed( $title_protection['permission'] )
2395 User
::whoIs( $title_protection['user'] ),
2396 $title_protection['reason']
2400 } elseif ( $action == 'move' ) {
2401 // Check for immobile pages
2402 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2403 // Specific message for this case
2404 $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
2405 } elseif ( !$this->isMovable() ) {
2406 // Less specific message for rarer cases
2407 $errors[] = [ 'immobile-source-page' ];
2409 } elseif ( $action == 'move-target' ) {
2410 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2411 $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
2412 } elseif ( !$this->isMovable() ) {
2413 $errors[] = [ 'immobile-target-page' ];
2415 } elseif ( $action == 'delete' ) {
2416 $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
2417 if ( !$tempErrors ) {
2418 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2419 $user, $tempErrors, $rigor, true );
2421 if ( $tempErrors ) {
2422 // If protection keeps them from editing, they shouldn't be able to delete.
2423 $errors[] = [ 'deleteprotected' ];
2425 if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
2426 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2428 $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
2430 } elseif ( $action === 'undelete' ) {
2431 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
2432 // Undeleting implies editing
2433 $errors[] = [ 'undelete-cantedit' ];
2435 if ( !$this->exists()
2436 && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
2438 // Undeleting where nothing currently exists implies creating
2439 $errors[] = [ 'undelete-cantcreate' ];
2446 * Check that the user isn't blocked from editing.
2448 * @param string $action The action to check
2449 * @param User $user User to check
2450 * @param array $errors List of current errors
2451 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2452 * @param bool $short Short circuit on first error
2454 * @return array List of errors
2456 private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
2457 global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
2458 // Account creation blocks handled at userlogin.
2459 // Unblocking handled in SpecialUnblock
2460 if ( $rigor === 'quick' ||
in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
2464 // Optimize for a very common case
2465 if ( $action === 'read' && !$wgBlockDisablesLogin ) {
2469 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2470 $errors[] = [ 'confirmedittext' ];
2473 $useSlave = ( $rigor !== 'secure' );
2474 if ( ( $action == 'edit' ||
$action == 'create' )
2475 && !$user->isBlockedFrom( $this, $useSlave )
2477 // Don't block the user from editing their own talk page unless they've been
2478 // explicitly blocked from that too.
2479 } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
2480 // @todo FIXME: Pass the relevant context into this function.
2481 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2488 * Check that the user is allowed to read this page.
2490 * @param string $action The action to check
2491 * @param User $user User to check
2492 * @param array $errors List of current errors
2493 * @param string $rigor Same format as Title::getUserPermissionsErrors()
2494 * @param bool $short Short circuit on first error
2496 * @return array List of errors
2498 private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
2499 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2501 $whitelisted = false;
2502 if ( User
::isEveryoneAllowed( 'read' ) ) {
2503 # Shortcut for public wikis, allows skipping quite a bit of code
2504 $whitelisted = true;
2505 } elseif ( $user->isAllowed( 'read' ) ) {
2506 # If the user is allowed to read pages, he is allowed to read all pages
2507 $whitelisted = true;
2508 } elseif ( $this->isSpecial( 'Userlogin' )
2509 ||
$this->isSpecial( 'PasswordReset' )
2510 ||
$this->isSpecial( 'Userlogout' )
2512 # Always grant access to the login page.
2513 # Even anons need to be able to log in.
2514 $whitelisted = true;
2515 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2516 # Time to check the whitelist
2517 # Only do these checks is there's something to check against
2518 $name = $this->getPrefixedText();
2519 $dbName = $this->getPrefixedDBkey();
2521 // Check for explicit whitelisting with and without underscores
2522 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2523 $whitelisted = true;
2524 } elseif ( $this->getNamespace() == NS_MAIN
) {
2525 # Old settings might have the title prefixed with
2526 # a colon for main-namespace pages
2527 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2528 $whitelisted = true;
2530 } elseif ( $this->isSpecialPage() ) {
2531 # If it's a special page, ditch the subpage bit and check again
2532 $name = $this->getDBkey();
2533 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2535 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2536 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2537 $whitelisted = true;
2543 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2544 $name = $this->getPrefixedText();
2545 // Check for regex whitelisting
2546 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2547 if ( preg_match( $listItem, $name ) ) {
2548 $whitelisted = true;
2554 if ( !$whitelisted ) {
2555 # If the title is not whitelisted, give extensions a chance to do so...
2556 Hooks
::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
2557 if ( !$whitelisted ) {
2558 $errors[] = $this->missingPermissionError( $action, $short );
2566 * Get a description array when the user doesn't have the right to perform
2567 * $action (i.e. when User::isAllowed() returns false)
2569 * @param string $action The action to check
2570 * @param bool $short Short circuit on first error
2571 * @return array Array containing an error message key and any parameters
2573 private function missingPermissionError( $action, $short ) {
2574 // We avoid expensive display logic for quickUserCan's and such
2576 return [ 'badaccess-group0' ];
2579 return User
::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
2583 * Can $user perform $action on this page? This is an internal function,
2584 * with multiple levels of checks depending on performance needs; see $rigor below.
2585 * It does not check wfReadOnly().
2587 * @param string $action Action that permission needs to be checked for
2588 * @param User $user User to check
2589 * @param string $rigor One of (quick,full,secure)
2590 * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
2591 * - full : does cheap and expensive checks possibly from a replica DB
2592 * - secure : does cheap and expensive checks, using the master as needed
2593 * @param bool $short Set this to true to stop after the first permission error.
2594 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2596 protected function getUserPermissionsErrorsInternal(
2597 $action, $user, $rigor = 'secure', $short = false
2599 if ( $rigor === true ) {
2600 $rigor = 'secure'; // b/c
2601 } elseif ( $rigor === false ) {
2602 $rigor = 'quick'; // b/c
2603 } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
2604 throw new Exception( "Invalid rigor parameter '$rigor'." );
2607 # Read has special handling
2608 if ( $action == 'read' ) {
2610 'checkPermissionHooks',
2611 'checkReadPermissions',
2612 'checkUserBlock', // for wgBlockDisablesLogin
2614 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2615 # here as it will lead to duplicate error messages. This is okay to do
2616 # since anywhere that checks for create will also check for edit, and
2617 # those checks are called for edit.
2618 } elseif ( $action == 'create' ) {
2620 'checkQuickPermissions',
2621 'checkPermissionHooks',
2622 'checkPageRestrictions',
2623 'checkCascadingSourcesRestrictions',
2624 'checkActionPermissions',
2629 'checkQuickPermissions',
2630 'checkPermissionHooks',
2631 'checkSpecialsAndNSPermissions',
2632 'checkCSSandJSPermissions',
2633 'checkPageRestrictions',
2634 'checkCascadingSourcesRestrictions',
2635 'checkActionPermissions',
2641 while ( count( $checks ) > 0 &&
2642 !( $short && count( $errors ) > 0 ) ) {
2643 $method = array_shift( $checks );
2644 $errors = $this->$method( $action, $user, $errors, $rigor, $short );
2651 * Get a filtered list of all restriction types supported by this wiki.
2652 * @param bool $exists True to get all restriction types that apply to
2653 * titles that do exist, False for all restriction types that apply to
2654 * titles that do not exist
2657 public static function getFilteredRestrictionTypes( $exists = true ) {
2658 global $wgRestrictionTypes;
2659 $types = $wgRestrictionTypes;
2661 # Remove the create restriction for existing titles
2662 $types = array_diff( $types, [ 'create' ] );
2664 # Only the create and upload restrictions apply to non-existing titles
2665 $types = array_intersect( $types, [ 'create', 'upload' ] );
2671 * Returns restriction types for the current Title
2673 * @return array Applicable restriction types
2675 public function getRestrictionTypes() {
2676 if ( $this->isSpecialPage() ) {
2680 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2682 if ( $this->getNamespace() != NS_FILE
) {
2683 # Remove the upload restriction for non-file titles
2684 $types = array_diff( $types, [ 'upload' ] );
2687 Hooks
::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
2689 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2690 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2696 * Is this title subject to title protection?
2697 * Title protection is the one applied against creation of such title.
2699 * @return array|bool An associative array representing any existent title
2700 * protection, or false if there's none.
2702 public function getTitleProtection() {
2703 $protection = $this->getTitleProtectionInternal();
2704 if ( $protection ) {
2705 if ( $protection['permission'] == 'sysop' ) {
2706 $protection['permission'] = 'editprotected'; // B/C
2708 if ( $protection['permission'] == 'autoconfirmed' ) {
2709 $protection['permission'] = 'editsemiprotected'; // B/C
2716 * Fetch title protection settings
2718 * To work correctly, $this->loadRestrictions() needs to have access to the
2719 * actual protections in the database without munging 'sysop' =>
2720 * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
2721 * callers probably want $this->getTitleProtection() instead.
2723 * @return array|bool
2725 protected function getTitleProtectionInternal() {
2726 // Can't protect pages in special namespaces
2727 if ( $this->getNamespace() < 0 ) {
2731 // Can't protect pages that exist.
2732 if ( $this->exists() ) {
2736 if ( $this->mTitleProtection
=== null ) {
2737 $dbr = wfGetDB( DB_REPLICA
);
2738 $commentStore = new CommentStore( 'pt_reason' );
2739 $commentQuery = $commentStore->getJoin();
2740 $res = $dbr->select(
2741 [ 'protected_titles' ] +
$commentQuery['tables'],
2743 'user' => 'pt_user',
2744 'expiry' => 'pt_expiry',
2745 'permission' => 'pt_create_perm'
2746 ] +
$commentQuery['fields'],
2747 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2750 $commentQuery['joins']
2753 // fetchRow returns false if there are no rows.
2754 $row = $dbr->fetchRow( $res );
2756 $this->mTitleProtection
= [
2757 'user' => $row['user'],
2758 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
2759 'permission' => $row['permission'],
2760 'reason' => $commentStore->getComment( $row )->text
,
2763 $this->mTitleProtection
= false;
2766 return $this->mTitleProtection
;
2770 * Remove any title protection due to page existing
2772 public function deleteTitleProtection() {
2773 $dbw = wfGetDB( DB_MASTER
);
2777 [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
2780 $this->mTitleProtection
= false;
2784 * Is this page "semi-protected" - the *only* protection levels are listed
2785 * in $wgSemiprotectedRestrictionLevels?
2787 * @param string $action Action to check (default: edit)
2790 public function isSemiProtected( $action = 'edit' ) {
2791 global $wgSemiprotectedRestrictionLevels;
2793 $restrictions = $this->getRestrictions( $action );
2794 $semi = $wgSemiprotectedRestrictionLevels;
2795 if ( !$restrictions ||
!$semi ) {
2796 // Not protected, or all protection is full protection
2800 // Remap autoconfirmed to editsemiprotected for BC
2801 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2802 $semi[$key] = 'editsemiprotected';
2804 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2805 $restrictions[$key] = 'editsemiprotected';
2808 return !array_diff( $restrictions, $semi );
2812 * Does the title correspond to a protected article?
2814 * @param string $action The action the page is protected from,
2815 * by default checks all actions.
2818 public function isProtected( $action = '' ) {
2819 global $wgRestrictionLevels;
2821 $restrictionTypes = $this->getRestrictionTypes();
2823 # Special pages have inherent protection
2824 if ( $this->isSpecialPage() ) {
2828 # Check regular protection levels
2829 foreach ( $restrictionTypes as $type ) {
2830 if ( $action == $type ||
$action == '' ) {
2831 $r = $this->getRestrictions( $type );
2832 foreach ( $wgRestrictionLevels as $level ) {
2833 if ( in_array( $level, $r ) && $level != '' ) {
2844 * Determines if $user is unable to edit this page because it has been protected
2845 * by $wgNamespaceProtection.
2847 * @param User $user User object to check permissions
2850 public function isNamespaceProtected( User
$user ) {
2851 global $wgNamespaceProtection;
2853 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2854 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2855 if ( $right != '' && !$user->isAllowed( $right ) ) {
2864 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2866 * @return bool If the page is subject to cascading restrictions.
2868 public function isCascadeProtected() {
2869 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2870 return ( $sources > 0 );
2874 * Determines whether cascading protection sources have already been loaded from
2877 * @param bool $getPages True to check if the pages are loaded, or false to check
2878 * if the status is loaded.
2879 * @return bool Whether or not the specified information has been loaded
2882 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2883 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2887 * Cascading protection: Get the source of any cascading restrictions on this page.
2889 * @param bool $getPages Whether or not to retrieve the actual pages
2890 * that the restrictions have come from and the actual restrictions
2892 * @return array Two elements: First is an array of Title objects of the
2893 * pages from which cascading restrictions have come, false for
2894 * none, or true if such restrictions exist but $getPages was not
2895 * set. Second is an array like that returned by
2896 * Title::getAllRestrictions(), or an empty array if $getPages is
2899 public function getCascadeProtectionSources( $getPages = true ) {
2900 $pagerestrictions = [];
2902 if ( $this->mCascadeSources
!== null && $getPages ) {
2903 return [ $this->mCascadeSources
, $this->mCascadingRestrictions
];
2904 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2905 return [ $this->mHasCascadingRestrictions
, $pagerestrictions ];
2908 $dbr = wfGetDB( DB_REPLICA
);
2910 if ( $this->getNamespace() == NS_FILE
) {
2911 $tables = [ 'imagelinks', 'page_restrictions' ];
2913 'il_to' => $this->getDBkey(),
2918 $tables = [ 'templatelinks', 'page_restrictions' ];
2920 'tl_namespace' => $this->getNamespace(),
2921 'tl_title' => $this->getDBkey(),
2928 $cols = [ 'pr_page', 'page_namespace', 'page_title',
2929 'pr_expiry', 'pr_type', 'pr_level' ];
2930 $where_clauses[] = 'page_id=pr_page';
2933 $cols = [ 'pr_expiry' ];
2936 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2938 $sources = $getPages ?
[] : false;
2939 $now = wfTimestampNow();
2941 foreach ( $res as $row ) {
2942 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
2943 if ( $expiry > $now ) {
2945 $page_id = $row->pr_page
;
2946 $page_ns = $row->page_namespace
;
2947 $page_title = $row->page_title
;
2948 $sources[$page_id] = self
::makeTitle( $page_ns, $page_title );
2949 # Add groups needed for each restriction type if its not already there
2950 # Make sure this restriction type still exists
2952 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2953 $pagerestrictions[$row->pr_type
] = [];
2957 isset( $pagerestrictions[$row->pr_type
] )
2958 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2960 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2969 $this->mCascadeSources
= $sources;
2970 $this->mCascadingRestrictions
= $pagerestrictions;
2972 $this->mHasCascadingRestrictions
= $sources;
2975 return [ $sources, $pagerestrictions ];
2979 * Accessor for mRestrictionsLoaded
2981 * @return bool Whether or not the page's restrictions have already been
2982 * loaded from the database
2985 public function areRestrictionsLoaded() {
2986 return $this->mRestrictionsLoaded
;
2990 * Accessor/initialisation for mRestrictions
2992 * @param string $action Action that permission needs to be checked for
2993 * @return array Restriction levels needed to take the action. All levels are
2994 * required. Note that restriction levels are normally user rights, but 'sysop'
2995 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2996 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2998 public function getRestrictions( $action ) {
2999 if ( !$this->mRestrictionsLoaded
) {
3000 $this->loadRestrictions();
3002 return isset( $this->mRestrictions
[$action] )
3003 ?
$this->mRestrictions
[$action]
3008 * Accessor/initialisation for mRestrictions
3010 * @return array Keys are actions, values are arrays as returned by
3011 * Title::getRestrictions()
3014 public function getAllRestrictions() {
3015 if ( !$this->mRestrictionsLoaded
) {
3016 $this->loadRestrictions();
3018 return $this->mRestrictions
;
3022 * Get the expiry time for the restriction against a given action
3024 * @param string $action
3025 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
3026 * or not protected at all, or false if the action is not recognised.
3028 public function getRestrictionExpiry( $action ) {
3029 if ( !$this->mRestrictionsLoaded
) {
3030 $this->loadRestrictions();
3032 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
3036 * Returns cascading restrictions for the current article
3040 function areRestrictionsCascading() {
3041 if ( !$this->mRestrictionsLoaded
) {
3042 $this->loadRestrictions();
3045 return $this->mCascadeRestriction
;
3049 * Compiles list of active page restrictions from both page table (pre 1.10)
3050 * and page_restrictions table for this existing page.
3051 * Public for usage by LiquidThreads.
3053 * @param array $rows Array of db result objects
3054 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3055 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3056 * Edit and move sections are separated by a colon
3057 * Example: "edit=autoconfirmed,sysop:move=sysop"
3059 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
3060 $dbr = wfGetDB( DB_REPLICA
);
3062 $restrictionTypes = $this->getRestrictionTypes();
3064 foreach ( $restrictionTypes as $type ) {
3065 $this->mRestrictions
[$type] = [];
3066 $this->mRestrictionsExpiry
[$type] = 'infinity';
3069 $this->mCascadeRestriction
= false;
3071 # Backwards-compatibility: also load the restrictions from the page record (old format).
3072 if ( $oldFashionedRestrictions !== null ) {
3073 $this->mOldRestrictions
= $oldFashionedRestrictions;
3076 if ( $this->mOldRestrictions
=== false ) {
3077 $this->mOldRestrictions
= $dbr->selectField( 'page', 'page_restrictions',
3078 [ 'page_id' => $this->getArticleID() ], __METHOD__
);
3081 if ( $this->mOldRestrictions
!= '' ) {
3082 foreach ( explode( ':', trim( $this->mOldRestrictions
) ) as $restrict ) {
3083 $temp = explode( '=', trim( $restrict ) );
3084 if ( count( $temp ) == 1 ) {
3085 // old old format should be treated as edit/move restriction
3086 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
3087 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
3089 $restriction = trim( $temp[1] );
3090 if ( $restriction != '' ) { // some old entries are empty
3091 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
3097 if ( count( $rows ) ) {
3098 # Current system - load second to make them override.
3099 $now = wfTimestampNow();
3101 # Cycle through all the restrictions.
3102 foreach ( $rows as $row ) {
3103 // Don't take care of restrictions types that aren't allowed
3104 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
3108 $expiry = $dbr->decodeExpiry( $row->pr_expiry
);
3110 // Only apply the restrictions if they haven't expired!
3111 if ( !$expiry ||
$expiry > $now ) {
3112 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
3113 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
3115 $this->mCascadeRestriction |
= $row->pr_cascade
;
3120 $this->mRestrictionsLoaded
= true;
3124 * Load restrictions from the page_restrictions table
3126 * @param string $oldFashionedRestrictions Comma-separated set of permission keys
3127 * indicating who can move or edit the page from the page table, (pre 1.10) rows.
3128 * Edit and move sections are separated by a colon
3129 * Example: "edit=autoconfirmed,sysop:move=sysop"
3131 public function loadRestrictions( $oldFashionedRestrictions = null ) {
3132 if ( $this->mRestrictionsLoaded
) {
3136 $id = $this->getArticleID();
3138 $cache = ObjectCache
::getMainWANInstance();
3139 $rows = $cache->getWithSetCallback(
3140 // Page protections always leave a new null revision
3141 $cache->makeKey( 'page-restrictions', $id, $this->getLatestRevID() ),
3143 function ( $curValue, &$ttl, array &$setOpts ) {
3144 $dbr = wfGetDB( DB_REPLICA
);
3146 $setOpts +
= Database
::getCacheSetOptions( $dbr );
3148 return iterator_to_array(
3150 'page_restrictions',
3151 [ 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ],
3152 [ 'pr_page' => $this->getArticleID() ],
3159 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
3161 $title_protection = $this->getTitleProtectionInternal();
3163 if ( $title_protection ) {
3164 $now = wfTimestampNow();
3165 $expiry = wfGetDB( DB_REPLICA
)->decodeExpiry( $title_protection['expiry'] );
3167 if ( !$expiry ||
$expiry > $now ) {
3168 // Apply the restrictions
3169 $this->mRestrictionsExpiry
['create'] = $expiry;
3170 $this->mRestrictions
['create'] =
3171 explode( ',', trim( $title_protection['permission'] ) );
3172 } else { // Get rid of the old restrictions
3173 $this->mTitleProtection
= false;
3176 $this->mRestrictionsExpiry
['create'] = 'infinity';
3178 $this->mRestrictionsLoaded
= true;
3183 * Flush the protection cache in this object and force reload from the database.
3184 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3186 public function flushRestrictions() {
3187 $this->mRestrictionsLoaded
= false;
3188 $this->mTitleProtection
= null;
3192 * Purge expired restrictions from the page_restrictions table
3194 * This will purge no more than $wgUpdateRowsPerQuery page_restrictions rows
3196 static function purgeExpiredRestrictions() {
3197 if ( wfReadOnly() ) {
3201 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3202 wfGetDB( DB_MASTER
),
3204 function ( IDatabase
$dbw, $fname ) {
3205 $config = MediaWikiServices
::getInstance()->getMainConfig();
3206 $ids = $dbw->selectFieldValues(
3207 'page_restrictions',
3209 [ 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3211 [ 'LIMIT' => $config->get( 'UpdateRowsPerQuery' ) ] // T135470
3214 $dbw->delete( 'page_restrictions', [ 'pr_id' => $ids ], $fname );
3219 DeferredUpdates
::addUpdate( new AtomicSectionUpdate(
3220 wfGetDB( DB_MASTER
),
3222 function ( IDatabase
$dbw, $fname ) {
3225 [ 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
3233 * Does this have subpages? (Warning, usually requires an extra DB query.)
3237 public function hasSubpages() {
3238 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3243 # We dynamically add a member variable for the purpose of this method
3244 # alone to cache the result. There's no point in having it hanging
3245 # around uninitialized in every Title object; therefore we only add it
3246 # if needed and don't declare it statically.
3247 if ( $this->mHasSubpages
=== null ) {
3248 $this->mHasSubpages
= false;
3249 $subpages = $this->getSubpages( 1 );
3250 if ( $subpages instanceof TitleArray
) {
3251 $this->mHasSubpages
= (bool)$subpages->count();
3255 return $this->mHasSubpages
;
3259 * Get all subpages of this page.
3261 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3262 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3263 * doesn't allow subpages
3265 public function getSubpages( $limit = -1 ) {
3266 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3270 $dbr = wfGetDB( DB_REPLICA
);
3271 $conds['page_namespace'] = $this->getNamespace();
3272 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3274 if ( $limit > -1 ) {
3275 $options['LIMIT'] = $limit;
3277 return TitleArray
::newFromResult(
3278 $dbr->select( 'page',
3279 [ 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ],
3288 * Is there a version of this page in the deletion archive?
3290 * @return int The number of archived revisions
3292 public function isDeleted() {
3293 if ( $this->getNamespace() < 0 ) {
3296 $dbr = wfGetDB( DB_REPLICA
);
3298 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3299 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3302 if ( $this->getNamespace() == NS_FILE
) {
3303 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3304 [ 'fa_name' => $this->getDBkey() ],
3313 * Is there a version of this page in the deletion archive?
3317 public function isDeletedQuick() {
3318 if ( $this->getNamespace() < 0 ) {
3321 $dbr = wfGetDB( DB_REPLICA
);
3322 $deleted = (bool)$dbr->selectField( 'archive', '1',
3323 [ 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ],
3326 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3327 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3328 [ 'fa_name' => $this->getDBkey() ],
3336 * Get the article ID for this Title from the link cache,
3337 * adding it if necessary
3339 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3341 * @return int The ID
3343 public function getArticleID( $flags = 0 ) {
3344 if ( $this->getNamespace() < 0 ) {
3345 $this->mArticleID
= 0;
3346 return $this->mArticleID
;
3348 $linkCache = LinkCache
::singleton();
3349 if ( $flags & self
::GAID_FOR_UPDATE
) {
3350 $oldUpdate = $linkCache->forUpdate( true );
3351 $linkCache->clearLink( $this );
3352 $this->mArticleID
= $linkCache->addLinkObj( $this );
3353 $linkCache->forUpdate( $oldUpdate );
3355 if ( -1 == $this->mArticleID
) {
3356 $this->mArticleID
= $linkCache->addLinkObj( $this );
3359 return $this->mArticleID
;
3363 * Is this an article that is a redirect page?
3364 * Uses link cache, adding it if necessary
3366 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3369 public function isRedirect( $flags = 0 ) {
3370 if ( !is_null( $this->mRedirect
) ) {
3371 return $this->mRedirect
;
3373 if ( !$this->getArticleID( $flags ) ) {
3374 $this->mRedirect
= false;
3375 return $this->mRedirect
;
3378 $linkCache = LinkCache
::singleton();
3379 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3380 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3381 if ( $cached === null ) {
3382 # Trust LinkCache's state over our own
3383 # LinkCache is telling us that the page doesn't exist, despite there being cached
3384 # data relating to an existing page in $this->mArticleID. Updaters should clear
3385 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3386 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3387 # LinkCache to refresh its data from the master.
3388 $this->mRedirect
= false;
3389 return $this->mRedirect
;
3392 $this->mRedirect
= (bool)$cached;
3394 return $this->mRedirect
;
3398 * What is the length of this page?
3399 * Uses link cache, adding it if necessary
3401 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3404 public function getLength( $flags = 0 ) {
3405 if ( $this->mLength
!= -1 ) {
3406 return $this->mLength
;
3408 if ( !$this->getArticleID( $flags ) ) {
3410 return $this->mLength
;
3412 $linkCache = LinkCache
::singleton();
3413 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3414 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3415 if ( $cached === null ) {
3416 # Trust LinkCache's state over our own, as for isRedirect()
3418 return $this->mLength
;
3421 $this->mLength
= intval( $cached );
3423 return $this->mLength
;
3427 * What is the page_latest field for this page?
3429 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3430 * @return int Int or 0 if the page doesn't exist
3432 public function getLatestRevID( $flags = 0 ) {
3433 if ( !( $flags & self
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3434 return intval( $this->mLatestID
);
3436 if ( !$this->getArticleID( $flags ) ) {
3437 $this->mLatestID
= 0;
3438 return $this->mLatestID
;
3440 $linkCache = LinkCache
::singleton();
3441 $linkCache->addLinkObj( $this ); # in case we already had an article ID
3442 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3443 if ( $cached === null ) {
3444 # Trust LinkCache's state over our own, as for isRedirect()
3445 $this->mLatestID
= 0;
3446 return $this->mLatestID
;
3449 $this->mLatestID
= intval( $cached );
3451 return $this->mLatestID
;
3455 * This clears some fields in this object, and clears any associated
3456 * keys in the "bad links" section of the link cache.
3458 * - This is called from WikiPage::doEditContent() and WikiPage::insertOn() to allow
3459 * loading of the new page_id. It's also called from
3460 * WikiPage::doDeleteArticleReal()
3462 * @param int $newid The new Article ID
3464 public function resetArticleID( $newid ) {
3465 $linkCache = LinkCache
::singleton();
3466 $linkCache->clearLink( $this );
3468 if ( $newid === false ) {
3469 $this->mArticleID
= -1;
3471 $this->mArticleID
= intval( $newid );
3473 $this->mRestrictionsLoaded
= false;
3474 $this->mRestrictions
= [];
3475 $this->mOldRestrictions
= false;
3476 $this->mRedirect
= null;
3477 $this->mLength
= -1;
3478 $this->mLatestID
= false;
3479 $this->mContentModel
= false;
3480 $this->mEstimateRevisions
= null;
3481 $this->mPageLanguage
= false;
3482 $this->mDbPageLanguage
= false;
3483 $this->mIsBigDeletion
= null;
3486 public static function clearCaches() {
3487 $linkCache = LinkCache
::singleton();
3488 $linkCache->clear();
3490 $titleCache = self
::getTitleCache();
3491 $titleCache->clear();
3495 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3497 * @param string $text Containing title to capitalize
3498 * @param int $ns Namespace index, defaults to NS_MAIN
3499 * @return string Containing capitalized title
3501 public static function capitalize( $text, $ns = NS_MAIN
) {
3504 if ( MWNamespace
::isCapitalized( $ns ) ) {
3505 return $wgContLang->ucfirst( $text );
3512 * Secure and split - main initialisation function for this object
3514 * Assumes that mDbkeyform has been set, and is urldecoded
3515 * and uses underscores, but not otherwise munged. This function
3516 * removes illegal characters, splits off the interwiki and
3517 * namespace prefixes, sets the other forms, and canonicalizes
3520 * @throws MalformedTitleException On invalid titles
3521 * @return bool True on success
3523 private function secureAndSplit() {
3525 $this->mInterwiki
= '';
3526 $this->mFragment
= '';
3527 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3529 $dbkey = $this->mDbkeyform
;
3531 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3532 // the parsing code with Title, while avoiding massive refactoring.
3533 // @todo: get rid of secureAndSplit, refactor parsing code.
3534 // @note: getTitleParser() returns a TitleParser implementation which does not have a
3535 // splitTitleString method, but the only implementation (MediaWikiTitleCodec) does
3536 $titleCodec = MediaWikiServices
::getInstance()->getTitleParser();
3537 // MalformedTitleException can be thrown here
3538 $parts = $titleCodec->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3541 $this->setFragment( '#' . $parts['fragment'] );
3542 $this->mInterwiki
= $parts['interwiki'];
3543 $this->mLocalInterwiki
= $parts['local_interwiki'];
3544 $this->mNamespace
= $parts['namespace'];
3545 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3547 $this->mDbkeyform
= $parts['dbkey'];
3548 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3549 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );
3551 # We already know that some pages won't be in the database!
3552 if ( $this->isExternal() ||
$this->isSpecialPage() ) {
3553 $this->mArticleID
= 0;
3560 * Get an array of Title objects linking to this Title
3561 * Also stores the IDs in the link cache.
3563 * WARNING: do not use this function on arbitrary user-supplied titles!
3564 * On heavily-used templates it will max out the memory.
3566 * @param array $options May be FOR UPDATE
3567 * @param string $table Table name
3568 * @param string $prefix Fields prefix
3569 * @return Title[] Array of Title objects linking here
3571 public function getLinksTo( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3572 if ( count( $options ) > 0 ) {
3573 $db = wfGetDB( DB_MASTER
);
3575 $db = wfGetDB( DB_REPLICA
);
3580 self
::getSelectFields(),
3582 "{$prefix}_from=page_id",
3583 "{$prefix}_namespace" => $this->getNamespace(),
3584 "{$prefix}_title" => $this->getDBkey() ],
3590 if ( $res->numRows() ) {
3591 $linkCache = LinkCache
::singleton();
3592 foreach ( $res as $row ) {
3593 $titleObj = self
::makeTitle( $row->page_namespace
, $row->page_title
);
3595 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3596 $retVal[] = $titleObj;
3604 * Get an array of Title objects using this Title as a template
3605 * Also stores the IDs in the link cache.
3607 * WARNING: do not use this function on arbitrary user-supplied titles!
3608 * On heavily-used templates it will max out the memory.
3610 * @param array $options Query option to Database::select()
3611 * @return Title[] Array of Title the Title objects linking here
3613 public function getTemplateLinksTo( $options = [] ) {
3614 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3618 * Get an array of Title objects linked from this Title
3619 * Also stores the IDs in the link cache.
3621 * WARNING: do not use this function on arbitrary user-supplied titles!
3622 * On heavily-used templates it will max out the memory.
3624 * @param array $options Query option to Database::select()
3625 * @param string $table Table name
3626 * @param string $prefix Fields prefix
3627 * @return array Array of Title objects linking here
3629 public function getLinksFrom( $options = [], $table = 'pagelinks', $prefix = 'pl' ) {
3630 $id = $this->getArticleID();
3632 # If the page doesn't exist; there can't be any link from this page
3637 $db = wfGetDB( DB_REPLICA
);
3639 $blNamespace = "{$prefix}_namespace";
3640 $blTitle = "{$prefix}_title";
3642 $pageQuery = WikiPage
::getQueryInfo();
3644 [ $table, 'nestpage' => $pageQuery['tables'] ],
3646 [ $blNamespace, $blTitle ],
3647 $pageQuery['fields']
3649 [ "{$prefix}_from" => $id ],
3654 [ "page_namespace=$blNamespace", "page_title=$blTitle" ]
3655 ] ] +
$pageQuery['joins']
3659 $linkCache = LinkCache
::singleton();
3660 foreach ( $res as $row ) {
3661 if ( $row->page_id
) {
3662 $titleObj = self
::newFromRow( $row );
3664 $titleObj = self
::makeTitle( $row->$blNamespace, $row->$blTitle );
3665 $linkCache->addBadLinkObj( $titleObj );
3667 $retVal[] = $titleObj;
3674 * Get an array of Title objects used on this Title as a template
3675 * Also stores the IDs in the link cache.
3677 * WARNING: do not use this function on arbitrary user-supplied titles!
3678 * On heavily-used templates it will max out the memory.
3680 * @param array $options May be FOR UPDATE
3681 * @return Title[] Array of Title the Title objects used here
3683 public function getTemplateLinksFrom( $options = [] ) {
3684 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3688 * Get an array of Title objects referring to non-existent articles linked
3691 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3692 * should use redirect table in this case).
3693 * @return Title[] Array of Title the Title objects
3695 public function getBrokenLinksFrom() {
3696 if ( $this->getArticleID() == 0 ) {
3697 # All links from article ID 0 are false positives
3701 $dbr = wfGetDB( DB_REPLICA
);
3702 $res = $dbr->select(
3703 [ 'page', 'pagelinks' ],
3704 [ 'pl_namespace', 'pl_title' ],
3706 'pl_from' => $this->getArticleID(),
3707 'page_namespace IS NULL'
3713 [ 'pl_namespace=page_namespace', 'pl_title=page_title' ]
3719 foreach ( $res as $row ) {
3720 $retVal[] = self
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3726 * Get a list of URLs to purge from the CDN cache when this
3729 * @return string[] Array of String the URLs
3731 public function getCdnUrls() {
3733 $this->getInternalURL(),
3734 $this->getInternalURL( 'action=history' )
3737 $pageLang = $this->getPageLanguage();
3738 if ( $pageLang->hasVariants() ) {
3739 $variants = $pageLang->getVariants();
3740 foreach ( $variants as $vCode ) {
3741 $urls[] = $this->getInternalURL( $vCode );
3745 // If we are looking at a css/js user subpage, purge the action=raw.
3746 if ( $this->isJsSubpage() ) {
3747 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/javascript' );
3748 } elseif ( $this->isCssSubpage() ) {
3749 $urls[] = $this->getInternalURL( 'action=raw&ctype=text/css' );
3752 Hooks
::run( 'TitleSquidURLs', [ $this, &$urls ] );
3757 * @deprecated since 1.27 use getCdnUrls()
3759 public function getSquidURLs() {
3760 return $this->getCdnUrls();
3764 * Purge all applicable CDN URLs
3766 public function purgeSquid() {
3767 DeferredUpdates
::addUpdate(
3768 new CdnCacheUpdate( $this->getCdnUrls() ),
3769 DeferredUpdates
::PRESEND
3774 * Check whether a given move operation would be valid.
3775 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3777 * @deprecated since 1.25, use MovePage's methods instead
3778 * @param Title &$nt The new title
3779 * @param bool $auth Whether to check user permissions (uses $wgUser)
3780 * @param string $reason Is the log summary of the move, used for spam checking
3781 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3783 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3786 if ( !( $nt instanceof Title
) ) {
3787 // Normally we'd add this to $errors, but we'll get
3788 // lots of syntax errors if $nt is not an object
3789 return [ [ 'badtitletext' ] ];
3792 $mp = new MovePage( $this, $nt );
3793 $errors = $mp->isValidMove()->getErrorsArray();
3795 $errors = wfMergeErrorArrays(
3797 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3801 return $errors ?
: true;
3805 * Check if the requested move target is a valid file move target
3806 * @todo move this to MovePage
3807 * @param Title $nt Target title
3808 * @return array List of errors
3810 protected function validateFileMoveOperation( $nt ) {
3815 $destFile = wfLocalFile( $nt );
3816 $destFile->load( File
::READ_LATEST
);
3817 if ( !$wgUser->isAllowed( 'reupload-shared' )
3818 && !$destFile->exists() && wfFindFile( $nt )
3820 $errors[] = [ 'file-exists-sharedrepo' ];
3827 * Move a title to a new location
3829 * @deprecated since 1.25, use the MovePage class instead
3830 * @param Title &$nt The new title
3831 * @param bool $auth Indicates whether $wgUser's permissions
3833 * @param string $reason The reason for the move
3834 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3835 * Ignored if the user doesn't have the suppressredirect right.
3836 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3837 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3839 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true,
3840 array $changeTags = []
3843 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3844 if ( is_array( $err ) ) {
3845 // Auto-block user's IP if the account was "hard" blocked
3846 $wgUser->spreadAnyEditBlock();
3849 // Check suppressredirect permission
3850 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3851 $createRedirect = true;
3854 $mp = new MovePage( $this, $nt );
3855 $status = $mp->move( $wgUser, $reason, $createRedirect, $changeTags );
3856 if ( $status->isOK() ) {
3859 return $status->getErrorsArray();
3864 * Move this page's subpages to be subpages of $nt
3866 * @param Title $nt Move target
3867 * @param bool $auth Whether $wgUser's permissions should be checked
3868 * @param string $reason The reason for the move
3869 * @param bool $createRedirect Whether to create redirects from the old subpages to
3870 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3871 * @param array $changeTags Applied to the entry in the move log and redirect page revision
3872 * @return array Array with old page titles as keys, and strings (new page titles) or
3873 * getUserPermissionsErrors()-like arrays (errors) as values, or a
3874 * getUserPermissionsErrors()-like error array with numeric indices if
3875 * no pages were moved
3877 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true,
3878 array $changeTags = []
3880 global $wgMaximumMovedPages;
3881 // Check permissions
3882 if ( !$this->userCan( 'move-subpages' ) ) {
3884 [ 'cant-move-subpages' ],
3887 // Do the source and target namespaces support subpages?
3888 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3890 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $this->getNamespace() ) ],
3893 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3895 [ 'namespace-nosubpages', MWNamespace
::getCanonicalName( $nt->getNamespace() ) ],
3899 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3902 foreach ( $subpages as $oldSubpage ) {
3904 if ( $count > $wgMaximumMovedPages ) {
3905 $retval[$oldSubpage->getPrefixedText()] = [
3906 [ 'movepage-max-pages', $wgMaximumMovedPages ],
3911 // We don't know whether this function was called before
3912 // or after moving the root page, so check both
3914 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3915 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3917 // When moving a page to a subpage of itself,
3918 // don't move it twice
3921 $newPageName = preg_replace(
3922 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3923 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # T23234
3924 $oldSubpage->getDBkey() );
3925 if ( $oldSubpage->isTalkPage() ) {
3926 $newNs = $nt->getTalkPage()->getNamespace();
3928 $newNs = $nt->getSubjectPage()->getNamespace();
3930 # T16385: we need makeTitleSafe because the new page names may
3931 # be longer than 255 characters.
3932 $newSubpage = self
::makeTitleSafe( $newNs, $newPageName );
3934 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect, $changeTags );
3935 if ( $success === true ) {
3936 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3938 $retval[$oldSubpage->getPrefixedText()] = $success;
3945 * Checks if this page is just a one-rev redirect.
3946 * Adds lock, so don't use just for light purposes.
3950 public function isSingleRevRedirect() {
3951 global $wgContentHandlerUseDB;
3953 $dbw = wfGetDB( DB_MASTER
);
3956 $fields = [ 'page_is_redirect', 'page_latest', 'page_id' ];
3957 if ( $wgContentHandlerUseDB ) {
3958 $fields[] = 'page_content_model';
3961 $row = $dbw->selectRow( 'page',
3967 # Cache some fields we may want
3968 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3969 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3970 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3971 $this->mContentModel
= $row && isset( $row->page_content_model
)
3972 ?
strval( $row->page_content_model
)
3975 if ( !$this->mRedirect
) {
3978 # Does the article have a history?
3979 $row = $dbw->selectField( [ 'page', 'revision' ],
3981 [ 'page_namespace' => $this->getNamespace(),
3982 'page_title' => $this->getDBkey(),
3984 'page_latest != rev_id'
3989 # Return true if there was no history
3990 return ( $row === false );
3994 * Checks if $this can be moved to a given Title
3995 * - Selects for update, so don't call it unless you mean business
3997 * @deprecated since 1.25, use MovePage's methods instead
3998 * @param Title $nt The new title to check
4001 public function isValidMoveTarget( $nt ) {
4002 # Is it an existing file?
4003 if ( $nt->getNamespace() == NS_FILE
) {
4004 $file = wfLocalFile( $nt );
4005 $file->load( File
::READ_LATEST
);
4006 if ( $file->exists() ) {
4007 wfDebug( __METHOD__
. ": file exists\n" );
4011 # Is it a redirect with no history?
4012 if ( !$nt->isSingleRevRedirect() ) {
4013 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4016 # Get the article text
4017 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4018 if ( !is_object( $rev ) ) {
4021 $content = $rev->getContent();
4022 # Does the redirect point to the source?
4023 # Or is it a broken self-redirect, usually caused by namespace collisions?
4024 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4026 if ( $redirTitle ) {
4027 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4028 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4029 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4035 # Fail safe (not a redirect after all. strange.)
4036 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4037 " is a redirect, but it doesn't contain a valid redirect.\n" );
4043 * Get categories to which this Title belongs and return an array of
4044 * categories' names.
4046 * @return array Array of parents in the form:
4047 * $parent => $currentarticle
4049 public function getParentCategories() {
4054 $titleKey = $this->getArticleID();
4056 if ( $titleKey === 0 ) {
4060 $dbr = wfGetDB( DB_REPLICA
);
4062 $res = $dbr->select(
4065 [ 'cl_from' => $titleKey ],
4069 if ( $res->numRows() > 0 ) {
4070 foreach ( $res as $row ) {
4071 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4072 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4079 * Get a tree of parent categories
4081 * @param array $children Array with the children in the keys, to check for circular refs
4082 * @return array Tree of parent categories
4084 public function getParentCategoryTree( $children = [] ) {
4086 $parents = $this->getParentCategories();
4089 foreach ( $parents as $parent => $current ) {
4090 if ( array_key_exists( $parent, $children ) ) {
4091 # Circular reference
4092 $stack[$parent] = [];
4094 $nt = self
::newFromText( $parent );
4096 $stack[$parent] = $nt->getParentCategoryTree( $children +
[ $parent => 1 ] );
4106 * Get an associative array for selecting this title from
4109 * @return array Array suitable for the $where parameter of DB::select()
4111 public function pageCond() {
4112 if ( $this->mArticleID
> 0 ) {
4113 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4114 return [ 'page_id' => $this->mArticleID
];
4116 return [ 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
];
4121 * Get next/previous revision ID relative to another revision ID
4122 * @param int $revId Revision ID. Get the revision that was before this one.
4123 * @param int $flags Title::GAID_FOR_UPDATE
4124 * @param string $dir 'next' or 'prev'
4125 * @return int|bool New revision ID, or false if none exists
4127 private function getRelativeRevisionID( $revId, $flags, $dir ) {
4128 $revId = (int)$revId;
4129 if ( $dir === 'next' ) {
4132 } elseif ( $dir === 'prev' ) {
4136 throw new InvalidArgumentException( '$dir must be "next" or "prev"' );
4139 if ( $flags & self
::GAID_FOR_UPDATE
) {
4140 $db = wfGetDB( DB_MASTER
);
4142 $db = wfGetDB( DB_REPLICA
, 'contributions' );
4145 // Intentionally not caring if the specified revision belongs to this
4146 // page. We only care about the timestamp.
4147 $ts = $db->selectField( 'revision', 'rev_timestamp', [ 'rev_id' => $revId ], __METHOD__
);
4148 if ( $ts === false ) {
4149 $ts = $db->selectField( 'archive', 'ar_timestamp', [ 'ar_rev_id' => $revId ], __METHOD__
);
4150 if ( $ts === false ) {
4151 // Or should this throw an InvalidArgumentException or something?
4155 $ts = $db->addQuotes( $ts );
4157 $revId = $db->selectField( 'revision', 'rev_id',
4159 'rev_page' => $this->getArticleID( $flags ),
4160 "rev_timestamp $op $ts OR (rev_timestamp = $ts AND rev_id $op $revId)"
4164 'ORDER BY' => "rev_timestamp $sort, rev_id $sort",
4165 'IGNORE INDEX' => 'rev_timestamp', // Probably needed for T159319
4169 if ( $revId === false ) {
4172 return intval( $revId );
4177 * Get the revision ID of the previous revision
4179 * @param int $revId Revision ID. Get the revision that was before this one.
4180 * @param int $flags Title::GAID_FOR_UPDATE
4181 * @return int|bool Old revision ID, or false if none exists
4183 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4184 return $this->getRelativeRevisionID( $revId, $flags, 'prev' );
4188 * Get the revision ID of the next revision
4190 * @param int $revId Revision ID. Get the revision that was after this one.
4191 * @param int $flags Title::GAID_FOR_UPDATE
4192 * @return int|bool Next revision ID, or false if none exists
4194 public function getNextRevisionID( $revId, $flags = 0 ) {
4195 return $this->getRelativeRevisionID( $revId, $flags, 'next' );
4199 * Get the first revision of the page
4201 * @param int $flags Title::GAID_FOR_UPDATE
4202 * @return Revision|null If page doesn't exist
4204 public function getFirstRevision( $flags = 0 ) {
4205 $pageId = $this->getArticleID( $flags );
4207 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_REPLICA
);
4208 $revQuery = Revision
::getQueryInfo();
4209 $row = $db->selectRow( $revQuery['tables'], $revQuery['fields'],
4210 [ 'rev_page' => $pageId ],
4213 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC',
4214 'IGNORE INDEX' => [ 'revision' => 'rev_timestamp' ], // See T159319
4219 return new Revision( $row );
4226 * Get the oldest revision timestamp of this page
4228 * @param int $flags Title::GAID_FOR_UPDATE
4229 * @return string MW timestamp
4231 public function getEarliestRevTime( $flags = 0 ) {
4232 $rev = $this->getFirstRevision( $flags );
4233 return $rev ?
$rev->getTimestamp() : null;
4237 * Check if this is a new page
4241 public function isNewPage() {
4242 $dbr = wfGetDB( DB_REPLICA
);
4243 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4247 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4251 public function isBigDeletion() {
4252 global $wgDeleteRevisionsLimit;
4254 if ( !$wgDeleteRevisionsLimit ) {
4258 if ( $this->mIsBigDeletion
=== null ) {
4259 $dbr = wfGetDB( DB_REPLICA
);
4261 $revCount = $dbr->selectRowCount(
4264 [ 'rev_page' => $this->getArticleID() ],
4266 [ 'LIMIT' => $wgDeleteRevisionsLimit +
1 ]
4269 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4272 return $this->mIsBigDeletion
;
4276 * Get the approximate revision count of this page.
4280 public function estimateRevisionCount() {
4281 if ( !$this->exists() ) {
4285 if ( $this->mEstimateRevisions
=== null ) {
4286 $dbr = wfGetDB( DB_REPLICA
);
4287 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4288 [ 'rev_page' => $this->getArticleID() ], __METHOD__
);
4291 return $this->mEstimateRevisions
;
4295 * Get the number of revisions between the given revision.
4296 * Used for diffs and other things that really need it.
4298 * @param int|Revision $old Old revision or rev ID (first before range)
4299 * @param int|Revision $new New revision or rev ID (first after range)
4300 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4301 * @return int Number of revisions between these revisions.
4303 public function countRevisionsBetween( $old, $new, $max = null ) {
4304 if ( !( $old instanceof Revision
) ) {
4305 $old = Revision
::newFromTitle( $this, (int)$old );
4307 if ( !( $new instanceof Revision
) ) {
4308 $new = Revision
::newFromTitle( $this, (int)$new );
4310 if ( !$old ||
!$new ) {
4311 return 0; // nothing to compare
4313 $dbr = wfGetDB( DB_REPLICA
);
4315 'rev_page' => $this->getArticleID(),
4316 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4317 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4319 if ( $max !== null ) {
4320 return $dbr->selectRowCount( 'revision', '1',
4323 [ 'LIMIT' => $max +
1 ] // extra to detect truncation
4326 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4331 * Get the authors between the given revisions or revision IDs.
4332 * Used for diffs and other things that really need it.
4336 * @param int|Revision $old Old revision or rev ID (first before range by default)
4337 * @param int|Revision $new New revision or rev ID (first after range by default)
4338 * @param int $limit Maximum number of authors
4339 * @param string|array $options (Optional): Single option, or an array of options:
4340 * 'include_old' Include $old in the range; $new is excluded.
4341 * 'include_new' Include $new in the range; $old is excluded.
4342 * 'include_both' Include both $old and $new in the range.
4343 * Unknown option values are ignored.
4344 * @return array|null Names of revision authors in the range; null if not both revisions exist
4346 public function getAuthorsBetween( $old, $new, $limit, $options = [] ) {
4347 if ( !( $old instanceof Revision
) ) {
4348 $old = Revision
::newFromTitle( $this, (int)$old );
4350 if ( !( $new instanceof Revision
) ) {
4351 $new = Revision
::newFromTitle( $this, (int)$new );
4353 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4354 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4355 // in the sanity check below?
4356 if ( !$old ||
!$new ) {
4357 return null; // nothing to compare
4362 $options = (array)$options;
4363 if ( in_array( 'include_old', $options ) ) {
4366 if ( in_array( 'include_new', $options ) ) {
4369 if ( in_array( 'include_both', $options ) ) {
4373 // No DB query needed if $old and $new are the same or successive revisions:
4374 if ( $old->getId() === $new->getId() ) {
4375 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
4377 [ $old->getUserText( Revision
::RAW
) ];
4378 } elseif ( $old->getId() === $new->getParentId() ) {
4379 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4380 $authors[] = $old->getUserText( Revision
::RAW
);
4381 if ( $old->getUserText( Revision
::RAW
) != $new->getUserText( Revision
::RAW
) ) {
4382 $authors[] = $new->getUserText( Revision
::RAW
);
4384 } elseif ( $old_cmp === '>=' ) {
4385 $authors[] = $old->getUserText( Revision
::RAW
);
4386 } elseif ( $new_cmp === '<=' ) {
4387 $authors[] = $new->getUserText( Revision
::RAW
);
4391 $dbr = wfGetDB( DB_REPLICA
);
4392 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4394 'rev_page' => $this->getArticleID(),
4395 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4396 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4398 [ 'LIMIT' => $limit +
1 ] // add one so caller knows it was truncated
4400 foreach ( $res as $row ) {
4401 $authors[] = $row->rev_user_text
;
4407 * Get the number of authors between the given revisions or revision IDs.
4408 * Used for diffs and other things that really need it.
4410 * @param int|Revision $old Old revision or rev ID (first before range by default)
4411 * @param int|Revision $new New revision or rev ID (first after range by default)
4412 * @param int $limit Maximum number of authors
4413 * @param string|array $options (Optional): Single option, or an array of options:
4414 * 'include_old' Include $old in the range; $new is excluded.
4415 * 'include_new' Include $new in the range; $old is excluded.
4416 * 'include_both' Include both $old and $new in the range.
4417 * Unknown option values are ignored.
4418 * @return int Number of revision authors in the range; zero if not both revisions exist
4420 public function countAuthorsBetween( $old, $new, $limit, $options = [] ) {
4421 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4422 return $authors ?
count( $authors ) : 0;
4426 * Compare with another title.
4428 * @param Title $title
4431 public function equals( Title
$title ) {
4432 // Note: === is necessary for proper matching of number-like titles.
4433 return $this->getInterwiki() === $title->getInterwiki()
4434 && $this->getNamespace() == $title->getNamespace()
4435 && $this->getDBkey() === $title->getDBkey();
4439 * Check if this title is a subpage of another title
4441 * @param Title $title
4444 public function isSubpageOf( Title
$title ) {
4445 return $this->getInterwiki() === $title->getInterwiki()
4446 && $this->getNamespace() == $title->getNamespace()
4447 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4451 * Check if page exists. For historical reasons, this function simply
4452 * checks for the existence of the title in the page table, and will
4453 * thus return false for interwiki links, special pages and the like.
4454 * If you want to know if a title can be meaningfully viewed, you should
4455 * probably call the isKnown() method instead.
4457 * @param int $flags An optional bit field; may be Title::GAID_FOR_UPDATE to check
4458 * from master/for update
4461 public function exists( $flags = 0 ) {
4462 $exists = $this->getArticleID( $flags ) != 0;
4463 Hooks
::run( 'TitleExists', [ $this, &$exists ] );
4468 * Should links to this title be shown as potentially viewable (i.e. as
4469 * "bluelinks"), even if there's no record by this title in the page
4472 * This function is semi-deprecated for public use, as well as somewhat
4473 * misleadingly named. You probably just want to call isKnown(), which
4474 * calls this function internally.
4476 * (ISSUE: Most of these checks are cheap, but the file existence check
4477 * can potentially be quite expensive. Including it here fixes a lot of
4478 * existing code, but we might want to add an optional parameter to skip
4479 * it and any other expensive checks.)
4483 public function isAlwaysKnown() {
4487 * Allows overriding default behavior for determining if a page exists.
4488 * If $isKnown is kept as null, regular checks happen. If it's
4489 * a boolean, this value is returned by the isKnown method.
4493 * @param Title $title
4494 * @param bool|null $isKnown
4496 Hooks
::run( 'TitleIsAlwaysKnown', [ $this, &$isKnown ] );
4498 if ( !is_null( $isKnown ) ) {
4502 if ( $this->isExternal() ) {
4503 return true; // any interwiki link might be viewable, for all we know
4506 switch ( $this->mNamespace
) {
4509 // file exists, possibly in a foreign repo
4510 return (bool)wfFindFile( $this );
4512 // valid special page
4513 return SpecialPageFactory
::exists( $this->getDBkey() );
4515 // selflink, possibly with fragment
4516 return $this->mDbkeyform
== '';
4518 // known system message
4519 return $this->hasSourceText() !== false;
4526 * Does this title refer to a page that can (or might) be meaningfully
4527 * viewed? In particular, this function may be used to determine if
4528 * links to the title should be rendered as "bluelinks" (as opposed to
4529 * "redlinks" to non-existent pages).
4530 * Adding something else to this function will cause inconsistency
4531 * since LinkHolderArray calls isAlwaysKnown() and does its own
4532 * page existence check.
4536 public function isKnown() {
4537 return $this->isAlwaysKnown() ||
$this->exists();
4541 * Does this page have source text?
4545 public function hasSourceText() {
4546 if ( $this->exists() ) {
4550 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4551 // If the page doesn't exist but is a known system message, default
4552 // message content will be displayed, same for language subpages-
4553 // Use always content language to avoid loading hundreds of languages
4554 // to get the link color.
4556 list( $name, ) = MessageCache
::singleton()->figureMessage(
4557 $wgContLang->lcfirst( $this->getText() )
4559 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4560 return $message->exists();
4567 * Get the default message text or false if the message doesn't exist
4569 * @return string|bool
4571 public function getDefaultMessageText() {
4574 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4578 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4579 $wgContLang->lcfirst( $this->getText() )
4581 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4583 if ( $message->exists() ) {
4584 return $message->plain();
4591 * Updates page_touched for this page; called from LinksUpdate.php
4593 * @param string $purgeTime [optional] TS_MW timestamp
4594 * @return bool True if the update succeeded
4596 public function invalidateCache( $purgeTime = null ) {
4597 if ( wfReadOnly() ) {
4599 } elseif ( $this->mArticleID
=== 0 ) {
4600 return true; // avoid gap locking if we know it's not there
4603 $dbw = wfGetDB( DB_MASTER
);
4604 $dbw->onTransactionPreCommitOrIdle( function () {
4605 ResourceLoaderWikiModule
::invalidateModuleCache( $this, null, null, wfWikiID() );
4608 $conds = $this->pageCond();
4609 DeferredUpdates
::addUpdate(
4610 new AutoCommitUpdate(
4613 function ( IDatabase
$dbw, $fname ) use ( $conds, $purgeTime ) {
4614 $dbTimestamp = $dbw->timestamp( $purgeTime ?
: time() );
4617 [ 'page_touched' => $dbTimestamp ],
4618 $conds +
[ 'page_touched < ' . $dbw->addQuotes( $dbTimestamp ) ],
4621 MediaWikiServices
::getInstance()->getLinkCache()->invalidateTitle( $this );
4624 DeferredUpdates
::PRESEND
4631 * Update page_touched timestamps and send CDN purge messages for
4632 * pages linking to this title. May be sent to the job queue depending
4633 * on the number of links. Typically called on create and delete.
4635 public function touchLinks() {
4636 DeferredUpdates
::addUpdate( new HTMLCacheUpdate( $this, 'pagelinks', 'page-touch' ) );
4637 if ( $this->getNamespace() == NS_CATEGORY
) {
4638 DeferredUpdates
::addUpdate(
4639 new HTMLCacheUpdate( $this, 'categorylinks', 'category-touch' )
4645 * Get the last touched timestamp
4647 * @param IDatabase $db Optional db
4648 * @return string|false Last-touched timestamp
4650 public function getTouched( $db = null ) {
4651 if ( $db === null ) {
4652 $db = wfGetDB( DB_REPLICA
);
4654 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4659 * Get the timestamp when this page was updated since the user last saw it.
4662 * @return string|null
4664 public function getNotificationTimestamp( $user = null ) {
4667 // Assume current user if none given
4671 // Check cache first
4672 $uid = $user->getId();
4676 // avoid isset here, as it'll return false for null entries
4677 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4678 return $this->mNotificationTimestamp
[$uid];
4680 // Don't cache too much!
4681 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4682 $this->mNotificationTimestamp
= [];
4685 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
4686 $watchedItem = $store->getWatchedItem( $user, $this );
4687 if ( $watchedItem ) {
4688 $this->mNotificationTimestamp
[$uid] = $watchedItem->getNotificationTimestamp();
4690 $this->mNotificationTimestamp
[$uid] = false;
4693 return $this->mNotificationTimestamp
[$uid];
4697 * Generate strings used for xml 'id' names in monobook tabs
4699 * @param string $prepend Defaults to 'nstab-'
4700 * @return string XML 'id' name
4702 public function getNamespaceKey( $prepend = 'nstab-' ) {
4704 // Gets the subject namespace if this title
4705 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4706 // Checks if canonical namespace name exists for namespace
4707 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4708 // Uses canonical namespace name
4709 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4711 // Uses text of namespace
4712 $namespaceKey = $this->getSubjectNsText();
4714 // Makes namespace key lowercase
4715 $namespaceKey = $wgContLang->lc( $namespaceKey );
4717 if ( $namespaceKey == '' ) {
4718 $namespaceKey = 'main';
4720 // Changes file to image for backwards compatibility
4721 if ( $namespaceKey == 'file' ) {
4722 $namespaceKey = 'image';
4724 return $prepend . $namespaceKey;
4728 * Get all extant redirects to this Title
4730 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4731 * @return Title[] Array of Title redirects to this title
4733 public function getRedirectsHere( $ns = null ) {
4736 $dbr = wfGetDB( DB_REPLICA
);
4738 'rd_namespace' => $this->getNamespace(),
4739 'rd_title' => $this->getDBkey(),
4742 if ( $this->isExternal() ) {
4743 $where['rd_interwiki'] = $this->getInterwiki();
4745 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4747 if ( !is_null( $ns ) ) {
4748 $where['page_namespace'] = $ns;
4751 $res = $dbr->select(
4752 [ 'redirect', 'page' ],
4753 [ 'page_namespace', 'page_title' ],
4758 foreach ( $res as $row ) {
4759 $redirs[] = self
::newFromRow( $row );
4765 * Check if this Title is a valid redirect target
4769 public function isValidRedirectTarget() {
4770 global $wgInvalidRedirectTargets;
4772 if ( $this->isSpecialPage() ) {
4773 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4774 if ( $this->isSpecial( 'Userlogout' ) ) {
4778 foreach ( $wgInvalidRedirectTargets as $target ) {
4779 if ( $this->isSpecial( $target ) ) {
4789 * Get a backlink cache object
4791 * @return BacklinkCache
4793 public function getBacklinkCache() {
4794 return BacklinkCache
::get( $this );
4798 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4802 public function canUseNoindex() {
4803 global $wgExemptFromUserRobotsControl;
4805 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4806 ? MWNamespace
::getContentNamespaces()
4807 : $wgExemptFromUserRobotsControl;
4809 return !in_array( $this->mNamespace
, $bannedNamespaces );
4813 * Returns the raw sort key to be used for categories, with the specified
4814 * prefix. This will be fed to Collation::getSortKey() to get a
4815 * binary sortkey that can be used for actual sorting.
4817 * @param string $prefix The prefix to be used, specified using
4818 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4822 public function getCategorySortkey( $prefix = '' ) {
4823 $unprefixed = $this->getText();
4825 // Anything that uses this hook should only depend
4826 // on the Title object passed in, and should probably
4827 // tell the users to run updateCollations.php --force
4828 // in order to re-sort existing category relations.
4829 Hooks
::run( 'GetDefaultSortkey', [ $this, &$unprefixed ] );
4830 if ( $prefix !== '' ) {
4831 # Separate with a line feed, so the unprefixed part is only used as
4832 # a tiebreaker when two pages have the exact same prefix.
4833 # In UCA, tab is the only character that can sort above LF
4834 # so we strip both of them from the original prefix.
4835 $prefix = strtr( $prefix, "\n\t", ' ' );
4836 return "$prefix\n$unprefixed";
4842 * Returns the page language code saved in the database, if $wgPageLanguageUseDB is set
4843 * to true in LocalSettings.php, otherwise returns false. If there is no language saved in
4844 * the db, it will return NULL.
4846 * @return string|null|bool
4848 private function getDbPageLanguageCode() {
4849 global $wgPageLanguageUseDB;
4851 // check, if the page language could be saved in the database, and if so and
4852 // the value is not requested already, lookup the page language using LinkCache
4853 if ( $wgPageLanguageUseDB && $this->mDbPageLanguage
=== false ) {
4854 $linkCache = LinkCache
::singleton();
4855 $linkCache->addLinkObj( $this );
4856 $this->mDbPageLanguage
= $linkCache->getGoodLinkFieldObj( $this, 'lang' );
4859 return $this->mDbPageLanguage
;
4863 * Get the language in which the content of this page is written in
4864 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4865 * e.g. $wgLang (such as special pages, which are in the user language).
4870 public function getPageLanguage() {
4871 global $wgLang, $wgLanguageCode;
4872 if ( $this->isSpecialPage() ) {
4873 // special pages are in the user language
4877 // Checking if DB language is set
4878 $dbPageLanguage = $this->getDbPageLanguageCode();
4879 if ( $dbPageLanguage ) {
4880 return wfGetLangObj( $dbPageLanguage );
4883 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4884 // Note that this may depend on user settings, so the cache should
4885 // be only per-request.
4886 // NOTE: ContentHandler::getPageLanguage() may need to load the
4887 // content to determine the page language!
4888 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4890 $contentHandler = ContentHandler
::getForTitle( $this );
4891 $langObj = $contentHandler->getPageLanguage( $this );
4892 $this->mPageLanguage
= [ $langObj->getCode(), $wgLanguageCode ];
4894 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4901 * Get the language in which the content of this page is written when
4902 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4903 * e.g. $wgLang (such as special pages, which are in the user language).
4908 public function getPageViewLanguage() {
4911 if ( $this->isSpecialPage() ) {
4912 // If the user chooses a variant, the content is actually
4913 // in a language whose code is the variant code.
4914 $variant = $wgLang->getPreferredVariant();
4915 if ( $wgLang->getCode() !== $variant ) {
4916 return Language
::factory( $variant );
4922 // Checking if DB language is set
4923 $dbPageLanguage = $this->getDbPageLanguageCode();
4924 if ( $dbPageLanguage ) {
4925 $pageLang = wfGetLangObj( $dbPageLanguage );
4926 $variant = $pageLang->getPreferredVariant();
4927 if ( $pageLang->getCode() !== $variant ) {
4928 $pageLang = Language
::factory( $variant );
4934 // @note Can't be cached persistently, depends on user settings.
4935 // @note ContentHandler::getPageViewLanguage() may need to load the
4936 // content to determine the page language!
4937 $contentHandler = ContentHandler
::getForTitle( $this );
4938 $pageLang = $contentHandler->getPageViewLanguage( $this );
4943 * Get a list of rendered edit notices for this page.
4945 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4946 * they will already be wrapped in paragraphs.
4949 * @param int $oldid Revision ID that's being edited
4952 public function getEditNotices( $oldid = 0 ) {
4955 // Optional notice for the entire namespace
4956 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4957 $msg = wfMessage( $editnotice_ns );
4958 if ( $msg->exists() ) {
4959 $html = $msg->parseAsBlock();
4960 // Edit notices may have complex logic, but output nothing (T91715)
4961 if ( trim( $html ) !== '' ) {
4962 $notices[$editnotice_ns] = Html
::rawElement(
4966 'mw-editnotice-namespace',
4967 Sanitizer
::escapeClass( "mw-$editnotice_ns" )
4974 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4975 // Optional notice for page itself and any parent page
4976 $parts = explode( '/', $this->getDBkey() );
4977 $editnotice_base = $editnotice_ns;
4978 while ( count( $parts ) > 0 ) {
4979 $editnotice_base .= '-' . array_shift( $parts );
4980 $msg = wfMessage( $editnotice_base );
4981 if ( $msg->exists() ) {
4982 $html = $msg->parseAsBlock();
4983 if ( trim( $html ) !== '' ) {
4984 $notices[$editnotice_base] = Html
::rawElement(
4988 'mw-editnotice-base',
4989 Sanitizer
::escapeClass( "mw-$editnotice_base" )
4997 // Even if there are no subpages in namespace, we still don't want "/" in MediaWiki message keys
4998 $editnoticeText = $editnotice_ns . '-' . strtr( $this->getDBkey(), '/', '-' );
4999 $msg = wfMessage( $editnoticeText );
5000 if ( $msg->exists() ) {
5001 $html = $msg->parseAsBlock();
5002 if ( trim( $html ) !== '' ) {
5003 $notices[$editnoticeText] = Html
::rawElement(
5007 'mw-editnotice-page',
5008 Sanitizer
::escapeClass( "mw-$editnoticeText" )
5016 Hooks
::run( 'TitleGetEditNotices', [ $this, $oldid, &$notices ] );
5023 public function __sleep() {
5031 'mDefaultNamespace',
5035 public function __wakeup() {
5036 $this->mArticleID
= ( $this->mNamespace
>= 0 ) ?
-1 : 0;
5037 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
5038 $this->mTextform
= strtr( $this->mDbkeyform
, '_', ' ' );