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
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
30 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
31 * and does not rely on global state or the database.
33 * @internal documentation reviewed 15 Mar 2010
36 /** @var MapCacheLRU */
37 static private $titleCache = null;
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 /** @var string Text form (spaces not underscores) of the main part */
60 public $mTextform = '';
62 /** @var string URL-encoded form of the main part */
63 public $mUrlform = '';
65 /** @var string Main part with underscores */
66 public $mDbkeyform = '';
68 /** @var string Database key with the initial letter in the case specified by the user */
69 protected $mUserCaseDBKey;
71 /** @var int Namespace index, i.e. one of the NS_xxxx constants */
72 public $mNamespace = NS_MAIN
;
74 /** @var string Interwiki prefix */
75 public $mInterwiki = '';
77 /** @var bool Was this Title created from a string with a local interwiki prefix? */
78 private $mLocalInterwiki = false;
80 /** @var string Title fragment (i.e. the bit after the #) */
81 public $mFragment = '';
83 /** @var int Article ID, fetched from the link cache on demand */
84 public $mArticleID = -1;
86 /** @var bool|int ID of most recent revision */
87 protected $mLatestID = false;
90 * @var bool|string ID of the page's content model, i.e. one of the
91 * CONTENT_MODEL_XXX constants
93 public $mContentModel = false;
95 /** @var int Estimated number of revisions; null of not loaded */
96 private $mEstimateRevisions;
98 /** @var array Array of groups allowed to edit this article */
99 public $mRestrictions = array();
102 protected $mOldRestrictions = false;
104 /** @var bool Cascade restrictions on this page to included templates and images? */
105 public $mCascadeRestriction;
107 /** Caching the results of getCascadeProtectionSources */
108 public $mCascadingRestrictions;
110 /** @var array When do the restrictions on this page expire? */
111 protected $mRestrictionsExpiry = array();
113 /** @var bool Are cascading restrictions in effect on this page? */
114 protected $mHasCascadingRestrictions;
116 /** @var array Where are the cascading restrictions coming from on this page? */
117 public $mCascadeSources;
119 /** @var bool Boolean for initialisation on demand */
120 public $mRestrictionsLoaded = false;
122 /** @var string Text form including namespace/interwiki, initialised on demand */
123 protected $mPrefixedText = null;
125 /** @var mixed Cached value for getTitleProtection (create protection) */
126 public $mTitleProtection;
129 * @var int Namespace index when there is no namespace. Don't change the
130 * following default, NS_MAIN is hardcoded in several places. See bug 696.
131 * Zero except in {{transclusion}} tags.
133 public $mDefaultNamespace = NS_MAIN
;
136 * @var bool Is $wgUser watching this page? null if unfilled, accessed
137 * through userIsWatching()
139 protected $mWatched = null;
141 /** @var int The page length, 0 for special pages */
142 protected $mLength = -1;
144 /** @var null Is the article at this title a redirect? */
145 public $mRedirect = null;
147 /** @var array Associative array of user ID -> timestamp/false */
148 private $mNotificationTimestamp = array();
150 /** @var bool Whether a page has any subpages */
151 private $mHasSubpages;
153 /** @var bool The (string) language code of the page's language and content code. */
154 private $mPageLanguage = false;
156 /** @var string The page language code from the database */
157 private $mDbPageLanguage = null;
159 /** @var TitleValue A corresponding TitleValue object */
160 private $mTitleValue = null;
162 /** @var bool Would deleting this page be a big deletion? */
163 private $mIsBigDeletion = null;
167 * B/C kludge: provide a TitleParser for use by Title.
168 * Ideally, Title would have no methods that need this.
169 * Avoid usage of this singleton by using TitleValue
170 * and the associated services when possible.
172 * @return TitleParser
174 private static function getTitleParser() {
175 global $wgContLang, $wgLocalInterwikis;
177 static $titleCodec = null;
178 static $titleCodecFingerprint = null;
180 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
181 // make sure we are using the right one. To detect changes over the course
182 // of a request, we remember a fingerprint of the config used to create the
183 // codec singleton, and re-create it if the fingerprint doesn't match.
184 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
186 if ( $fingerprint !== $titleCodecFingerprint ) {
190 if ( !$titleCodec ) {
191 $titleCodec = new MediaWikiTitleCodec(
193 GenderCache
::singleton(),
196 $titleCodecFingerprint = $fingerprint;
203 * B/C kludge: provide a TitleParser for use by Title.
204 * Ideally, Title would have no methods that need this.
205 * Avoid usage of this singleton by using TitleValue
206 * and the associated services when possible.
208 * @return TitleFormatter
210 private static function getTitleFormatter() {
211 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
212 // which implements TitleFormatter.
213 return self
::getTitleParser();
216 function __construct() {
220 * Create a new Title from a prefixed DB key
222 * @param string $key The database key, which has underscores
223 * instead of spaces, possibly including namespace and
225 * @return Title|null Title, or null on an error
227 public static function newFromDBkey( $key ) {
229 $t->mDbkeyform
= $key;
230 if ( $t->secureAndSplit() ) {
238 * Create a new Title from a TitleValue
240 * @param TitleValue $titleValue Assumed to be safe.
244 public static function newFromTitleValue( TitleValue
$titleValue ) {
245 return self
::makeTitle(
246 $titleValue->getNamespace(),
247 $titleValue->getText(),
248 $titleValue->getFragment() );
252 * Create a new Title from text, such as what one would find in a link. De-
253 * codes any HTML entities in the text.
255 * @param string $text The link text; spaces, prefixes, and an
256 * initial ':' indicating the main namespace are accepted.
257 * @param int $defaultNamespace The namespace to use if none is specified
258 * by a prefix. If you want to force a specific namespace even if
259 * $text might begin with a namespace prefix, use makeTitle() or
261 * @throws MWException
262 * @return Title|null Title or null on an error.
264 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
265 if ( is_object( $text ) ) {
266 throw new MWException( 'Title::newFromText given an object' );
269 $cache = self
::getTitleCache();
272 * Wiki pages often contain multiple links to the same page.
273 * Title normalization and parsing can become expensive on
274 * pages with many links, so we can save a little time by
277 * In theory these are value objects and won't get changed...
279 if ( $defaultNamespace == NS_MAIN
&& $cache->has( $text ) ) {
280 return $cache->get( $text );
283 # Convert things like é ā or 〗 into normalized (bug 14952) text
284 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
287 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
288 $t->mDefaultNamespace
= intval( $defaultNamespace );
290 if ( $t->secureAndSplit() ) {
291 if ( $defaultNamespace == NS_MAIN
) {
292 $cache->set( $text, $t );
301 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
303 * Example of wrong and broken code:
304 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
306 * Example of right code:
307 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
309 * Create a new Title from URL-encoded text. Ensures that
310 * the given title's length does not exceed the maximum.
312 * @param string $url The title, as might be taken from a URL
313 * @return Title|null The new object, or null on an error
315 public static function newFromURL( $url ) {
318 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
319 # but some URLs used it as a space replacement and they still come
320 # from some external search tools.
321 if ( strpos( self
::legalChars(), '+' ) === false ) {
322 $url = str_replace( '+', ' ', $url );
325 $t->mDbkeyform
= str_replace( ' ', '_', $url );
326 if ( $t->secureAndSplit() ) {
334 * @return MapCacheLRU
336 private static function getTitleCache() {
337 if ( self
::$titleCache == null ) {
338 self
::$titleCache = new MapCacheLRU( self
::CACHE_MAX
);
340 return self
::$titleCache;
344 * Returns a list of fields that are to be selected for initializing Title
345 * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine
346 * whether to include page_content_model.
350 protected static function getSelectFields() {
351 global $wgContentHandlerUseDB;
354 'page_namespace', 'page_title', 'page_id',
355 'page_len', 'page_is_redirect', 'page_latest',
358 if ( $wgContentHandlerUseDB ) {
359 $fields[] = 'page_content_model';
366 * Create a new Title from an article ID
368 * @param int $id The page_id corresponding to the Title to create
369 * @param int $flags Use Title::GAID_FOR_UPDATE to use master
370 * @return Title|null The new object, or null on an error
372 public static function newFromID( $id, $flags = 0 ) {
373 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
374 $row = $db->selectRow(
376 self
::getSelectFields(),
377 array( 'page_id' => $id ),
380 if ( $row !== false ) {
381 $title = Title
::newFromRow( $row );
389 * Make an array of titles from an array of IDs
391 * @param int[] $ids Array of IDs
392 * @return Title[] Array of Titles
394 public static function newFromIDs( $ids ) {
395 if ( !count( $ids ) ) {
398 $dbr = wfGetDB( DB_SLAVE
);
402 self
::getSelectFields(),
403 array( 'page_id' => $ids ),
408 foreach ( $res as $row ) {
409 $titles[] = Title
::newFromRow( $row );
415 * Make a Title object from a DB row
417 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
418 * @return Title Corresponding Title
420 public static function newFromRow( $row ) {
421 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
422 $t->loadFromRow( $row );
427 * Load Title object fields from a DB row.
428 * If false is given, the title will be treated as non-existing.
430 * @param stdClass|bool $row Database row
432 public function loadFromRow( $row ) {
433 if ( $row ) { // page found
434 if ( isset( $row->page_id
) ) {
435 $this->mArticleID
= (int)$row->page_id
;
437 if ( isset( $row->page_len
) ) {
438 $this->mLength
= (int)$row->page_len
;
440 if ( isset( $row->page_is_redirect
) ) {
441 $this->mRedirect
= (bool)$row->page_is_redirect
;
443 if ( isset( $row->page_latest
) ) {
444 $this->mLatestID
= (int)$row->page_latest
;
446 if ( isset( $row->page_content_model
) ) {
447 $this->mContentModel
= strval( $row->page_content_model
);
449 $this->mContentModel
= false; # initialized lazily in getContentModel()
451 if ( isset( $row->page_lang
) ) {
452 $this->mDbPageLanguage
= (string)$row->page_lang
;
454 } else { // page not found
455 $this->mArticleID
= 0;
457 $this->mRedirect
= false;
458 $this->mLatestID
= 0;
459 $this->mContentModel
= false; # initialized lazily in getContentModel()
464 * Create a new Title from a namespace index and a DB key.
465 * It's assumed that $ns and $title are *valid*, for instance when
466 * they came directly from the database or a special page name.
467 * For convenience, spaces are converted to underscores so that
468 * eg user_text fields can be used directly.
470 * @param int $ns The namespace of the article
471 * @param string $title The unprefixed database key form
472 * @param string $fragment The link fragment (after the "#")
473 * @param string $interwiki The interwiki prefix
474 * @return Title The new object
476 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
478 $t->mInterwiki
= $interwiki;
479 $t->mFragment
= $fragment;
480 $t->mNamespace
= $ns = intval( $ns );
481 $t->mDbkeyform
= str_replace( ' ', '_', $title );
482 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
483 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
484 $t->mTextform
= str_replace( '_', ' ', $title );
485 $t->mContentModel
= false; # initialized lazily in getContentModel()
490 * Create a new Title from a namespace index and a DB key.
491 * The parameters will be checked for validity, which is a bit slower
492 * than makeTitle() but safer for user-provided data.
494 * @param int $ns The namespace of the article
495 * @param string $title Database key form
496 * @param string $fragment The link fragment (after the "#")
497 * @param string $interwiki Interwiki prefix
498 * @return Title The new object, or null on an error
500 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
501 if ( !MWNamespace
::exists( $ns ) ) {
506 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki, true );
507 if ( $t->secureAndSplit() ) {
515 * Create a new Title for the Main Page
517 * @return Title The new object
519 public static function newMainPage() {
520 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
521 // Don't give fatal errors if the message is broken
523 $title = Title
::newFromText( 'Main Page' );
529 * Extract a redirect destination from a string and return the
530 * Title, or null if the text doesn't contain a valid redirect
531 * This will only return the very next target, useful for
532 * the redirect table and other checks that don't need full recursion
534 * @param string $text Text with possible redirect
535 * @return Title The corresponding Title
536 * @deprecated since 1.21, use Content::getRedirectTarget instead.
538 public static function newFromRedirect( $text ) {
539 ContentHandler
::deprecated( __METHOD__
, '1.21' );
541 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
542 return $content->getRedirectTarget();
546 * Extract a redirect destination from a string and return the
547 * Title, or null if the text doesn't contain a valid redirect
548 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
549 * in order to provide (hopefully) the Title of the final destination instead of another redirect
551 * @param string $text Text with possible redirect
553 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
555 public static function newFromRedirectRecurse( $text ) {
556 ContentHandler
::deprecated( __METHOD__
, '1.21' );
558 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
559 return $content->getUltimateRedirectTarget();
563 * Extract a redirect destination from a string and return an
564 * array of Titles, or null if the text doesn't contain a valid redirect
565 * The last element in the array is the final destination after all redirects
566 * have been resolved (up to $wgMaxRedirects times)
568 * @param string $text Text with possible redirect
569 * @return Title[] Array of Titles, with the destination last
570 * @deprecated since 1.21, use Content::getRedirectChain instead.
572 public static function newFromRedirectArray( $text ) {
573 ContentHandler
::deprecated( __METHOD__
, '1.21' );
575 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
576 return $content->getRedirectChain();
580 * Get the prefixed DB key associated with an ID
582 * @param int $id The page_id of the article
583 * @return Title|null An object representing the article, or null if no such article was found
585 public static function nameOf( $id ) {
586 $dbr = wfGetDB( DB_SLAVE
);
588 $s = $dbr->selectRow(
590 array( 'page_namespace', 'page_title' ),
591 array( 'page_id' => $id ),
594 if ( $s === false ) {
598 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
603 * Get a regex character class describing the legal characters in a link
605 * @return string The list of characters, not delimited
607 public static function legalChars() {
608 global $wgLegalTitleChars;
609 return $wgLegalTitleChars;
613 * Returns a simple regex that will match on characters and sequences invalid in titles.
614 * Note that this doesn't pick up many things that could be wrong with titles, but that
615 * replacing this regex with something valid will make many titles valid.
617 * @deprecated since 1.25, use MediaWikiTitleCodec::getTitleInvalidRegex() instead
619 * @return string Regex string
621 static function getTitleInvalidRegex() {
622 wfDeprecated( __METHOD__
, '1.25' );
623 return MediaWikiTitleCodec
::getTitleInvalidRegex();
627 * Utility method for converting a character sequence from bytes to Unicode.
629 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
630 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
632 * @param string $byteClass
635 public static function convertByteClassToUnicodeClass( $byteClass ) {
636 $length = strlen( $byteClass );
638 $x0 = $x1 = $x2 = '';
640 $d0 = $d1 = $d2 = '';
641 // Decoded integer codepoints
642 $ord0 = $ord1 = $ord2 = 0;
644 $r0 = $r1 = $r2 = '';
648 $allowUnicode = false;
649 for ( $pos = 0; $pos < $length; $pos++
) {
650 // Shift the queues down
659 // Load the current input token and decoded values
660 $inChar = $byteClass[$pos];
661 if ( $inChar == '\\' ) {
662 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
663 $x0 = $inChar . $m[0];
664 $d0 = chr( hexdec( $m[1] ) );
665 $pos +
= strlen( $m[0] );
666 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
667 $x0 = $inChar . $m[0];
668 $d0 = chr( octdec( $m[0] ) );
669 $pos +
= strlen( $m[0] );
670 } elseif ( $pos +
1 >= $length ) {
673 $d0 = $byteClass[$pos +
1];
681 // Load the current re-encoded value
682 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
683 $r0 = sprintf( '\x%02x', $ord0 );
684 } elseif ( $ord0 >= 0x80 ) {
685 // Allow unicode if a single high-bit character appears
686 $r0 = sprintf( '\x%02x', $ord0 );
687 $allowUnicode = true;
688 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
694 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
696 if ( $ord2 > $ord0 ) {
698 } elseif ( $ord0 >= 0x80 ) {
700 $allowUnicode = true;
701 if ( $ord2 < 0x80 ) {
702 // Keep the non-unicode section of the range
709 // Reset state to the initial value
710 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
711 } elseif ( $ord2 < 0x80 ) {
716 if ( $ord1 < 0x80 ) {
719 if ( $ord0 < 0x80 ) {
722 if ( $allowUnicode ) {
723 $out .= '\u0080-\uFFFF';
729 * Make a prefixed DB key from a DB key and a namespace index
731 * @param int $ns Numerical representation of the namespace
732 * @param string $title The DB key form the title
733 * @param string $fragment The link fragment (after the "#")
734 * @param string $interwiki The interwiki prefix
735 * @param bool $canoncialNamespace If true, use the canonical name for
736 * $ns instead of the localized version.
737 * @return string The prefixed form of the title
739 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
740 $canoncialNamespace = false
744 if ( $canoncialNamespace ) {
745 $namespace = MWNamespace
::getCanonicalName( $ns );
747 $namespace = $wgContLang->getNsText( $ns );
749 $name = $namespace == '' ?
$title : "$namespace:$title";
750 if ( strval( $interwiki ) != '' ) {
751 $name = "$interwiki:$name";
753 if ( strval( $fragment ) != '' ) {
754 $name .= '#' . $fragment;
760 * Escape a text fragment, say from a link, for a URL
762 * @param string $fragment Containing a URL or link fragment (after the "#")
763 * @return string Escaped string
765 static function escapeFragmentForURL( $fragment ) {
766 # Note that we don't urlencode the fragment. urlencoded Unicode
767 # fragments appear not to work in IE (at least up to 7) or in at least
768 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
769 # to care if they aren't encoded.
770 return Sanitizer
::escapeId( $fragment, 'noninitial' );
774 * Callback for usort() to do title sorts by (namespace, title)
779 * @return int Result of string comparison, or namespace comparison
781 public static function compare( $a, $b ) {
782 if ( $a->getNamespace() == $b->getNamespace() ) {
783 return strcmp( $a->getText(), $b->getText() );
785 return $a->getNamespace() - $b->getNamespace();
790 * Determine whether the object refers to a page within
791 * this project (either this wiki or a wiki with a local
792 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
794 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
796 public function isLocal() {
797 if ( $this->isExternal() ) {
798 $iw = Interwiki
::fetch( $this->mInterwiki
);
800 return $iw->isLocal();
807 * Is this Title interwiki?
811 public function isExternal() {
812 return $this->mInterwiki
!== '';
816 * Get the interwiki prefix
818 * Use Title::isExternal to check if a interwiki is set
820 * @return string Interwiki prefix
822 public function getInterwiki() {
823 return $this->mInterwiki
;
827 * Was this a local interwiki link?
831 public function wasLocalInterwiki() {
832 return $this->mLocalInterwiki
;
836 * Determine whether the object refers to a page within
837 * this project and is transcludable.
839 * @return bool True if this is transcludable
841 public function isTrans() {
842 if ( !$this->isExternal() ) {
846 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
850 * Returns the DB name of the distant wiki which owns the object.
852 * @return string The DB name
854 public function getTransWikiID() {
855 if ( !$this->isExternal() ) {
859 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
863 * Get a TitleValue object representing this Title.
865 * @note Not all valid Titles have a corresponding valid TitleValue
866 * (e.g. TitleValues cannot represent page-local links that have a
867 * fragment but no title text).
869 * @return TitleValue|null
871 public function getTitleValue() {
872 if ( $this->mTitleValue
=== null ) {
874 $this->mTitleValue
= new TitleValue(
875 $this->getNamespace(),
877 $this->getFragment() );
878 } catch ( InvalidArgumentException
$ex ) {
879 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
880 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
884 return $this->mTitleValue
;
888 * Get the text form (spaces not underscores) of the main part
890 * @return string Main part of the title
892 public function getText() {
893 return $this->mTextform
;
897 * Get the URL-encoded form of the main part
899 * @return string Main part of the title, URL-encoded
901 public function getPartialURL() {
902 return $this->mUrlform
;
906 * Get the main part with underscores
908 * @return string Main part of the title, with underscores
910 public function getDBkey() {
911 return $this->mDbkeyform
;
915 * Get the DB key with the initial letter case as specified by the user
917 * @return string DB key
919 function getUserCaseDBKey() {
920 if ( !is_null( $this->mUserCaseDBKey
) ) {
921 return $this->mUserCaseDBKey
;
923 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
924 return $this->mDbkeyform
;
929 * Get the namespace index, i.e. one of the NS_xxxx constants.
931 * @return int Namespace index
933 public function getNamespace() {
934 return $this->mNamespace
;
938 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
940 * @throws MWException
941 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
942 * @return string Content model id
944 public function getContentModel( $flags = 0 ) {
945 # Calling getArticleID() loads the field from cache as needed
946 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
947 $linkCache = LinkCache
::singleton();
948 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
951 if ( !$this->mContentModel
) {
952 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
955 if ( !$this->mContentModel
) {
956 throw new MWException( 'Failed to determine content model!' );
959 return $this->mContentModel
;
963 * Convenience method for checking a title's content model name
965 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
966 * @return bool True if $this->getContentModel() == $id
968 public function hasContentModel( $id ) {
969 return $this->getContentModel() == $id;
973 * Get the namespace text
975 * @return string Namespace text
977 public function getNsText() {
978 if ( $this->isExternal() ) {
979 // This probably shouldn't even happen. ohh man, oh yuck.
980 // But for interwiki transclusion it sometimes does.
981 // Shit. Shit shit shit.
983 // Use the canonical namespaces if possible to try to
984 // resolve a foreign namespace.
985 if ( MWNamespace
::exists( $this->mNamespace
) ) {
986 return MWNamespace
::getCanonicalName( $this->mNamespace
);
991 $formatter = self
::getTitleFormatter();
992 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
993 } catch ( InvalidArgumentException
$ex ) {
994 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1000 * Get the namespace text of the subject (rather than talk) page
1002 * @return string Namespace text
1004 public function getSubjectNsText() {
1006 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1010 * Get the namespace text of the talk page
1012 * @return string Namespace text
1014 public function getTalkNsText() {
1016 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1020 * Could this title have a corresponding talk page?
1024 public function canTalk() {
1025 return MWNamespace
::canTalk( $this->mNamespace
);
1029 * Is this in a namespace that allows actual pages?
1033 public function canExist() {
1034 return $this->mNamespace
>= NS_MAIN
;
1038 * Can this title be added to a user's watchlist?
1042 public function isWatchable() {
1043 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1047 * Returns true if this is a special page.
1051 public function isSpecialPage() {
1052 return $this->getNamespace() == NS_SPECIAL
;
1056 * Returns true if this title resolves to the named special page
1058 * @param string $name The special page name
1061 public function isSpecial( $name ) {
1062 if ( $this->isSpecialPage() ) {
1063 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1064 if ( $name == $thisName ) {
1072 * If the Title refers to a special page alias which is not the local default, resolve
1073 * the alias, and localise the name as necessary. Otherwise, return $this
1077 public function fixSpecialName() {
1078 if ( $this->isSpecialPage() ) {
1079 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1080 if ( $canonicalName ) {
1081 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1082 if ( $localName != $this->mDbkeyform
) {
1083 return Title
::makeTitle( NS_SPECIAL
, $localName );
1091 * Returns true if the title is inside the specified namespace.
1093 * Please make use of this instead of comparing to getNamespace()
1094 * This function is much more resistant to changes we may make
1095 * to namespaces than code that makes direct comparisons.
1096 * @param int $ns The namespace
1100 public function inNamespace( $ns ) {
1101 return MWNamespace
::equals( $this->getNamespace(), $ns );
1105 * Returns true if the title is inside one of the specified namespaces.
1107 * @param int $namespaces,... The namespaces to check for
1111 public function inNamespaces( /* ... */ ) {
1112 $namespaces = func_get_args();
1113 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1114 $namespaces = $namespaces[0];
1117 foreach ( $namespaces as $ns ) {
1118 if ( $this->inNamespace( $ns ) ) {
1127 * Returns true if the title has the same subject namespace as the
1128 * namespace specified.
1129 * For example this method will take NS_USER and return true if namespace
1130 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1131 * as their subject namespace.
1133 * This is MUCH simpler than individually testing for equivalence
1134 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1139 public function hasSubjectNamespace( $ns ) {
1140 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1144 * Is this Title in a namespace which contains content?
1145 * In other words, is this a content page, for the purposes of calculating
1150 public function isContentPage() {
1151 return MWNamespace
::isContent( $this->getNamespace() );
1155 * Would anybody with sufficient privileges be able to move this page?
1156 * Some pages just aren't movable.
1160 public function isMovable() {
1161 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1162 // Interwiki title or immovable namespace. Hooks don't get to override here
1167 Hooks
::run( 'TitleIsMovable', array( $this, &$result ) );
1172 * Is this the mainpage?
1173 * @note Title::newFromText seems to be sufficiently optimized by the title
1174 * cache that we don't need to over-optimize by doing direct comparisons and
1175 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1176 * ends up reporting something differently than $title->isMainPage();
1181 public function isMainPage() {
1182 return $this->equals( Title
::newMainPage() );
1186 * Is this a subpage?
1190 public function isSubpage() {
1191 return MWNamespace
::hasSubpages( $this->mNamespace
)
1192 ?
strpos( $this->getText(), '/' ) !== false
1197 * Is this a conversion table for the LanguageConverter?
1201 public function isConversionTable() {
1202 // @todo ConversionTable should become a separate content model.
1204 return $this->getNamespace() == NS_MEDIAWIKI
&&
1205 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1209 * Does that page contain wikitext, or it is JS, CSS or whatever?
1213 public function isWikitextPage() {
1214 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1218 * Could this page contain custom CSS or JavaScript for the global UI.
1219 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1220 * or CONTENT_MODEL_JAVASCRIPT.
1222 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1225 * Note that this method should not return true for pages that contain and
1226 * show "inactive" CSS or JS.
1230 public function isCssOrJsPage() {
1231 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1232 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1233 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1235 # @note This hook is also called in ContentHandler::getDefaultModel.
1236 # It's called here again to make sure hook functions can force this
1237 # method to return true even outside the MediaWiki namespace.
1239 Hooks
::run( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1241 return $isCssOrJsPage;
1245 * Is this a .css or .js subpage of a user page?
1248 public function isCssJsSubpage() {
1249 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1250 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1251 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1255 * Trim down a .css or .js subpage title to get the corresponding skin name
1257 * @return string Containing skin name from .css or .js subpage title
1259 public function getSkinFromCssJsSubpage() {
1260 $subpage = explode( '/', $this->mTextform
);
1261 $subpage = $subpage[count( $subpage ) - 1];
1262 $lastdot = strrpos( $subpage, '.' );
1263 if ( $lastdot === false ) {
1264 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1266 return substr( $subpage, 0, $lastdot );
1270 * Is this a .css subpage of a user page?
1274 public function isCssSubpage() {
1275 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1276 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1280 * Is this a .js subpage of a user page?
1284 public function isJsSubpage() {
1285 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1286 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1290 * Is this a talk page of some sort?
1294 public function isTalkPage() {
1295 return MWNamespace
::isTalk( $this->getNamespace() );
1299 * Get a Title object associated with the talk page of this article
1301 * @return Title The object for the talk page
1303 public function getTalkPage() {
1304 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1308 * Get a title object associated with the subject page of this
1311 * @return Title The object for the subject page
1313 public function getSubjectPage() {
1314 // Is this the same title?
1315 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1316 if ( $this->getNamespace() == $subjectNS ) {
1319 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1323 * Get the other title for this page, if this is a subject page
1324 * get the talk page, if it is a subject page get the talk page
1327 * @throws MWException
1330 public function getOtherPage() {
1331 if ( $this->isSpecialPage() ) {
1332 throw new MWException( 'Special pages cannot have other pages' );
1334 if ( $this->isTalkPage() ) {
1335 return $this->getSubjectPage();
1337 return $this->getTalkPage();
1342 * Get the default namespace index, for when there is no namespace
1344 * @return int Default namespace index
1346 public function getDefaultNamespace() {
1347 return $this->mDefaultNamespace
;
1351 * Get the Title fragment (i.e.\ the bit after the #) in text form
1353 * Use Title::hasFragment to check for a fragment
1355 * @return string Title fragment
1357 public function getFragment() {
1358 return $this->mFragment
;
1362 * Check if a Title fragment is set
1367 public function hasFragment() {
1368 return $this->mFragment
!== '';
1372 * Get the fragment in URL form, including the "#" character if there is one
1373 * @return string Fragment in URL form
1375 public function getFragmentForURL() {
1376 if ( !$this->hasFragment() ) {
1379 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1384 * Set the fragment for this title. Removes the first character from the
1385 * specified fragment before setting, so it assumes you're passing it with
1388 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1389 * Still in active use privately.
1391 * @param string $fragment Text
1393 public function setFragment( $fragment ) {
1394 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1398 * Prefix some arbitrary text with the namespace or interwiki prefix
1401 * @param string $name The text
1402 * @return string The prefixed text
1404 private function prefix( $name ) {
1406 if ( $this->isExternal() ) {
1407 $p = $this->mInterwiki
. ':';
1410 if ( 0 != $this->mNamespace
) {
1411 $p .= $this->getNsText() . ':';
1417 * Get the prefixed database key form
1419 * @return string The prefixed title, with underscores and
1420 * any interwiki and namespace prefixes
1422 public function getPrefixedDBkey() {
1423 $s = $this->prefix( $this->mDbkeyform
);
1424 $s = str_replace( ' ', '_', $s );
1429 * Get the prefixed title with spaces.
1430 * This is the form usually used for display
1432 * @return string The prefixed title, with spaces
1434 public function getPrefixedText() {
1435 if ( $this->mPrefixedText
=== null ) {
1436 $s = $this->prefix( $this->mTextform
);
1437 $s = str_replace( '_', ' ', $s );
1438 $this->mPrefixedText
= $s;
1440 return $this->mPrefixedText
;
1444 * Return a string representation of this title
1446 * @return string Representation of this title
1448 public function __toString() {
1449 return $this->getPrefixedText();
1453 * Get the prefixed title with spaces, plus any fragment
1454 * (part beginning with '#')
1456 * @return string The prefixed title, with spaces and the fragment, including '#'
1458 public function getFullText() {
1459 $text = $this->getPrefixedText();
1460 if ( $this->hasFragment() ) {
1461 $text .= '#' . $this->getFragment();
1467 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1471 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1475 * @return string Root name
1478 public function getRootText() {
1479 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1480 return $this->getText();
1483 return strtok( $this->getText(), '/' );
1487 * Get the root page name title, i.e. the leftmost part before any slashes
1491 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1492 * # returns: Title{User:Foo}
1495 * @return Title Root title
1498 public function getRootTitle() {
1499 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1503 * Get the base page name without a namespace, i.e. the part before the subpage name
1507 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1508 * # returns: 'Foo/Bar'
1511 * @return string Base name
1513 public function getBaseText() {
1514 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1515 return $this->getText();
1518 $parts = explode( '/', $this->getText() );
1519 # Don't discard the real title if there's no subpage involved
1520 if ( count( $parts ) > 1 ) {
1521 unset( $parts[count( $parts ) - 1] );
1523 return implode( '/', $parts );
1527 * Get the base page name title, i.e. the part before the subpage name
1531 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1532 * # returns: Title{User:Foo/Bar}
1535 * @return Title Base title
1538 public function getBaseTitle() {
1539 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1543 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1547 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1551 * @return string Subpage name
1553 public function getSubpageText() {
1554 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1555 return $this->mTextform
;
1557 $parts = explode( '/', $this->mTextform
);
1558 return $parts[count( $parts ) - 1];
1562 * Get the title for a subpage of the current page
1566 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1567 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1570 * @param string $text The subpage name to add to the title
1571 * @return Title Subpage title
1574 public function getSubpage( $text ) {
1575 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1579 * Get a URL-encoded form of the subpage text
1581 * @return string URL-encoded subpage name
1583 public function getSubpageUrlForm() {
1584 $text = $this->getSubpageText();
1585 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1590 * Get a URL-encoded title (not an actual URL) including interwiki
1592 * @return string The URL-encoded form
1594 public function getPrefixedURL() {
1595 $s = $this->prefix( $this->mDbkeyform
);
1596 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1601 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1602 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1603 * second argument named variant. This was deprecated in favor
1604 * of passing an array of option with a "variant" key
1605 * Once $query2 is removed for good, this helper can be dropped
1606 * and the wfArrayToCgi moved to getLocalURL();
1608 * @since 1.19 (r105919)
1609 * @param array|string $query
1610 * @param bool $query2
1613 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1614 if ( $query2 !== false ) {
1615 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1616 "method called with a second parameter is deprecated. Add your " .
1617 "parameter to an array passed as the first parameter.", "1.19" );
1619 if ( is_array( $query ) ) {
1620 $query = wfArrayToCgi( $query );
1623 if ( is_string( $query2 ) ) {
1624 // $query2 is a string, we will consider this to be
1625 // a deprecated $variant argument and add it to the query
1626 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1628 $query2 = wfArrayToCgi( $query2 );
1630 // If we have $query content add a & to it first
1634 // Now append the queries together
1641 * Get a real URL referring to this title, with interwiki link and
1644 * @see self::getLocalURL for the arguments.
1646 * @param array|string $query
1647 * @param bool $query2
1648 * @param string $proto Protocol type to use in URL
1649 * @return string The URL
1651 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1652 $query = self
::fixUrlQueryArgs( $query, $query2 );
1654 # Hand off all the decisions on urls to getLocalURL
1655 $url = $this->getLocalURL( $query );
1657 # Expand the url to make it a full url. Note that getLocalURL has the
1658 # potential to output full urls for a variety of reasons, so we use
1659 # wfExpandUrl instead of simply prepending $wgServer
1660 $url = wfExpandUrl( $url, $proto );
1662 # Finally, add the fragment.
1663 $url .= $this->getFragmentForURL();
1665 Hooks
::run( 'GetFullURL', array( &$this, &$url, $query ) );
1670 * Get a URL with no fragment or server name (relative URL) from a Title object.
1671 * If this page is generated with action=render, however,
1672 * $wgServer is prepended to make an absolute URL.
1674 * @see self::getFullURL to always get an absolute URL.
1675 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1676 * valid to link, locally, to the current Title.
1677 * @see self::newFromText to produce a Title object.
1679 * @param string|array $query An optional query string,
1680 * not used for interwiki links. Can be specified as an associative array as well,
1681 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1682 * Some query patterns will trigger various shorturl path replacements.
1683 * @param array $query2 An optional secondary query array. This one MUST
1684 * be an array. If a string is passed it will be interpreted as a deprecated
1685 * variant argument and urlencoded into a variant= argument.
1686 * This second query argument will be added to the $query
1687 * The second parameter is deprecated since 1.19. Pass it as a key,value
1688 * pair in the first parameter array instead.
1690 * @return string String of the URL.
1692 public function getLocalURL( $query = '', $query2 = false ) {
1693 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1695 $query = self
::fixUrlQueryArgs( $query, $query2 );
1697 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1699 $namespace = $this->getNsText();
1700 if ( $namespace != '' ) {
1701 # Can this actually happen? Interwikis shouldn't be parsed.
1702 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1705 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1706 $url = wfAppendQuery( $url, $query );
1708 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1709 if ( $query == '' ) {
1710 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1711 Hooks
::run( 'GetLocalURL::Article', array( &$this, &$url ) );
1713 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1717 if ( !empty( $wgActionPaths )
1718 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1720 $action = urldecode( $matches[2] );
1721 if ( isset( $wgActionPaths[$action] ) ) {
1722 $query = $matches[1];
1723 if ( isset( $matches[4] ) ) {
1724 $query .= $matches[4];
1726 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1727 if ( $query != '' ) {
1728 $url = wfAppendQuery( $url, $query );
1734 && $wgVariantArticlePath
1735 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1736 && $this->getPageLanguage()->hasVariants()
1737 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1739 $variant = urldecode( $matches[1] );
1740 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1741 // Only do the variant replacement if the given variant is a valid
1742 // variant for the page's language.
1743 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1744 $url = str_replace( '$1', $dbkey, $url );
1748 if ( $url === false ) {
1749 if ( $query == '-' ) {
1752 $url = "{$wgScript}?title={$dbkey}&{$query}";
1756 Hooks
::run( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1758 // @todo FIXME: This causes breakage in various places when we
1759 // actually expected a local URL and end up with dupe prefixes.
1760 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1761 $url = $wgServer . $url;
1764 Hooks
::run( 'GetLocalURL', array( &$this, &$url, $query ) );
1769 * Get a URL that's the simplest URL that will be valid to link, locally,
1770 * to the current Title. It includes the fragment, but does not include
1771 * the server unless action=render is used (or the link is external). If
1772 * there's a fragment but the prefixed text is empty, we just return a link
1775 * The result obviously should not be URL-escaped, but does need to be
1776 * HTML-escaped if it's being output in HTML.
1778 * @param array $query
1779 * @param bool $query2
1780 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1781 * @see self::getLocalURL for the arguments.
1782 * @return string The URL
1784 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1785 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1786 $ret = $this->getFullURL( $query, $query2, $proto );
1787 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1788 $ret = $this->getFragmentForURL();
1790 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1796 * Get the URL form for an internal link.
1797 * - Used in various Squid-related code, in case we have a different
1798 * internal hostname for the server from the exposed one.
1800 * This uses $wgInternalServer to qualify the path, or $wgServer
1801 * if $wgInternalServer is not set. If the server variable used is
1802 * protocol-relative, the URL will be expanded to http://
1804 * @see self::getLocalURL for the arguments.
1805 * @return string The URL
1807 public function getInternalURL( $query = '', $query2 = false ) {
1808 global $wgInternalServer, $wgServer;
1809 $query = self
::fixUrlQueryArgs( $query, $query2 );
1810 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1811 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1812 Hooks
::run( 'GetInternalURL', array( &$this, &$url, $query ) );
1817 * Get the URL for a canonical link, for use in things like IRC and
1818 * e-mail notifications. Uses $wgCanonicalServer and the
1819 * GetCanonicalURL hook.
1821 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1823 * @see self::getLocalURL for the arguments.
1824 * @return string The URL
1827 public function getCanonicalURL( $query = '', $query2 = false ) {
1828 $query = self
::fixUrlQueryArgs( $query, $query2 );
1829 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1830 Hooks
::run( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1835 * Get the edit URL for this Title
1837 * @return string The URL, or a null string if this is an interwiki link
1839 public function getEditURL() {
1840 if ( $this->isExternal() ) {
1843 $s = $this->getLocalURL( 'action=edit' );
1849 * Is $wgUser watching this page?
1851 * @deprecated since 1.20; use User::isWatched() instead.
1854 public function userIsWatching() {
1857 if ( is_null( $this->mWatched
) ) {
1858 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1859 $this->mWatched
= false;
1861 $this->mWatched
= $wgUser->isWatched( $this );
1864 return $this->mWatched
;
1868 * Can $user perform $action on this page?
1869 * This skips potentially expensive cascading permission checks
1870 * as well as avoids expensive error formatting
1872 * Suitable for use for nonessential UI controls in common cases, but
1873 * _not_ for functional access control.
1875 * May provide false positives, but should never provide a false negative.
1877 * @param string $action Action that permission needs to be checked for
1878 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1881 public function quickUserCan( $action, $user = null ) {
1882 return $this->userCan( $action, $user, false );
1886 * Can $user perform $action on this page?
1888 * @param string $action Action that permission needs to be checked for
1889 * @param User $user User to check (since 1.19); $wgUser will be used if not
1891 * @param bool $doExpensiveQueries Set this to false to avoid doing
1892 * unnecessary queries.
1895 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1896 if ( !$user instanceof User
) {
1901 return !count( $this->getUserPermissionsErrorsInternal(
1902 $action, $user, $doExpensiveQueries, true ) );
1906 * Can $user perform $action on this page?
1908 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1910 * @param string $action Action that permission needs to be checked for
1911 * @param User $user User to check
1912 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1913 * queries by skipping checks for cascading protections and user blocks.
1914 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1915 * whose corresponding errors may be ignored.
1916 * @return array Array of arguments to wfMessage to explain permissions problems.
1918 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1919 $ignoreErrors = array()
1921 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1923 // Remove the errors being ignored.
1924 foreach ( $errors as $index => $error ) {
1925 $error_key = is_array( $error ) ?
$error[0] : $error;
1927 if ( in_array( $error_key, $ignoreErrors ) ) {
1928 unset( $errors[$index] );
1936 * Permissions checks that fail most often, and which are easiest to test.
1938 * @param string $action The action to check
1939 * @param User $user User to check
1940 * @param array $errors List of current errors
1941 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1942 * @param bool $short Short circuit on first error
1944 * @return array List of errors
1946 private function checkQuickPermissions( $action, $user, $errors,
1947 $doExpensiveQueries, $short
1949 if ( !Hooks
::run( 'TitleQuickPermissions',
1950 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1955 if ( $action == 'create' ) {
1957 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1958 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1960 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1962 } elseif ( $action == 'move' ) {
1963 if ( !$user->isAllowed( 'move-rootuserpages' )
1964 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1965 // Show user page-specific message only if the user can move other pages
1966 $errors[] = array( 'cant-move-user-page' );
1969 // Check if user is allowed to move files if it's a file
1970 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1971 $errors[] = array( 'movenotallowedfile' );
1974 // Check if user is allowed to move category pages if it's a category page
1975 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1976 $errors[] = array( 'cant-move-category-page' );
1979 if ( !$user->isAllowed( 'move' ) ) {
1980 // User can't move anything
1981 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1982 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1983 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1984 // custom message if logged-in users without any special rights can move
1985 $errors[] = array( 'movenologintext' );
1987 $errors[] = array( 'movenotallowed' );
1990 } elseif ( $action == 'move-target' ) {
1991 if ( !$user->isAllowed( 'move' ) ) {
1992 // User can't move anything
1993 $errors[] = array( 'movenotallowed' );
1994 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1995 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1996 // Show user page-specific message only if the user can move other pages
1997 $errors[] = array( 'cant-move-to-user-page' );
1998 } elseif ( !$user->isAllowed( 'move-categorypages' )
1999 && $this->mNamespace
== NS_CATEGORY
) {
2000 // Show category page-specific message only if the user can move other pages
2001 $errors[] = array( 'cant-move-to-category-page' );
2003 } elseif ( !$user->isAllowed( $action ) ) {
2004 $errors[] = $this->missingPermissionError( $action, $short );
2011 * Add the resulting error code to the errors array
2013 * @param array $errors List of current errors
2014 * @param array $result Result of errors
2016 * @return array List of errors
2018 private function resultToError( $errors, $result ) {
2019 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2020 // A single array representing an error
2021 $errors[] = $result;
2022 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2023 // A nested array representing multiple errors
2024 $errors = array_merge( $errors, $result );
2025 } elseif ( $result !== '' && is_string( $result ) ) {
2026 // A string representing a message-id
2027 $errors[] = array( $result );
2028 } elseif ( $result === false ) {
2029 // a generic "We don't want them to do that"
2030 $errors[] = array( 'badaccess-group0' );
2036 * Check various permission hooks
2038 * @param string $action The action to check
2039 * @param User $user User to check
2040 * @param array $errors List of current errors
2041 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2042 * @param bool $short Short circuit on first error
2044 * @return array List of errors
2046 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2047 // Use getUserPermissionsErrors instead
2049 if ( !Hooks
::run( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2050 return $result ?
array() : array( array( 'badaccess-group0' ) );
2052 // Check getUserPermissionsErrors hook
2053 if ( !Hooks
::run( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2054 $errors = $this->resultToError( $errors, $result );
2056 // Check getUserPermissionsErrorsExpensive hook
2059 && !( $short && count( $errors ) > 0 )
2060 && !Hooks
::run( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2062 $errors = $this->resultToError( $errors, $result );
2069 * Check permissions on special pages & namespaces
2071 * @param string $action The action to check
2072 * @param User $user User to check
2073 * @param array $errors List of current errors
2074 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2075 * @param bool $short Short circuit on first error
2077 * @return array List of errors
2079 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2080 $doExpensiveQueries, $short
2082 # Only 'createaccount' can be performed on special pages,
2083 # which don't actually exist in the DB.
2084 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2085 $errors[] = array( 'ns-specialprotected' );
2088 # Check $wgNamespaceProtection for restricted namespaces
2089 if ( $this->isNamespaceProtected( $user ) ) {
2090 $ns = $this->mNamespace
== NS_MAIN ?
2091 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2092 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2093 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2100 * Check CSS/JS sub-page permissions
2102 * @param string $action The action to check
2103 * @param User $user User to check
2104 * @param array $errors List of current errors
2105 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2106 * @param bool $short Short circuit on first error
2108 * @return array List of errors
2110 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2111 # Protect css/js subpages of user pages
2112 # XXX: this might be better using restrictions
2113 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2114 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2115 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2116 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2117 $errors[] = array( 'mycustomcssprotected', $action );
2118 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2119 $errors[] = array( 'mycustomjsprotected', $action );
2122 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2123 $errors[] = array( 'customcssprotected', $action );
2124 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2125 $errors[] = array( 'customjsprotected', $action );
2134 * Check against page_restrictions table requirements on this
2135 * page. The user must possess all required rights for this
2138 * @param string $action The action to check
2139 * @param User $user User to check
2140 * @param array $errors List of current errors
2141 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2142 * @param bool $short Short circuit on first error
2144 * @return array List of errors
2146 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2147 foreach ( $this->getRestrictions( $action ) as $right ) {
2148 // Backwards compatibility, rewrite sysop -> editprotected
2149 if ( $right == 'sysop' ) {
2150 $right = 'editprotected';
2152 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2153 if ( $right == 'autoconfirmed' ) {
2154 $right = 'editsemiprotected';
2156 if ( $right == '' ) {
2159 if ( !$user->isAllowed( $right ) ) {
2160 $errors[] = array( 'protectedpagetext', $right, $action );
2161 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2162 $errors[] = array( 'protectedpagetext', 'protect', $action );
2170 * Check restrictions on cascading pages.
2172 * @param string $action The action to check
2173 * @param User $user User to check
2174 * @param array $errors List of current errors
2175 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2176 * @param bool $short Short circuit on first error
2178 * @return array List of errors
2180 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2181 $doExpensiveQueries, $short
2183 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2184 # We /could/ use the protection level on the source page, but it's
2185 # fairly ugly as we have to establish a precedence hierarchy for pages
2186 # included by multiple cascade-protected pages. So just restrict
2187 # it to people with 'protect' permission, as they could remove the
2188 # protection anyway.
2189 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2190 # Cascading protection depends on more than this page...
2191 # Several cascading protected pages may include this page...
2192 # Check each cascading level
2193 # This is only for protection restrictions, not for all actions
2194 if ( isset( $restrictions[$action] ) ) {
2195 foreach ( $restrictions[$action] as $right ) {
2196 // Backwards compatibility, rewrite sysop -> editprotected
2197 if ( $right == 'sysop' ) {
2198 $right = 'editprotected';
2200 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2201 if ( $right == 'autoconfirmed' ) {
2202 $right = 'editsemiprotected';
2204 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2206 foreach ( $cascadingSources as $page ) {
2207 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2209 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2219 * Check action permissions not already checked in checkQuickPermissions
2221 * @param string $action The action to check
2222 * @param User $user User to check
2223 * @param array $errors List of current errors
2224 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2225 * @param bool $short Short circuit on first error
2227 * @return array List of errors
2229 private function checkActionPermissions( $action, $user, $errors,
2230 $doExpensiveQueries, $short
2232 global $wgDeleteRevisionsLimit, $wgLang;
2234 if ( $action == 'protect' ) {
2235 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2236 $user, $doExpensiveQueries, true ) )
2238 // If they can't edit, they shouldn't protect.
2239 $errors[] = array( 'protect-cantedit' );
2241 } elseif ( $action == 'create' ) {
2242 $title_protection = $this->getTitleProtection();
2243 if ( $title_protection ) {
2244 if ( $title_protection['permission'] == ''
2245 ||
!$user->isAllowed( $title_protection['permission'] )
2249 User
::whoIs( $title_protection['user'] ),
2250 $title_protection['reason']
2254 } elseif ( $action == 'move' ) {
2255 // Check for immobile pages
2256 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2257 // Specific message for this case
2258 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2259 } elseif ( !$this->isMovable() ) {
2260 // Less specific message for rarer cases
2261 $errors[] = array( 'immobile-source-page' );
2263 } elseif ( $action == 'move-target' ) {
2264 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2265 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2266 } elseif ( !$this->isMovable() ) {
2267 $errors[] = array( 'immobile-target-page' );
2269 } elseif ( $action == 'delete' ) {
2270 $tempErrors = $this->checkPageRestrictions( 'edit',
2271 $user, array(), $doExpensiveQueries, true );
2272 if ( !$tempErrors ) {
2273 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2274 $user, $tempErrors, $doExpensiveQueries, true );
2276 if ( $tempErrors ) {
2277 // If protection keeps them from editing, they shouldn't be able to delete.
2278 $errors[] = array( 'deleteprotected' );
2280 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2281 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2283 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2290 * Check that the user isn't blocked from editing.
2292 * @param string $action The action to check
2293 * @param User $user User to check
2294 * @param array $errors List of current errors
2295 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2296 * @param bool $short Short circuit on first error
2298 * @return array List of errors
2300 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2301 // Account creation blocks handled at userlogin.
2302 // Unblocking handled in SpecialUnblock
2303 if ( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2307 global $wgEmailConfirmToEdit;
2309 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2310 $errors[] = array( 'confirmedittext' );
2313 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2314 // Don't block the user from editing their own talk page unless they've been
2315 // explicitly blocked from that too.
2316 } elseif ( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2317 // @todo FIXME: Pass the relevant context into this function.
2318 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2325 * Check that the user is allowed to read this page.
2327 * @param string $action The action to check
2328 * @param User $user User to check
2329 * @param array $errors List of current errors
2330 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2331 * @param bool $short Short circuit on first error
2333 * @return array List of errors
2335 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2336 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2338 $whitelisted = false;
2339 if ( User
::isEveryoneAllowed( 'read' ) ) {
2340 # Shortcut for public wikis, allows skipping quite a bit of code
2341 $whitelisted = true;
2342 } elseif ( $user->isAllowed( 'read' ) ) {
2343 # If the user is allowed to read pages, he is allowed to read all pages
2344 $whitelisted = true;
2345 } elseif ( $this->isSpecial( 'Userlogin' )
2346 ||
$this->isSpecial( 'ChangePassword' )
2347 ||
$this->isSpecial( 'PasswordReset' )
2349 # Always grant access to the login page.
2350 # Even anons need to be able to log in.
2351 $whitelisted = true;
2352 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2353 # Time to check the whitelist
2354 # Only do these checks is there's something to check against
2355 $name = $this->getPrefixedText();
2356 $dbName = $this->getPrefixedDBkey();
2358 // Check for explicit whitelisting with and without underscores
2359 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2360 $whitelisted = true;
2361 } elseif ( $this->getNamespace() == NS_MAIN
) {
2362 # Old settings might have the title prefixed with
2363 # a colon for main-namespace pages
2364 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2365 $whitelisted = true;
2367 } elseif ( $this->isSpecialPage() ) {
2368 # If it's a special page, ditch the subpage bit and check again
2369 $name = $this->getDBkey();
2370 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2372 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2373 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2374 $whitelisted = true;
2380 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2381 $name = $this->getPrefixedText();
2382 // Check for regex whitelisting
2383 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2384 if ( preg_match( $listItem, $name ) ) {
2385 $whitelisted = true;
2391 if ( !$whitelisted ) {
2392 # If the title is not whitelisted, give extensions a chance to do so...
2393 Hooks
::run( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2394 if ( !$whitelisted ) {
2395 $errors[] = $this->missingPermissionError( $action, $short );
2403 * Get a description array when the user doesn't have the right to perform
2404 * $action (i.e. when User::isAllowed() returns false)
2406 * @param string $action The action to check
2407 * @param bool $short Short circuit on first error
2408 * @return array List of errors
2410 private function missingPermissionError( $action, $short ) {
2411 // We avoid expensive display logic for quickUserCan's and such
2413 return array( 'badaccess-group0' );
2416 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2417 User
::getGroupsWithPermission( $action ) );
2419 if ( count( $groups ) ) {
2423 $wgLang->commaList( $groups ),
2427 return array( 'badaccess-group0' );
2432 * Can $user perform $action on this page? This is an internal function,
2433 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2434 * checks on wfReadOnly() and blocks)
2436 * @param string $action Action that permission needs to be checked for
2437 * @param User $user User to check
2438 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2439 * @param bool $short Set this to true to stop after the first permission error.
2440 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2442 protected function getUserPermissionsErrorsInternal( $action, $user,
2443 $doExpensiveQueries = true, $short = false
2446 # Read has special handling
2447 if ( $action == 'read' ) {
2449 'checkPermissionHooks',
2450 'checkReadPermissions',
2452 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2453 # here as it will lead to duplicate error messages. This is okay to do
2454 # since anywhere that checks for create will also check for edit, and
2455 # those checks are called for edit.
2456 } elseif ( $action == 'create' ) {
2458 'checkQuickPermissions',
2459 'checkPermissionHooks',
2460 'checkPageRestrictions',
2461 'checkCascadingSourcesRestrictions',
2462 'checkActionPermissions',
2467 'checkQuickPermissions',
2468 'checkPermissionHooks',
2469 'checkSpecialsAndNSPermissions',
2470 'checkCSSandJSPermissions',
2471 'checkPageRestrictions',
2472 'checkCascadingSourcesRestrictions',
2473 'checkActionPermissions',
2479 while ( count( $checks ) > 0 &&
2480 !( $short && count( $errors ) > 0 ) ) {
2481 $method = array_shift( $checks );
2482 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2489 * Get a filtered list of all restriction types supported by this wiki.
2490 * @param bool $exists True to get all restriction types that apply to
2491 * titles that do exist, False for all restriction types that apply to
2492 * titles that do not exist
2495 public static function getFilteredRestrictionTypes( $exists = true ) {
2496 global $wgRestrictionTypes;
2497 $types = $wgRestrictionTypes;
2499 # Remove the create restriction for existing titles
2500 $types = array_diff( $types, array( 'create' ) );
2502 # Only the create and upload restrictions apply to non-existing titles
2503 $types = array_intersect( $types, array( 'create', 'upload' ) );
2509 * Returns restriction types for the current Title
2511 * @return array Applicable restriction types
2513 public function getRestrictionTypes() {
2514 if ( $this->isSpecialPage() ) {
2518 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2520 if ( $this->getNamespace() != NS_FILE
) {
2521 # Remove the upload restriction for non-file titles
2522 $types = array_diff( $types, array( 'upload' ) );
2525 Hooks
::run( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2527 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2528 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2534 * Is this title subject to title protection?
2535 * Title protection is the one applied against creation of such title.
2537 * @return array|bool An associative array representing any existent title
2538 * protection, or false if there's none.
2540 public function getTitleProtection() {
2541 // Can't protect pages in special namespaces
2542 if ( $this->getNamespace() < 0 ) {
2546 // Can't protect pages that exist.
2547 if ( $this->exists() ) {
2551 if ( $this->mTitleProtection
=== null ) {
2552 $dbr = wfGetDB( DB_SLAVE
);
2553 $res = $dbr->select(
2556 'user' => 'pt_user',
2557 'reason' => 'pt_reason',
2558 'expiry' => 'pt_expiry',
2559 'permission' => 'pt_create_perm'
2561 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2565 // fetchRow returns false if there are no rows.
2566 $row = $dbr->fetchRow( $res );
2568 if ( $row['permission'] == 'sysop' ) {
2569 $row['permission'] = 'editprotected'; // B/C
2571 if ( $row['permission'] == 'autoconfirmed' ) {
2572 $row['permission'] = 'editsemiprotected'; // B/C
2575 $this->mTitleProtection
= $row;
2577 return $this->mTitleProtection
;
2581 * Remove any title protection due to page existing
2583 public function deleteTitleProtection() {
2584 $dbw = wfGetDB( DB_MASTER
);
2588 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2591 $this->mTitleProtection
= false;
2595 * Is this page "semi-protected" - the *only* protection levels are listed
2596 * in $wgSemiprotectedRestrictionLevels?
2598 * @param string $action Action to check (default: edit)
2601 public function isSemiProtected( $action = 'edit' ) {
2602 global $wgSemiprotectedRestrictionLevels;
2604 $restrictions = $this->getRestrictions( $action );
2605 $semi = $wgSemiprotectedRestrictionLevels;
2606 if ( !$restrictions ||
!$semi ) {
2607 // Not protected, or all protection is full protection
2611 // Remap autoconfirmed to editsemiprotected for BC
2612 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2613 $semi[$key] = 'editsemiprotected';
2615 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2616 $restrictions[$key] = 'editsemiprotected';
2619 return !array_diff( $restrictions, $semi );
2623 * Does the title correspond to a protected article?
2625 * @param string $action The action the page is protected from,
2626 * by default checks all actions.
2629 public function isProtected( $action = '' ) {
2630 global $wgRestrictionLevels;
2632 $restrictionTypes = $this->getRestrictionTypes();
2634 # Special pages have inherent protection
2635 if ( $this->isSpecialPage() ) {
2639 # Check regular protection levels
2640 foreach ( $restrictionTypes as $type ) {
2641 if ( $action == $type ||
$action == '' ) {
2642 $r = $this->getRestrictions( $type );
2643 foreach ( $wgRestrictionLevels as $level ) {
2644 if ( in_array( $level, $r ) && $level != '' ) {
2655 * Determines if $user is unable to edit this page because it has been protected
2656 * by $wgNamespaceProtection.
2658 * @param User $user User object to check permissions
2661 public function isNamespaceProtected( User
$user ) {
2662 global $wgNamespaceProtection;
2664 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2665 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2666 if ( $right != '' && !$user->isAllowed( $right ) ) {
2675 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2677 * @return bool If the page is subject to cascading restrictions.
2679 public function isCascadeProtected() {
2680 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2681 return ( $sources > 0 );
2685 * Determines whether cascading protection sources have already been loaded from
2688 * @param bool $getPages True to check if the pages are loaded, or false to check
2689 * if the status is loaded.
2690 * @return bool Whether or not the specified information has been loaded
2693 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2694 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2698 * Cascading protection: Get the source of any cascading restrictions on this page.
2700 * @param bool $getPages Whether or not to retrieve the actual pages
2701 * that the restrictions have come from and the actual restrictions
2703 * @return array Two elements: First is an array of Title objects of the
2704 * pages from which cascading restrictions have come, false for
2705 * none, or true if such restrictions exist but $getPages was not
2706 * set. Second is an array like that returned by
2707 * Title::getAllRestrictions(), or an empty array if $getPages is
2710 public function getCascadeProtectionSources( $getPages = true ) {
2712 $pagerestrictions = array();
2714 if ( $this->mCascadeSources
!== null && $getPages ) {
2715 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2716 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2717 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2721 $dbr = wfGetDB( DB_SLAVE
);
2723 if ( $this->getNamespace() == NS_FILE
) {
2724 $tables = array( 'imagelinks', 'page_restrictions' );
2725 $where_clauses = array(
2726 'il_to' => $this->getDBkey(),
2731 $tables = array( 'templatelinks', 'page_restrictions' );
2732 $where_clauses = array(
2733 'tl_namespace' => $this->getNamespace(),
2734 'tl_title' => $this->getDBkey(),
2741 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2742 'pr_expiry', 'pr_type', 'pr_level' );
2743 $where_clauses[] = 'page_id=pr_page';
2746 $cols = array( 'pr_expiry' );
2749 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2751 $sources = $getPages ?
array() : false;
2752 $now = wfTimestampNow();
2753 $purgeExpired = false;
2755 foreach ( $res as $row ) {
2756 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2757 if ( $expiry > $now ) {
2759 $page_id = $row->pr_page
;
2760 $page_ns = $row->page_namespace
;
2761 $page_title = $row->page_title
;
2762 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2763 # Add groups needed for each restriction type if its not already there
2764 # Make sure this restriction type still exists
2766 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2767 $pagerestrictions[$row->pr_type
] = array();
2771 isset( $pagerestrictions[$row->pr_type
] )
2772 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2774 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2780 // Trigger lazy purge of expired restrictions from the db
2781 $purgeExpired = true;
2784 if ( $purgeExpired ) {
2785 Title
::purgeExpiredRestrictions();
2789 $this->mCascadeSources
= $sources;
2790 $this->mCascadingRestrictions
= $pagerestrictions;
2792 $this->mHasCascadingRestrictions
= $sources;
2795 return array( $sources, $pagerestrictions );
2799 * Accessor for mRestrictionsLoaded
2801 * @return bool Whether or not the page's restrictions have already been
2802 * loaded from the database
2805 public function areRestrictionsLoaded() {
2806 return $this->mRestrictionsLoaded
;
2810 * Accessor/initialisation for mRestrictions
2812 * @param string $action Action that permission needs to be checked for
2813 * @return array Restriction levels needed to take the action. All levels are
2814 * required. Note that restriction levels are normally user rights, but 'sysop'
2815 * and 'autoconfirmed' are also allowed for backwards compatibility. These should
2816 * be mapped to 'editprotected' and 'editsemiprotected' respectively.
2818 public function getRestrictions( $action ) {
2819 if ( !$this->mRestrictionsLoaded
) {
2820 $this->loadRestrictions();
2822 return isset( $this->mRestrictions
[$action] )
2823 ?
$this->mRestrictions
[$action]
2828 * Accessor/initialisation for mRestrictions
2830 * @return array Keys are actions, values are arrays as returned by
2831 * Title::getRestrictions()
2834 public function getAllRestrictions() {
2835 if ( !$this->mRestrictionsLoaded
) {
2836 $this->loadRestrictions();
2838 return $this->mRestrictions
;
2842 * Get the expiry time for the restriction against a given action
2844 * @param string $action
2845 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2846 * or not protected at all, or false if the action is not recognised.
2848 public function getRestrictionExpiry( $action ) {
2849 if ( !$this->mRestrictionsLoaded
) {
2850 $this->loadRestrictions();
2852 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2856 * Returns cascading restrictions for the current article
2860 function areRestrictionsCascading() {
2861 if ( !$this->mRestrictionsLoaded
) {
2862 $this->loadRestrictions();
2865 return $this->mCascadeRestriction
;
2869 * Loads a string into mRestrictions array
2871 * @param ResultWrapper $res Resource restrictions as an SQL result.
2872 * @param string $oldFashionedRestrictions Comma-separated list of page
2873 * restrictions from page table (pre 1.10)
2875 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2878 foreach ( $res as $row ) {
2882 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2886 * Compiles list of active page restrictions from both page table (pre 1.10)
2887 * and page_restrictions table for this existing page.
2888 * Public for usage by LiquidThreads.
2890 * @param array $rows Array of db result objects
2891 * @param string $oldFashionedRestrictions Comma-separated list of page
2892 * restrictions from page table (pre 1.10)
2894 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2896 $dbr = wfGetDB( DB_SLAVE
);
2898 $restrictionTypes = $this->getRestrictionTypes();
2900 foreach ( $restrictionTypes as $type ) {
2901 $this->mRestrictions
[$type] = array();
2902 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2905 $this->mCascadeRestriction
= false;
2907 # Backwards-compatibility: also load the restrictions from the page record (old format).
2909 if ( $oldFashionedRestrictions === null ) {
2910 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2911 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2914 if ( $oldFashionedRestrictions != '' ) {
2916 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2917 $temp = explode( '=', trim( $restrict ) );
2918 if ( count( $temp ) == 1 ) {
2919 // old old format should be treated as edit/move restriction
2920 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2921 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2923 $restriction = trim( $temp[1] );
2924 if ( $restriction != '' ) { //some old entries are empty
2925 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2930 $this->mOldRestrictions
= true;
2934 if ( count( $rows ) ) {
2935 # Current system - load second to make them override.
2936 $now = wfTimestampNow();
2937 $purgeExpired = false;
2939 # Cycle through all the restrictions.
2940 foreach ( $rows as $row ) {
2942 // Don't take care of restrictions types that aren't allowed
2943 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2947 // This code should be refactored, now that it's being used more generally,
2948 // But I don't really see any harm in leaving it in Block for now -werdna
2949 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2951 // Only apply the restrictions if they haven't expired!
2952 if ( !$expiry ||
$expiry > $now ) {
2953 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2954 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2956 $this->mCascadeRestriction |
= $row->pr_cascade
;
2958 // Trigger a lazy purge of expired restrictions
2959 $purgeExpired = true;
2963 if ( $purgeExpired ) {
2964 Title
::purgeExpiredRestrictions();
2968 $this->mRestrictionsLoaded
= true;
2972 * Load restrictions from the page_restrictions table
2974 * @param string $oldFashionedRestrictions Comma-separated list of page
2975 * restrictions from page table (pre 1.10)
2977 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2979 if ( !$this->mRestrictionsLoaded
) {
2980 if ( $this->exists() ) {
2981 $dbr = wfGetDB( DB_SLAVE
);
2983 $res = $dbr->select(
2984 'page_restrictions',
2985 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2986 array( 'pr_page' => $this->getArticleID() ),
2990 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2992 $title_protection = $this->getTitleProtection();
2994 if ( $title_protection ) {
2995 $now = wfTimestampNow();
2996 $expiry = $wgContLang->formatExpiry( $title_protection['expiry'], TS_MW
);
2998 if ( !$expiry ||
$expiry > $now ) {
2999 // Apply the restrictions
3000 $this->mRestrictionsExpiry
['create'] = $expiry;
3001 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
3002 } else { // Get rid of the old restrictions
3003 Title
::purgeExpiredRestrictions();
3004 $this->mTitleProtection
= false;
3007 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
3009 $this->mRestrictionsLoaded
= true;
3015 * Flush the protection cache in this object and force reload from the database.
3016 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3018 public function flushRestrictions() {
3019 $this->mRestrictionsLoaded
= false;
3020 $this->mTitleProtection
= null;
3024 * Purge expired restrictions from the page_restrictions table
3026 static function purgeExpiredRestrictions() {
3027 if ( wfReadOnly() ) {
3031 $method = __METHOD__
;
3032 $dbw = wfGetDB( DB_MASTER
);
3033 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3035 'page_restrictions',
3036 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3041 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3048 * Does this have subpages? (Warning, usually requires an extra DB query.)
3052 public function hasSubpages() {
3053 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3058 # We dynamically add a member variable for the purpose of this method
3059 # alone to cache the result. There's no point in having it hanging
3060 # around uninitialized in every Title object; therefore we only add it
3061 # if needed and don't declare it statically.
3062 if ( $this->mHasSubpages
=== null ) {
3063 $this->mHasSubpages
= false;
3064 $subpages = $this->getSubpages( 1 );
3065 if ( $subpages instanceof TitleArray
) {
3066 $this->mHasSubpages
= (bool)$subpages->count();
3070 return $this->mHasSubpages
;
3074 * Get all subpages of this page.
3076 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3077 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3078 * doesn't allow subpages
3080 public function getSubpages( $limit = -1 ) {
3081 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3085 $dbr = wfGetDB( DB_SLAVE
);
3086 $conds['page_namespace'] = $this->getNamespace();
3087 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3089 if ( $limit > -1 ) {
3090 $options['LIMIT'] = $limit;
3092 $this->mSubpages
= TitleArray
::newFromResult(
3093 $dbr->select( 'page',
3094 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3100 return $this->mSubpages
;
3104 * Is there a version of this page in the deletion archive?
3106 * @return int The number of archived revisions
3108 public function isDeleted() {
3109 if ( $this->getNamespace() < 0 ) {
3112 $dbr = wfGetDB( DB_SLAVE
);
3114 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3115 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3118 if ( $this->getNamespace() == NS_FILE
) {
3119 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3120 array( 'fa_name' => $this->getDBkey() ),
3129 * Is there a version of this page in the deletion archive?
3133 public function isDeletedQuick() {
3134 if ( $this->getNamespace() < 0 ) {
3137 $dbr = wfGetDB( DB_SLAVE
);
3138 $deleted = (bool)$dbr->selectField( 'archive', '1',
3139 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3142 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3143 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3144 array( 'fa_name' => $this->getDBkey() ),
3152 * Get the article ID for this Title from the link cache,
3153 * adding it if necessary
3155 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3157 * @return int The ID
3159 public function getArticleID( $flags = 0 ) {
3160 if ( $this->getNamespace() < 0 ) {
3161 $this->mArticleID
= 0;
3162 return $this->mArticleID
;
3164 $linkCache = LinkCache
::singleton();
3165 if ( $flags & self
::GAID_FOR_UPDATE
) {
3166 $oldUpdate = $linkCache->forUpdate( true );
3167 $linkCache->clearLink( $this );
3168 $this->mArticleID
= $linkCache->addLinkObj( $this );
3169 $linkCache->forUpdate( $oldUpdate );
3171 if ( -1 == $this->mArticleID
) {
3172 $this->mArticleID
= $linkCache->addLinkObj( $this );
3175 return $this->mArticleID
;
3179 * Is this an article that is a redirect page?
3180 * Uses link cache, adding it if necessary
3182 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3185 public function isRedirect( $flags = 0 ) {
3186 if ( !is_null( $this->mRedirect
) ) {
3187 return $this->mRedirect
;
3189 # Calling getArticleID() loads the field from cache as needed
3190 if ( !$this->getArticleID( $flags ) ) {
3191 $this->mRedirect
= false;
3192 return $this->mRedirect
;
3195 $linkCache = LinkCache
::singleton();
3196 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3197 if ( $cached === null ) {
3198 # Trust LinkCache's state over our own
3199 # LinkCache is telling us that the page doesn't exist, despite there being cached
3200 # data relating to an existing page in $this->mArticleID. Updaters should clear
3201 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3202 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3203 # LinkCache to refresh its data from the master.
3204 $this->mRedirect
= false;
3205 return $this->mRedirect
;
3208 $this->mRedirect
= (bool)$cached;
3210 return $this->mRedirect
;
3214 * What is the length of this page?
3215 * Uses link cache, adding it if necessary
3217 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3220 public function getLength( $flags = 0 ) {
3221 if ( $this->mLength
!= -1 ) {
3222 return $this->mLength
;
3224 # Calling getArticleID() loads the field from cache as needed
3225 if ( !$this->getArticleID( $flags ) ) {
3227 return $this->mLength
;
3229 $linkCache = LinkCache
::singleton();
3230 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3231 if ( $cached === null ) {
3232 # Trust LinkCache's state over our own, as for isRedirect()
3234 return $this->mLength
;
3237 $this->mLength
= intval( $cached );
3239 return $this->mLength
;
3243 * What is the page_latest field for this page?
3245 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3246 * @return int Int or 0 if the page doesn't exist
3248 public function getLatestRevID( $flags = 0 ) {
3249 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3250 return intval( $this->mLatestID
);
3252 # Calling getArticleID() loads the field from cache as needed
3253 if ( !$this->getArticleID( $flags ) ) {
3254 $this->mLatestID
= 0;
3255 return $this->mLatestID
;
3257 $linkCache = LinkCache
::singleton();
3258 $linkCache->addLinkObj( $this );
3259 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3260 if ( $cached === null ) {
3261 # Trust LinkCache's state over our own, as for isRedirect()
3262 $this->mLatestID
= 0;
3263 return $this->mLatestID
;
3266 $this->mLatestID
= intval( $cached );
3268 return $this->mLatestID
;
3272 * This clears some fields in this object, and clears any associated
3273 * keys in the "bad links" section of the link cache.
3275 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3276 * loading of the new page_id. It's also called from
3277 * WikiPage::doDeleteArticleReal()
3279 * @param int $newid The new Article ID
3281 public function resetArticleID( $newid ) {
3282 $linkCache = LinkCache
::singleton();
3283 $linkCache->clearLink( $this );
3285 if ( $newid === false ) {
3286 $this->mArticleID
= -1;
3288 $this->mArticleID
= intval( $newid );
3290 $this->mRestrictionsLoaded
= false;
3291 $this->mRestrictions
= array();
3292 $this->mRedirect
= null;
3293 $this->mLength
= -1;
3294 $this->mLatestID
= false;
3295 $this->mContentModel
= false;
3296 $this->mEstimateRevisions
= null;
3297 $this->mPageLanguage
= false;
3298 $this->mDbPageLanguage
= null;
3299 $this->mIsBigDeletion
= null;
3303 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3305 * @param string $text Containing title to capitalize
3306 * @param int $ns Namespace index, defaults to NS_MAIN
3307 * @return string Containing capitalized title
3309 public static function capitalize( $text, $ns = NS_MAIN
) {
3312 if ( MWNamespace
::isCapitalized( $ns ) ) {
3313 return $wgContLang->ucfirst( $text );
3320 * Secure and split - main initialisation function for this object
3322 * Assumes that mDbkeyform has been set, and is urldecoded
3323 * and uses underscores, but not otherwise munged. This function
3324 * removes illegal characters, splits off the interwiki and
3325 * namespace prefixes, sets the other forms, and canonicalizes
3328 * @return bool True on success
3330 private function secureAndSplit() {
3332 $this->mInterwiki
= '';
3333 $this->mFragment
= '';
3334 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3336 $dbkey = $this->mDbkeyform
;
3339 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3340 // the parsing code with Title, while avoiding massive refactoring.
3341 // @todo: get rid of secureAndSplit, refactor parsing code.
3342 $titleParser = self
::getTitleParser();
3343 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3344 } catch ( MalformedTitleException
$ex ) {
3349 $this->setFragment( '#' . $parts['fragment'] );
3350 $this->mInterwiki
= $parts['interwiki'];
3351 $this->mLocalInterwiki
= $parts['local_interwiki'];
3352 $this->mNamespace
= $parts['namespace'];
3353 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3355 $this->mDbkeyform
= $parts['dbkey'];
3356 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3357 $this->mTextform
= str_replace( '_', ' ', $this->mDbkeyform
);
3359 # We already know that some pages won't be in the database!
3360 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3361 $this->mArticleID
= 0;
3368 * Get an array of Title objects linking to this Title
3369 * Also stores the IDs in the link cache.
3371 * WARNING: do not use this function on arbitrary user-supplied titles!
3372 * On heavily-used templates it will max out the memory.
3374 * @param array $options May be FOR UPDATE
3375 * @param string $table Table name
3376 * @param string $prefix Fields prefix
3377 * @return Title[] Array of Title objects linking here
3379 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3380 if ( count( $options ) > 0 ) {
3381 $db = wfGetDB( DB_MASTER
);
3383 $db = wfGetDB( DB_SLAVE
);
3387 array( 'page', $table ),
3388 self
::getSelectFields(),
3390 "{$prefix}_from=page_id",
3391 "{$prefix}_namespace" => $this->getNamespace(),
3392 "{$prefix}_title" => $this->getDBkey() ),
3398 if ( $res->numRows() ) {
3399 $linkCache = LinkCache
::singleton();
3400 foreach ( $res as $row ) {
3401 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3403 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3404 $retVal[] = $titleObj;
3412 * Get an array of Title objects using this Title as a template
3413 * Also stores the IDs in the link cache.
3415 * WARNING: do not use this function on arbitrary user-supplied titles!
3416 * On heavily-used templates it will max out the memory.
3418 * @param array $options May be FOR UPDATE
3419 * @return Title[] Array of Title the Title objects linking here
3421 public function getTemplateLinksTo( $options = array() ) {
3422 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3426 * Get an array of Title objects linked from this Title
3427 * Also stores the IDs in the link cache.
3429 * WARNING: do not use this function on arbitrary user-supplied titles!
3430 * On heavily-used templates it will max out the memory.
3432 * @param array $options May be FOR UPDATE
3433 * @param string $table Table name
3434 * @param string $prefix Fields prefix
3435 * @return array Array of Title objects linking here
3437 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3438 global $wgContentHandlerUseDB;
3440 $id = $this->getArticleID();
3442 # If the page doesn't exist; there can't be any link from this page
3447 if ( count( $options ) > 0 ) {
3448 $db = wfGetDB( DB_MASTER
);
3450 $db = wfGetDB( DB_SLAVE
);
3453 $namespaceFiled = "{$prefix}_namespace";
3454 $titleField = "{$prefix}_title";
3465 if ( $wgContentHandlerUseDB ) {
3466 $fields[] = 'page_content_model';
3470 array( $table, 'page' ),
3472 array( "{$prefix}_from" => $id ),
3475 array( 'page' => array(
3477 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3482 if ( $res->numRows() ) {
3483 $linkCache = LinkCache
::singleton();
3484 foreach ( $res as $row ) {
3485 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3487 if ( $row->page_id
) {
3488 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3490 $linkCache->addBadLinkObj( $titleObj );
3492 $retVal[] = $titleObj;
3500 * Get an array of Title objects used on this Title as a template
3501 * Also stores the IDs in the link cache.
3503 * WARNING: do not use this function on arbitrary user-supplied titles!
3504 * On heavily-used templates it will max out the memory.
3506 * @param array $options May be FOR UPDATE
3507 * @return Title[] Array of Title the Title objects used here
3509 public function getTemplateLinksFrom( $options = array() ) {
3510 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3514 * Get an array of Title objects referring to non-existent articles linked
3517 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3518 * should use redirect table in this case).
3519 * @return Title[] Array of Title the Title objects
3521 public function getBrokenLinksFrom() {
3522 if ( $this->getArticleID() == 0 ) {
3523 # All links from article ID 0 are false positives
3527 $dbr = wfGetDB( DB_SLAVE
);
3528 $res = $dbr->select(
3529 array( 'page', 'pagelinks' ),
3530 array( 'pl_namespace', 'pl_title' ),
3532 'pl_from' => $this->getArticleID(),
3533 'page_namespace IS NULL'
3535 __METHOD__
, array(),
3539 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3545 foreach ( $res as $row ) {
3546 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3552 * Get a list of URLs to purge from the Squid cache when this
3555 * @return string[] Array of String the URLs
3557 public function getSquidURLs() {
3559 $this->getInternalURL(),
3560 $this->getInternalURL( 'action=history' )
3563 $pageLang = $this->getPageLanguage();
3564 if ( $pageLang->hasVariants() ) {
3565 $variants = $pageLang->getVariants();
3566 foreach ( $variants as $vCode ) {
3567 $urls[] = $this->getInternalURL( '', $vCode );
3571 // If we are looking at a css/js user subpage, purge the action=raw.
3572 if ( $this->isJsSubpage() ) {
3573 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3574 } elseif ( $this->isCssSubpage() ) {
3575 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3578 Hooks
::run( 'TitleSquidURLs', array( $this, &$urls ) );
3583 * Purge all applicable Squid URLs
3585 public function purgeSquid() {
3587 if ( $wgUseSquid ) {
3588 $urls = $this->getSquidURLs();
3589 $u = new SquidUpdate( $urls );
3595 * Move this page without authentication
3597 * @deprecated since 1.25 use MovePage class instead
3598 * @param Title $nt The new page Title
3599 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3601 public function moveNoAuth( &$nt ) {
3602 wfDeprecated( __METHOD__
, '1.25' );
3603 return $this->moveTo( $nt, false );
3607 * Check whether a given move operation would be valid.
3608 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3610 * @deprecated since 1.25, use MovePage's methods instead
3611 * @param Title $nt The new title
3612 * @param bool $auth Ignored
3613 * @param string $reason Is the log summary of the move, used for spam checking
3614 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3616 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3619 if ( !( $nt instanceof Title
) ) {
3620 // Normally we'd add this to $errors, but we'll get
3621 // lots of syntax errors if $nt is not an object
3622 return array( array( 'badtitletext' ) );
3625 $mp = new MovePage( $this, $nt );
3626 $errors = wfMergeErrorArrays(
3627 $mp->isValidMove()->getErrorsArray(),
3628 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3631 return $errors ?
: true;
3635 * Check if the requested move target is a valid file move target
3636 * @todo move this to MovePage
3637 * @param Title $nt Target title
3638 * @return array List of errors
3640 protected function validateFileMoveOperation( $nt ) {
3645 $destFile = wfLocalFile( $nt );
3646 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3647 $errors[] = array( 'file-exists-sharedrepo' );
3654 * Move a title to a new location
3656 * @deprecated since 1.25, use the MovePage class instead
3657 * @param Title $nt The new title
3658 * @param bool $auth Indicates whether $wgUser's permissions
3660 * @param string $reason The reason for the move
3661 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3662 * Ignored if the user doesn't have the suppressredirect right.
3663 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3665 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3667 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3668 if ( is_array( $err ) ) {
3669 // Auto-block user's IP if the account was "hard" blocked
3670 $wgUser->spreadAnyEditBlock();
3673 // Check suppressredirect permission
3674 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3675 $createRedirect = true;
3678 $mp = new MovePage( $this, $nt );
3679 $status = $mp->move( $wgUser, $reason, $createRedirect );
3680 if ( $status->isOK() ) {
3683 return $status->getErrorsArray();
3688 * Move this page's subpages to be subpages of $nt
3690 * @param Title $nt Move target
3691 * @param bool $auth Whether $wgUser's permissions should be checked
3692 * @param string $reason The reason for the move
3693 * @param bool $createRedirect Whether to create redirects from the old subpages to
3694 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3695 * @return array Array with old page titles as keys, and strings (new page titles) or
3696 * arrays (errors) as values, or an error array with numeric indices if no pages
3699 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3700 global $wgMaximumMovedPages;
3701 // Check permissions
3702 if ( !$this->userCan( 'move-subpages' ) ) {
3703 return array( 'cant-move-subpages' );
3705 // Do the source and target namespaces support subpages?
3706 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3707 return array( 'namespace-nosubpages',
3708 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3710 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3711 return array( 'namespace-nosubpages',
3712 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3715 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3718 foreach ( $subpages as $oldSubpage ) {
3720 if ( $count > $wgMaximumMovedPages ) {
3721 $retval[$oldSubpage->getPrefixedText()] =
3722 array( 'movepage-max-pages',
3723 $wgMaximumMovedPages );
3727 // We don't know whether this function was called before
3728 // or after moving the root page, so check both
3730 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3731 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3733 // When moving a page to a subpage of itself,
3734 // don't move it twice
3737 $newPageName = preg_replace(
3738 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3739 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3740 $oldSubpage->getDBkey() );
3741 if ( $oldSubpage->isTalkPage() ) {
3742 $newNs = $nt->getTalkPage()->getNamespace();
3744 $newNs = $nt->getSubjectPage()->getNamespace();
3746 # Bug 14385: we need makeTitleSafe because the new page names may
3747 # be longer than 255 characters.
3748 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3750 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3751 if ( $success === true ) {
3752 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3754 $retval[$oldSubpage->getPrefixedText()] = $success;
3761 * Checks if this page is just a one-rev redirect.
3762 * Adds lock, so don't use just for light purposes.
3766 public function isSingleRevRedirect() {
3767 global $wgContentHandlerUseDB;
3769 $dbw = wfGetDB( DB_MASTER
);
3772 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3773 if ( $wgContentHandlerUseDB ) {
3774 $fields[] = 'page_content_model';
3777 $row = $dbw->selectRow( 'page',
3781 array( 'FOR UPDATE' )
3783 # Cache some fields we may want
3784 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3785 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3786 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3787 $this->mContentModel
= $row && isset( $row->page_content_model
)
3788 ?
strval( $row->page_content_model
)
3791 if ( !$this->mRedirect
) {
3794 # Does the article have a history?
3795 $row = $dbw->selectField( array( 'page', 'revision' ),
3797 array( 'page_namespace' => $this->getNamespace(),
3798 'page_title' => $this->getDBkey(),
3800 'page_latest != rev_id'
3803 array( 'FOR UPDATE' )
3805 # Return true if there was no history
3806 return ( $row === false );
3810 * Checks if $this can be moved to a given Title
3811 * - Selects for update, so don't call it unless you mean business
3813 * @deprecated since 1.25, use MovePage's methods instead
3814 * @param Title $nt The new title to check
3817 public function isValidMoveTarget( $nt ) {
3818 # Is it an existing file?
3819 if ( $nt->getNamespace() == NS_FILE
) {
3820 $file = wfLocalFile( $nt );
3821 if ( $file->exists() ) {
3822 wfDebug( __METHOD__
. ": file exists\n" );
3826 # Is it a redirect with no history?
3827 if ( !$nt->isSingleRevRedirect() ) {
3828 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3831 # Get the article text
3832 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3833 if ( !is_object( $rev ) ) {
3836 $content = $rev->getContent();
3837 # Does the redirect point to the source?
3838 # Or is it a broken self-redirect, usually caused by namespace collisions?
3839 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3841 if ( $redirTitle ) {
3842 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3843 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3844 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3850 # Fail safe (not a redirect after all. strange.)
3851 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3852 " is a redirect, but it doesn't contain a valid redirect.\n" );
3858 * Get categories to which this Title belongs and return an array of
3859 * categories' names.
3861 * @return array Array of parents in the form:
3862 * $parent => $currentarticle
3864 public function getParentCategories() {
3869 $titleKey = $this->getArticleID();
3871 if ( $titleKey === 0 ) {
3875 $dbr = wfGetDB( DB_SLAVE
);
3877 $res = $dbr->select(
3880 array( 'cl_from' => $titleKey ),
3884 if ( $res->numRows() > 0 ) {
3885 foreach ( $res as $row ) {
3886 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3887 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3894 * Get a tree of parent categories
3896 * @param array $children Array with the children in the keys, to check for circular refs
3897 * @return array Tree of parent categories
3899 public function getParentCategoryTree( $children = array() ) {
3901 $parents = $this->getParentCategories();
3904 foreach ( $parents as $parent => $current ) {
3905 if ( array_key_exists( $parent, $children ) ) {
3906 # Circular reference
3907 $stack[$parent] = array();
3909 $nt = Title
::newFromText( $parent );
3911 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3921 * Get an associative array for selecting this title from
3924 * @return array Array suitable for the $where parameter of DB::select()
3926 public function pageCond() {
3927 if ( $this->mArticleID
> 0 ) {
3928 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3929 return array( 'page_id' => $this->mArticleID
);
3931 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3936 * Get the revision ID of the previous revision
3938 * @param int $revId Revision ID. Get the revision that was before this one.
3939 * @param int $flags Title::GAID_FOR_UPDATE
3940 * @return int|bool Old revision ID, or false if none exists
3942 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3943 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3944 $revId = $db->selectField( 'revision', 'rev_id',
3946 'rev_page' => $this->getArticleID( $flags ),
3947 'rev_id < ' . intval( $revId )
3950 array( 'ORDER BY' => 'rev_id DESC' )
3953 if ( $revId === false ) {
3956 return intval( $revId );
3961 * Get the revision ID of the next revision
3963 * @param int $revId Revision ID. Get the revision that was after this one.
3964 * @param int $flags Title::GAID_FOR_UPDATE
3965 * @return int|bool Next revision ID, or false if none exists
3967 public function getNextRevisionID( $revId, $flags = 0 ) {
3968 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3969 $revId = $db->selectField( 'revision', 'rev_id',
3971 'rev_page' => $this->getArticleID( $flags ),
3972 'rev_id > ' . intval( $revId )
3975 array( 'ORDER BY' => 'rev_id' )
3978 if ( $revId === false ) {
3981 return intval( $revId );
3986 * Get the first revision of the page
3988 * @param int $flags Title::GAID_FOR_UPDATE
3989 * @return Revision|null If page doesn't exist
3991 public function getFirstRevision( $flags = 0 ) {
3992 $pageId = $this->getArticleID( $flags );
3994 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3995 $row = $db->selectRow( 'revision', Revision
::selectFields(),
3996 array( 'rev_page' => $pageId ),
3998 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4001 return new Revision( $row );
4008 * Get the oldest revision timestamp of this page
4010 * @param int $flags Title::GAID_FOR_UPDATE
4011 * @return string MW timestamp
4013 public function getEarliestRevTime( $flags = 0 ) {
4014 $rev = $this->getFirstRevision( $flags );
4015 return $rev ?
$rev->getTimestamp() : null;
4019 * Check if this is a new page
4023 public function isNewPage() {
4024 $dbr = wfGetDB( DB_SLAVE
);
4025 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4029 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4033 public function isBigDeletion() {
4034 global $wgDeleteRevisionsLimit;
4036 if ( !$wgDeleteRevisionsLimit ) {
4040 if ( $this->mIsBigDeletion
=== null ) {
4041 $dbr = wfGetDB( DB_SLAVE
);
4043 $revCount = $dbr->selectRowCount(
4046 array( 'rev_page' => $this->getArticleID() ),
4048 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4051 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4054 return $this->mIsBigDeletion
;
4058 * Get the approximate revision count of this page.
4062 public function estimateRevisionCount() {
4063 if ( !$this->exists() ) {
4067 if ( $this->mEstimateRevisions
=== null ) {
4068 $dbr = wfGetDB( DB_SLAVE
);
4069 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4070 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4073 return $this->mEstimateRevisions
;
4077 * Get the number of revisions between the given revision.
4078 * Used for diffs and other things that really need it.
4080 * @param int|Revision $old Old revision or rev ID (first before range)
4081 * @param int|Revision $new New revision or rev ID (first after range)
4082 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4083 * @return int Number of revisions between these revisions.
4085 public function countRevisionsBetween( $old, $new, $max = null ) {
4086 if ( !( $old instanceof Revision
) ) {
4087 $old = Revision
::newFromTitle( $this, (int)$old );
4089 if ( !( $new instanceof Revision
) ) {
4090 $new = Revision
::newFromTitle( $this, (int)$new );
4092 if ( !$old ||
!$new ) {
4093 return 0; // nothing to compare
4095 $dbr = wfGetDB( DB_SLAVE
);
4097 'rev_page' => $this->getArticleID(),
4098 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4099 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4101 if ( $max !== null ) {
4102 $res = $dbr->select( 'revision', '1',
4105 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4107 return $res->numRows();
4109 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4114 * Get the authors between the given revisions or revision IDs.
4115 * Used for diffs and other things that really need it.
4119 * @param int|Revision $old Old revision or rev ID (first before range by default)
4120 * @param int|Revision $new New revision or rev ID (first after range by default)
4121 * @param int $limit Maximum number of authors
4122 * @param string|array $options (Optional): Single option, or an array of options:
4123 * 'include_old' Include $old in the range; $new is excluded.
4124 * 'include_new' Include $new in the range; $old is excluded.
4125 * 'include_both' Include both $old and $new in the range.
4126 * Unknown option values are ignored.
4127 * @return array|null Names of revision authors in the range; null if not both revisions exist
4129 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4130 if ( !( $old instanceof Revision
) ) {
4131 $old = Revision
::newFromTitle( $this, (int)$old );
4133 if ( !( $new instanceof Revision
) ) {
4134 $new = Revision
::newFromTitle( $this, (int)$new );
4136 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4137 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4138 // in the sanity check below?
4139 if ( !$old ||
!$new ) {
4140 return null; // nothing to compare
4145 $options = (array)$options;
4146 if ( in_array( 'include_old', $options ) ) {
4149 if ( in_array( 'include_new', $options ) ) {
4152 if ( in_array( 'include_both', $options ) ) {
4156 // No DB query needed if $old and $new are the same or successive revisions:
4157 if ( $old->getId() === $new->getId() ) {
4158 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
array() : array( $old->getRawUserText() );
4159 } elseif ( $old->getId() === $new->getParentId() ) {
4160 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4161 $authors[] = $old->getRawUserText();
4162 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4163 $authors[] = $new->getRawUserText();
4165 } elseif ( $old_cmp === '>=' ) {
4166 $authors[] = $old->getRawUserText();
4167 } elseif ( $new_cmp === '<=' ) {
4168 $authors[] = $new->getRawUserText();
4172 $dbr = wfGetDB( DB_SLAVE
);
4173 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4175 'rev_page' => $this->getArticleID(),
4176 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4177 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4179 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4181 foreach ( $res as $row ) {
4182 $authors[] = $row->rev_user_text
;
4188 * Get the number of authors between the given revisions or revision IDs.
4189 * Used for diffs and other things that really need it.
4191 * @param int|Revision $old Old revision or rev ID (first before range by default)
4192 * @param int|Revision $new New revision or rev ID (first after range by default)
4193 * @param int $limit Maximum number of authors
4194 * @param string|array $options (Optional): Single option, or an array of options:
4195 * 'include_old' Include $old in the range; $new is excluded.
4196 * 'include_new' Include $new in the range; $old is excluded.
4197 * 'include_both' Include both $old and $new in the range.
4198 * Unknown option values are ignored.
4199 * @return int Number of revision authors in the range; zero if not both revisions exist
4201 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4202 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4203 return $authors ?
count( $authors ) : 0;
4207 * Compare with another title.
4209 * @param Title $title
4212 public function equals( Title
$title ) {
4213 // Note: === is necessary for proper matching of number-like titles.
4214 return $this->getInterwiki() === $title->getInterwiki()
4215 && $this->getNamespace() == $title->getNamespace()
4216 && $this->getDBkey() === $title->getDBkey();
4220 * Check if this title is a subpage of another title
4222 * @param Title $title
4225 public function isSubpageOf( Title
$title ) {
4226 return $this->getInterwiki() === $title->getInterwiki()
4227 && $this->getNamespace() == $title->getNamespace()
4228 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4232 * Check if page exists. For historical reasons, this function simply
4233 * checks for the existence of the title in the page table, and will
4234 * thus return false for interwiki links, special pages and the like.
4235 * If you want to know if a title can be meaningfully viewed, you should
4236 * probably call the isKnown() method instead.
4240 public function exists() {
4241 $exists = $this->getArticleID() != 0;
4242 Hooks
::run( 'TitleExists', array( $this, &$exists ) );
4247 * Should links to this title be shown as potentially viewable (i.e. as
4248 * "bluelinks"), even if there's no record by this title in the page
4251 * This function is semi-deprecated for public use, as well as somewhat
4252 * misleadingly named. You probably just want to call isKnown(), which
4253 * calls this function internally.
4255 * (ISSUE: Most of these checks are cheap, but the file existence check
4256 * can potentially be quite expensive. Including it here fixes a lot of
4257 * existing code, but we might want to add an optional parameter to skip
4258 * it and any other expensive checks.)
4262 public function isAlwaysKnown() {
4266 * Allows overriding default behavior for determining if a page exists.
4267 * If $isKnown is kept as null, regular checks happen. If it's
4268 * a boolean, this value is returned by the isKnown method.
4272 * @param Title $title
4273 * @param bool|null $isKnown
4275 Hooks
::run( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4277 if ( !is_null( $isKnown ) ) {
4281 if ( $this->isExternal() ) {
4282 return true; // any interwiki link might be viewable, for all we know
4285 switch ( $this->mNamespace
) {
4288 // file exists, possibly in a foreign repo
4289 return (bool)wfFindFile( $this );
4291 // valid special page
4292 return SpecialPageFactory
::exists( $this->getDBkey() );
4294 // selflink, possibly with fragment
4295 return $this->mDbkeyform
== '';
4297 // known system message
4298 return $this->hasSourceText() !== false;
4305 * Does this title refer to a page that can (or might) be meaningfully
4306 * viewed? In particular, this function may be used to determine if
4307 * links to the title should be rendered as "bluelinks" (as opposed to
4308 * "redlinks" to non-existent pages).
4309 * Adding something else to this function will cause inconsistency
4310 * since LinkHolderArray calls isAlwaysKnown() and does its own
4311 * page existence check.
4315 public function isKnown() {
4316 return $this->isAlwaysKnown() ||
$this->exists();
4320 * Does this page have source text?
4324 public function hasSourceText() {
4325 if ( $this->exists() ) {
4329 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4330 // If the page doesn't exist but is a known system message, default
4331 // message content will be displayed, same for language subpages-
4332 // Use always content language to avoid loading hundreds of languages
4333 // to get the link color.
4335 list( $name, ) = MessageCache
::singleton()->figureMessage(
4336 $wgContLang->lcfirst( $this->getText() )
4338 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4339 return $message->exists();
4346 * Get the default message text or false if the message doesn't exist
4348 * @return string|bool
4350 public function getDefaultMessageText() {
4353 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4357 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4358 $wgContLang->lcfirst( $this->getText() )
4360 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4362 if ( $message->exists() ) {
4363 return $message->plain();
4370 * Updates page_touched for this page; called from LinksUpdate.php
4372 * @return bool True if the update succeeded
4374 public function invalidateCache() {
4375 if ( wfReadOnly() ) {
4379 if ( $this->mArticleID
=== 0 ) {
4380 return true; // avoid gap locking if we know it's not there
4383 $method = __METHOD__
;
4384 $dbw = wfGetDB( DB_MASTER
);
4385 $conds = $this->pageCond();
4386 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4389 array( 'page_touched' => $dbw->timestamp() ),
4399 * Update page_touched timestamps and send squid purge messages for
4400 * pages linking to this title. May be sent to the job queue depending
4401 * on the number of links. Typically called on create and delete.
4403 public function touchLinks() {
4404 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4407 if ( $this->getNamespace() == NS_CATEGORY
) {
4408 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4414 * Get the last touched timestamp
4416 * @param DatabaseBase $db Optional db
4417 * @return string Last-touched timestamp
4419 public function getTouched( $db = null ) {
4420 if ( $db === null ) {
4421 $db = wfGetDB( DB_SLAVE
);
4423 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4428 * Get the timestamp when this page was updated since the user last saw it.
4431 * @return string|null
4433 public function getNotificationTimestamp( $user = null ) {
4434 global $wgUser, $wgShowUpdatedMarker;
4435 // Assume current user if none given
4439 // Check cache first
4440 $uid = $user->getId();
4441 // avoid isset here, as it'll return false for null entries
4442 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4443 return $this->mNotificationTimestamp
[$uid];
4445 if ( !$uid ||
!$wgShowUpdatedMarker ||
!$user->isAllowed( 'viewmywatchlist' ) ) {
4446 $this->mNotificationTimestamp
[$uid] = false;
4447 return $this->mNotificationTimestamp
[$uid];
4449 // Don't cache too much!
4450 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4451 $this->mNotificationTimestamp
= array();
4453 $dbr = wfGetDB( DB_SLAVE
);
4454 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4455 'wl_notificationtimestamp',
4457 'wl_user' => $user->getId(),
4458 'wl_namespace' => $this->getNamespace(),
4459 'wl_title' => $this->getDBkey(),
4463 return $this->mNotificationTimestamp
[$uid];
4467 * Generate strings used for xml 'id' names in monobook tabs
4469 * @param string $prepend Defaults to 'nstab-'
4470 * @return string XML 'id' name
4472 public function getNamespaceKey( $prepend = 'nstab-' ) {
4474 // Gets the subject namespace if this title
4475 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4476 // Checks if canonical namespace name exists for namespace
4477 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4478 // Uses canonical namespace name
4479 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4481 // Uses text of namespace
4482 $namespaceKey = $this->getSubjectNsText();
4484 // Makes namespace key lowercase
4485 $namespaceKey = $wgContLang->lc( $namespaceKey );
4487 if ( $namespaceKey == '' ) {
4488 $namespaceKey = 'main';
4490 // Changes file to image for backwards compatibility
4491 if ( $namespaceKey == 'file' ) {
4492 $namespaceKey = 'image';
4494 return $prepend . $namespaceKey;
4498 * Get all extant redirects to this Title
4500 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4501 * @return Title[] Array of Title redirects to this title
4503 public function getRedirectsHere( $ns = null ) {
4506 $dbr = wfGetDB( DB_SLAVE
);
4508 'rd_namespace' => $this->getNamespace(),
4509 'rd_title' => $this->getDBkey(),
4512 if ( $this->isExternal() ) {
4513 $where['rd_interwiki'] = $this->getInterwiki();
4515 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4517 if ( !is_null( $ns ) ) {
4518 $where['page_namespace'] = $ns;
4521 $res = $dbr->select(
4522 array( 'redirect', 'page' ),
4523 array( 'page_namespace', 'page_title' ),
4528 foreach ( $res as $row ) {
4529 $redirs[] = self
::newFromRow( $row );
4535 * Check if this Title is a valid redirect target
4539 public function isValidRedirectTarget() {
4540 global $wgInvalidRedirectTargets;
4542 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4543 if ( $this->isSpecial( 'Userlogout' ) ) {
4547 foreach ( $wgInvalidRedirectTargets as $target ) {
4548 if ( $this->isSpecial( $target ) ) {
4557 * Get a backlink cache object
4559 * @return BacklinkCache
4561 public function getBacklinkCache() {
4562 return BacklinkCache
::get( $this );
4566 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4570 public function canUseNoindex() {
4571 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4573 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4574 ?
$wgContentNamespaces
4575 : $wgExemptFromUserRobotsControl;
4577 return !in_array( $this->mNamespace
, $bannedNamespaces );
4582 * Returns the raw sort key to be used for categories, with the specified
4583 * prefix. This will be fed to Collation::getSortKey() to get a
4584 * binary sortkey that can be used for actual sorting.
4586 * @param string $prefix The prefix to be used, specified using
4587 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4591 public function getCategorySortkey( $prefix = '' ) {
4592 $unprefixed = $this->getText();
4594 // Anything that uses this hook should only depend
4595 // on the Title object passed in, and should probably
4596 // tell the users to run updateCollations.php --force
4597 // in order to re-sort existing category relations.
4598 Hooks
::run( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4599 if ( $prefix !== '' ) {
4600 # Separate with a line feed, so the unprefixed part is only used as
4601 # a tiebreaker when two pages have the exact same prefix.
4602 # In UCA, tab is the only character that can sort above LF
4603 # so we strip both of them from the original prefix.
4604 $prefix = strtr( $prefix, "\n\t", ' ' );
4605 return "$prefix\n$unprefixed";
4611 * Get the language in which the content of this page is written in
4612 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4613 * e.g. $wgLang (such as special pages, which are in the user language).
4618 public function getPageLanguage() {
4619 global $wgLang, $wgLanguageCode;
4620 if ( $this->isSpecialPage() ) {
4621 // special pages are in the user language
4625 // Checking if DB language is set
4626 if ( $this->mDbPageLanguage
) {
4627 return wfGetLangObj( $this->mDbPageLanguage
);
4630 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4631 // Note that this may depend on user settings, so the cache should
4632 // be only per-request.
4633 // NOTE: ContentHandler::getPageLanguage() may need to load the
4634 // content to determine the page language!
4635 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4637 $contentHandler = ContentHandler
::getForTitle( $this );
4638 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4639 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4641 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4648 * Get the language in which the content of this page is written when
4649 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4650 * e.g. $wgLang (such as special pages, which are in the user language).
4655 public function getPageViewLanguage() {
4658 if ( $this->isSpecialPage() ) {
4659 // If the user chooses a variant, the content is actually
4660 // in a language whose code is the variant code.
4661 $variant = $wgLang->getPreferredVariant();
4662 if ( $wgLang->getCode() !== $variant ) {
4663 return Language
::factory( $variant );
4669 // @note Can't be cached persistently, depends on user settings.
4670 // @note ContentHandler::getPageViewLanguage() may need to load the
4671 // content to determine the page language!
4672 $contentHandler = ContentHandler
::getForTitle( $this );
4673 $pageLang = $contentHandler->getPageViewLanguage( $this );
4678 * Get a list of rendered edit notices for this page.
4680 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4681 * they will already be wrapped in paragraphs.
4684 * @param int $oldid Revision ID that's being edited
4687 public function getEditNotices( $oldid = 0 ) {
4690 # Optional notices on a per-namespace and per-page basis
4691 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4692 $editnotice_ns_message = wfMessage( $editnotice_ns );
4693 if ( $editnotice_ns_message->exists() ) {
4694 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4696 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4697 $parts = explode( '/', $this->getDBkey() );
4698 $editnotice_base = $editnotice_ns;
4699 while ( count( $parts ) > 0 ) {
4700 $editnotice_base .= '-' . array_shift( $parts );
4701 $editnotice_base_msg = wfMessage( $editnotice_base );
4702 if ( $editnotice_base_msg->exists() ) {
4703 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4707 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4708 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4709 $editnoticeMsg = wfMessage( $editnoticeText );
4710 if ( $editnoticeMsg->exists() ) {
4711 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4715 Hooks
::run( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );