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 * @todo move this into MediaWikiTitleCodec
619 * @return string Regex string
621 static function getTitleInvalidRegex() {
622 static $rxTc = false;
624 # Matching titles will be held as illegal.
626 # Any character not allowed is forbidden...
627 '[^' . self
::legalChars() . ']' .
628 # URL percent encoding sequences interfere with the ability
629 # to round-trip titles -- you can't link to them consistently.
631 # XML/HTML character references produce similar issues.
632 '|&[A-Za-z0-9\x80-\xff]+;' .
634 '|&#x[0-9A-Fa-f]+;' .
642 * Utility method for converting a character sequence from bytes to Unicode.
644 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
645 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
647 * @param string $byteClass
650 public static function convertByteClassToUnicodeClass( $byteClass ) {
651 $length = strlen( $byteClass );
653 $x0 = $x1 = $x2 = '';
655 $d0 = $d1 = $d2 = '';
656 // Decoded integer codepoints
657 $ord0 = $ord1 = $ord2 = 0;
659 $r0 = $r1 = $r2 = '';
663 $allowUnicode = false;
664 for ( $pos = 0; $pos < $length; $pos++
) {
665 // Shift the queues down
674 // Load the current input token and decoded values
675 $inChar = $byteClass[$pos];
676 if ( $inChar == '\\' ) {
677 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos +
1 ) ) {
678 $x0 = $inChar . $m[0];
679 $d0 = chr( hexdec( $m[1] ) );
680 $pos +
= strlen( $m[0] );
681 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos +
1 ) ) {
682 $x0 = $inChar . $m[0];
683 $d0 = chr( octdec( $m[0] ) );
684 $pos +
= strlen( $m[0] );
685 } elseif ( $pos +
1 >= $length ) {
688 $d0 = $byteClass[$pos +
1];
696 // Load the current re-encoded value
697 if ( $ord0 < 32 ||
$ord0 == 0x7f ) {
698 $r0 = sprintf( '\x%02x', $ord0 );
699 } elseif ( $ord0 >= 0x80 ) {
700 // Allow unicode if a single high-bit character appears
701 $r0 = sprintf( '\x%02x', $ord0 );
702 $allowUnicode = true;
703 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
709 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
711 if ( $ord2 > $ord0 ) {
713 } elseif ( $ord0 >= 0x80 ) {
715 $allowUnicode = true;
716 if ( $ord2 < 0x80 ) {
717 // Keep the non-unicode section of the range
724 // Reset state to the initial value
725 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
726 } elseif ( $ord2 < 0x80 ) {
731 if ( $ord1 < 0x80 ) {
734 if ( $ord0 < 0x80 ) {
737 if ( $allowUnicode ) {
738 $out .= '\u0080-\uFFFF';
744 * Make a prefixed DB key from a DB key and a namespace index
746 * @param int $ns Numerical representation of the namespace
747 * @param string $title The DB key form the title
748 * @param string $fragment The link fragment (after the "#")
749 * @param string $interwiki The interwiki prefix
750 * @param boolean $canoncialNamespace If true, use the canonical name for
751 * $ns instead of the localized version.
752 * @return string The prefixed form of the title
754 public static function makeName( $ns, $title, $fragment = '', $interwiki = '',
755 $canoncialNamespace = false
759 if ( $canoncialNamespace ) {
760 $namespace = MWNamespace
::getCanonicalName( $ns );
762 $namespace = $wgContLang->getNsText( $ns );
764 $name = $namespace == '' ?
$title : "$namespace:$title";
765 if ( strval( $interwiki ) != '' ) {
766 $name = "$interwiki:$name";
768 if ( strval( $fragment ) != '' ) {
769 $name .= '#' . $fragment;
775 * Escape a text fragment, say from a link, for a URL
777 * @param string $fragment Containing a URL or link fragment (after the "#")
778 * @return string Escaped string
780 static function escapeFragmentForURL( $fragment ) {
781 # Note that we don't urlencode the fragment. urlencoded Unicode
782 # fragments appear not to work in IE (at least up to 7) or in at least
783 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
784 # to care if they aren't encoded.
785 return Sanitizer
::escapeId( $fragment, 'noninitial' );
789 * Callback for usort() to do title sorts by (namespace, title)
794 * @return int Result of string comparison, or namespace comparison
796 public static function compare( $a, $b ) {
797 if ( $a->getNamespace() == $b->getNamespace() ) {
798 return strcmp( $a->getText(), $b->getText() );
800 return $a->getNamespace() - $b->getNamespace();
805 * Determine whether the object refers to a page within
806 * this project (either this wiki or a wiki with a local
807 * interwiki, see https://www.mediawiki.org/wiki/Manual:Interwiki_table#iw_local )
809 * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise
811 public function isLocal() {
812 if ( $this->isExternal() ) {
813 $iw = Interwiki
::fetch( $this->mInterwiki
);
815 return $iw->isLocal();
822 * Is this Title interwiki?
826 public function isExternal() {
827 return $this->mInterwiki
!== '';
831 * Get the interwiki prefix
833 * Use Title::isExternal to check if a interwiki is set
835 * @return string Interwiki prefix
837 public function getInterwiki() {
838 return $this->mInterwiki
;
842 * Was this a local interwiki link?
846 public function wasLocalInterwiki() {
847 return $this->mLocalInterwiki
;
851 * Determine whether the object refers to a page within
852 * this project and is transcludable.
854 * @return bool True if this is transcludable
856 public function isTrans() {
857 if ( !$this->isExternal() ) {
861 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
865 * Returns the DB name of the distant wiki which owns the object.
867 * @return string The DB name
869 public function getTransWikiID() {
870 if ( !$this->isExternal() ) {
874 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
878 * Get a TitleValue object representing this Title.
880 * @note Not all valid Titles have a corresponding valid TitleValue
881 * (e.g. TitleValues cannot represent page-local links that have a
882 * fragment but no title text).
884 * @return TitleValue|null
886 public function getTitleValue() {
887 if ( $this->mTitleValue
=== null ) {
889 $this->mTitleValue
= new TitleValue(
890 $this->getNamespace(),
892 $this->getFragment() );
893 } catch ( InvalidArgumentException
$ex ) {
894 wfDebug( __METHOD__
. ': Can\'t create a TitleValue for [[' .
895 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
899 return $this->mTitleValue
;
903 * Get the text form (spaces not underscores) of the main part
905 * @return string Main part of the title
907 public function getText() {
908 return $this->mTextform
;
912 * Get the URL-encoded form of the main part
914 * @return string Main part of the title, URL-encoded
916 public function getPartialURL() {
917 return $this->mUrlform
;
921 * Get the main part with underscores
923 * @return string Main part of the title, with underscores
925 public function getDBkey() {
926 return $this->mDbkeyform
;
930 * Get the DB key with the initial letter case as specified by the user
932 * @return string DB key
934 function getUserCaseDBKey() {
935 if ( !is_null( $this->mUserCaseDBKey
) ) {
936 return $this->mUserCaseDBKey
;
938 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
939 return $this->mDbkeyform
;
944 * Get the namespace index, i.e. one of the NS_xxxx constants.
946 * @return int Namespace index
948 public function getNamespace() {
949 return $this->mNamespace
;
953 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
955 * @throws MWException
956 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
957 * @return string Content model id
959 public function getContentModel( $flags = 0 ) {
960 # Calling getArticleID() loads the field from cache as needed
961 if ( !$this->mContentModel
&& $this->getArticleID( $flags ) ) {
962 $linkCache = LinkCache
::singleton();
963 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
966 if ( !$this->mContentModel
) {
967 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
970 if ( !$this->mContentModel
) {
971 throw new MWException( 'Failed to determine content model!' );
974 return $this->mContentModel
;
978 * Convenience method for checking a title's content model name
980 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
981 * @return bool True if $this->getContentModel() == $id
983 public function hasContentModel( $id ) {
984 return $this->getContentModel() == $id;
988 * Get the namespace text
990 * @return string Namespace text
992 public function getNsText() {
993 if ( $this->isExternal() ) {
994 // This probably shouldn't even happen. ohh man, oh yuck.
995 // But for interwiki transclusion it sometimes does.
996 // Shit. Shit shit shit.
998 // Use the canonical namespaces if possible to try to
999 // resolve a foreign namespace.
1000 if ( MWNamespace
::exists( $this->mNamespace
) ) {
1001 return MWNamespace
::getCanonicalName( $this->mNamespace
);
1006 $formatter = self
::getTitleFormatter();
1007 return $formatter->getNamespaceName( $this->mNamespace
, $this->mDbkeyform
);
1008 } catch ( InvalidArgumentException
$ex ) {
1009 wfDebug( __METHOD__
. ': ' . $ex->getMessage() . "\n" );
1015 * Get the namespace text of the subject (rather than talk) page
1017 * @return string Namespace text
1019 public function getSubjectNsText() {
1021 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
1025 * Get the namespace text of the talk page
1027 * @return string Namespace text
1029 public function getTalkNsText() {
1031 return $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) );
1035 * Could this title have a corresponding talk page?
1039 public function canTalk() {
1040 return MWNamespace
::canTalk( $this->mNamespace
);
1044 * Is this in a namespace that allows actual pages?
1047 * @internal note -- uses hardcoded namespace index instead of constants
1049 public function canExist() {
1050 return $this->mNamespace
>= NS_MAIN
;
1054 * Can this title be added to a user's watchlist?
1058 public function isWatchable() {
1059 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
1063 * Returns true if this is a special page.
1067 public function isSpecialPage() {
1068 return $this->getNamespace() == NS_SPECIAL
;
1072 * Returns true if this title resolves to the named special page
1074 * @param string $name The special page name
1077 public function isSpecial( $name ) {
1078 if ( $this->isSpecialPage() ) {
1079 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
1080 if ( $name == $thisName ) {
1088 * If the Title refers to a special page alias which is not the local default, resolve
1089 * the alias, and localise the name as necessary. Otherwise, return $this
1093 public function fixSpecialName() {
1094 if ( $this->isSpecialPage() ) {
1095 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
1096 if ( $canonicalName ) {
1097 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
1098 if ( $localName != $this->mDbkeyform
) {
1099 return Title
::makeTitle( NS_SPECIAL
, $localName );
1107 * Returns true if the title is inside the specified namespace.
1109 * Please make use of this instead of comparing to getNamespace()
1110 * This function is much more resistant to changes we may make
1111 * to namespaces than code that makes direct comparisons.
1112 * @param int $ns The namespace
1116 public function inNamespace( $ns ) {
1117 return MWNamespace
::equals( $this->getNamespace(), $ns );
1121 * Returns true if the title is inside one of the specified namespaces.
1123 * @param int $namespaces,... The namespaces to check for
1127 public function inNamespaces( /* ... */ ) {
1128 $namespaces = func_get_args();
1129 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1130 $namespaces = $namespaces[0];
1133 foreach ( $namespaces as $ns ) {
1134 if ( $this->inNamespace( $ns ) ) {
1143 * Returns true if the title has the same subject namespace as the
1144 * namespace specified.
1145 * For example this method will take NS_USER and return true if namespace
1146 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1147 * as their subject namespace.
1149 * This is MUCH simpler than individually testing for equivalence
1150 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1155 public function hasSubjectNamespace( $ns ) {
1156 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
1160 * Is this Title in a namespace which contains content?
1161 * In other words, is this a content page, for the purposes of calculating
1166 public function isContentPage() {
1167 return MWNamespace
::isContent( $this->getNamespace() );
1171 * Would anybody with sufficient privileges be able to move this page?
1172 * Some pages just aren't movable.
1176 public function isMovable() {
1177 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->isExternal() ) {
1178 // Interwiki title or immovable namespace. Hooks don't get to override here
1183 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1188 * Is this the mainpage?
1189 * @note Title::newFromText seems to be sufficiently optimized by the title
1190 * cache that we don't need to over-optimize by doing direct comparisons and
1191 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1192 * ends up reporting something differently than $title->isMainPage();
1197 public function isMainPage() {
1198 return $this->equals( Title
::newMainPage() );
1202 * Is this a subpage?
1206 public function isSubpage() {
1207 return MWNamespace
::hasSubpages( $this->mNamespace
)
1208 ?
strpos( $this->getText(), '/' ) !== false
1213 * Is this a conversion table for the LanguageConverter?
1217 public function isConversionTable() {
1218 // @todo ConversionTable should become a separate content model.
1220 return $this->getNamespace() == NS_MEDIAWIKI
&&
1221 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1225 * Does that page contain wikitext, or it is JS, CSS or whatever?
1229 public function isWikitextPage() {
1230 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
1234 * Could this page contain custom CSS or JavaScript for the global UI.
1235 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1236 * or CONTENT_MODEL_JAVASCRIPT.
1238 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage()
1241 * Note that this method should not return true for pages that contain and
1242 * show "inactive" CSS or JS.
1246 public function isCssOrJsPage() {
1247 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
1248 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1249 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1251 # @note This hook is also called in ContentHandler::getDefaultModel.
1252 # It's called here again to make sure hook functions can force this
1253 # method to return true even outside the MediaWiki namespace.
1255 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ), '1.25' );
1257 return $isCssOrJsPage;
1261 * Is this a .css or .js subpage of a user page?
1264 public function isCssJsSubpage() {
1265 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1266 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
1267 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
1271 * Trim down a .css or .js subpage title to get the corresponding skin name
1273 * @return string Containing skin name from .css or .js subpage title
1275 public function getSkinFromCssJsSubpage() {
1276 $subpage = explode( '/', $this->mTextform
);
1277 $subpage = $subpage[count( $subpage ) - 1];
1278 $lastdot = strrpos( $subpage, '.' );
1279 if ( $lastdot === false ) {
1280 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1282 return substr( $subpage, 0, $lastdot );
1286 * Is this a .css subpage of a user page?
1290 public function isCssSubpage() {
1291 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1292 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1296 * Is this a .js subpage of a user page?
1300 public function isJsSubpage() {
1301 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1302 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1306 * Is this a talk page of some sort?
1310 public function isTalkPage() {
1311 return MWNamespace
::isTalk( $this->getNamespace() );
1315 * Get a Title object associated with the talk page of this article
1317 * @return Title The object for the talk page
1319 public function getTalkPage() {
1320 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1324 * Get a title object associated with the subject page of this
1327 * @return Title The object for the subject page
1329 public function getSubjectPage() {
1330 // Is this the same title?
1331 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1332 if ( $this->getNamespace() == $subjectNS ) {
1335 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1339 * Get the other title for this page, if this is a subject page
1340 * get the talk page, if it is a subject page get the talk page
1343 * @throws MWException
1346 public function getOtherPage() {
1347 if ( $this->isSpecialPage() ) {
1348 throw new MWException( 'Special pages cannot have other pages' );
1350 if ( $this->isTalkPage() ) {
1351 return $this->getSubjectPage();
1353 return $this->getTalkPage();
1358 * Get the default namespace index, for when there is no namespace
1360 * @return int Default namespace index
1362 public function getDefaultNamespace() {
1363 return $this->mDefaultNamespace
;
1367 * Get the Title fragment (i.e.\ the bit after the #) in text form
1369 * Use Title::hasFragment to check for a fragment
1371 * @return string Title fragment
1373 public function getFragment() {
1374 return $this->mFragment
;
1378 * Check if a Title fragment is set
1383 public function hasFragment() {
1384 return $this->mFragment
!== '';
1388 * Get the fragment in URL form, including the "#" character if there is one
1389 * @return string Fragment in URL form
1391 public function getFragmentForURL() {
1392 if ( !$this->hasFragment() ) {
1395 return '#' . Title
::escapeFragmentForURL( $this->getFragment() );
1400 * Set the fragment for this title. Removes the first character from the
1401 * specified fragment before setting, so it assumes you're passing it with
1404 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1405 * Still in active use privately.
1407 * @param string $fragment Text
1409 public function setFragment( $fragment ) {
1410 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1414 * Prefix some arbitrary text with the namespace or interwiki prefix
1417 * @param string $name The text
1418 * @return string The prefixed text
1420 private function prefix( $name ) {
1422 if ( $this->isExternal() ) {
1423 $p = $this->mInterwiki
. ':';
1426 if ( 0 != $this->mNamespace
) {
1427 $p .= $this->getNsText() . ':';
1433 * Get the prefixed database key form
1435 * @return string The prefixed title, with underscores and
1436 * any interwiki and namespace prefixes
1438 public function getPrefixedDBkey() {
1439 $s = $this->prefix( $this->mDbkeyform
);
1440 $s = str_replace( ' ', '_', $s );
1445 * Get the prefixed title with spaces.
1446 * This is the form usually used for display
1448 * @return string The prefixed title, with spaces
1450 public function getPrefixedText() {
1451 if ( $this->mPrefixedText
=== null ) {
1452 $s = $this->prefix( $this->mTextform
);
1453 $s = str_replace( '_', ' ', $s );
1454 $this->mPrefixedText
= $s;
1456 return $this->mPrefixedText
;
1460 * Return a string representation of this title
1462 * @return string Representation of this title
1464 public function __toString() {
1465 return $this->getPrefixedText();
1469 * Get the prefixed title with spaces, plus any fragment
1470 * (part beginning with '#')
1472 * @return string The prefixed title, with spaces and the fragment, including '#'
1474 public function getFullText() {
1475 $text = $this->getPrefixedText();
1476 if ( $this->hasFragment() ) {
1477 $text .= '#' . $this->getFragment();
1483 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1487 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1491 * @return string Root name
1494 public function getRootText() {
1495 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1496 return $this->getText();
1499 return strtok( $this->getText(), '/' );
1503 * Get the root page name title, i.e. the leftmost part before any slashes
1507 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1508 * # returns: Title{User:Foo}
1511 * @return Title Root title
1514 public function getRootTitle() {
1515 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1519 * Get the base page name without a namespace, i.e. the part before the subpage name
1523 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1524 * # returns: 'Foo/Bar'
1527 * @return string Base name
1529 public function getBaseText() {
1530 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1531 return $this->getText();
1534 $parts = explode( '/', $this->getText() );
1535 # Don't discard the real title if there's no subpage involved
1536 if ( count( $parts ) > 1 ) {
1537 unset( $parts[count( $parts ) - 1] );
1539 return implode( '/', $parts );
1543 * Get the base page name title, i.e. the part before the subpage name
1547 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1548 * # returns: Title{User:Foo/Bar}
1551 * @return Title Base title
1554 public function getBaseTitle() {
1555 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1559 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1563 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1567 * @return string Subpage name
1569 public function getSubpageText() {
1570 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1571 return $this->mTextform
;
1573 $parts = explode( '/', $this->mTextform
);
1574 return $parts[count( $parts ) - 1];
1578 * Get the title for a subpage of the current page
1582 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1583 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1586 * @param string $text The subpage name to add to the title
1587 * @return Title Subpage title
1590 public function getSubpage( $text ) {
1591 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1595 * Get a URL-encoded form of the subpage text
1597 * @return string URL-encoded subpage name
1599 public function getSubpageUrlForm() {
1600 $text = $this->getSubpageText();
1601 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1606 * Get a URL-encoded title (not an actual URL) including interwiki
1608 * @return string The URL-encoded form
1610 public function getPrefixedURL() {
1611 $s = $this->prefix( $this->mDbkeyform
);
1612 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1617 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1618 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1619 * second argument named variant. This was deprecated in favor
1620 * of passing an array of option with a "variant" key
1621 * Once $query2 is removed for good, this helper can be dropped
1622 * and the wfArrayToCgi moved to getLocalURL();
1624 * @since 1.19 (r105919)
1625 * @param array|string $query
1626 * @param bool $query2
1629 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1630 if ( $query2 !== false ) {
1631 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1632 "method called with a second parameter is deprecated. Add your " .
1633 "parameter to an array passed as the first parameter.", "1.19" );
1635 if ( is_array( $query ) ) {
1636 $query = wfArrayToCgi( $query );
1639 if ( is_string( $query2 ) ) {
1640 // $query2 is a string, we will consider this to be
1641 // a deprecated $variant argument and add it to the query
1642 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1644 $query2 = wfArrayToCgi( $query2 );
1646 // If we have $query content add a & to it first
1650 // Now append the queries together
1657 * Get a real URL referring to this title, with interwiki link and
1660 * @see self::getLocalURL for the arguments.
1662 * @param array|string $query
1663 * @param bool $query2
1664 * @param string $proto Protocol type to use in URL
1665 * @return string The URL
1667 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1668 $query = self
::fixUrlQueryArgs( $query, $query2 );
1670 # Hand off all the decisions on urls to getLocalURL
1671 $url = $this->getLocalURL( $query );
1673 # Expand the url to make it a full url. Note that getLocalURL has the
1674 # potential to output full urls for a variety of reasons, so we use
1675 # wfExpandUrl instead of simply prepending $wgServer
1676 $url = wfExpandUrl( $url, $proto );
1678 # Finally, add the fragment.
1679 $url .= $this->getFragmentForURL();
1681 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1686 * Get a URL with no fragment or server name (relative URL) from a Title object.
1687 * If this page is generated with action=render, however,
1688 * $wgServer is prepended to make an absolute URL.
1690 * @see self::getFullURL to always get an absolute URL.
1691 * @see self::getLinkURL to always get a URL that's the simplest URL that will be
1692 * valid to link, locally, to the current Title.
1693 * @see self::newFromText to produce a Title object.
1695 * @param string|array $query An optional query string,
1696 * not used for interwiki links. Can be specified as an associative array as well,
1697 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1698 * Some query patterns will trigger various shorturl path replacements.
1699 * @param array $query2 An optional secondary query array. This one MUST
1700 * be an array. If a string is passed it will be interpreted as a deprecated
1701 * variant argument and urlencoded into a variant= argument.
1702 * This second query argument will be added to the $query
1703 * The second parameter is deprecated since 1.19. Pass it as a key,value
1704 * pair in the first parameter array instead.
1706 * @return string String of the URL.
1708 public function getLocalURL( $query = '', $query2 = false ) {
1709 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1711 $query = self
::fixUrlQueryArgs( $query, $query2 );
1713 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1715 $namespace = $this->getNsText();
1716 if ( $namespace != '' ) {
1717 # Can this actually happen? Interwikis shouldn't be parsed.
1718 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1721 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1722 $url = wfAppendQuery( $url, $query );
1724 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1725 if ( $query == '' ) {
1726 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1727 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1729 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1733 if ( !empty( $wgActionPaths )
1734 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1736 $action = urldecode( $matches[2] );
1737 if ( isset( $wgActionPaths[$action] ) ) {
1738 $query = $matches[1];
1739 if ( isset( $matches[4] ) ) {
1740 $query .= $matches[4];
1742 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1743 if ( $query != '' ) {
1744 $url = wfAppendQuery( $url, $query );
1750 && $wgVariantArticlePath
1751 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1752 && $this->getPageLanguage()->hasVariants()
1753 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1755 $variant = urldecode( $matches[1] );
1756 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1757 // Only do the variant replacement if the given variant is a valid
1758 // variant for the page's language.
1759 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1760 $url = str_replace( '$1', $dbkey, $url );
1764 if ( $url === false ) {
1765 if ( $query == '-' ) {
1768 $url = "{$wgScript}?title={$dbkey}&{$query}";
1772 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1774 // @todo FIXME: This causes breakage in various places when we
1775 // actually expected a local URL and end up with dupe prefixes.
1776 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1777 $url = $wgServer . $url;
1780 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1785 * Get a URL that's the simplest URL that will be valid to link, locally,
1786 * to the current Title. It includes the fragment, but does not include
1787 * the server unless action=render is used (or the link is external). If
1788 * there's a fragment but the prefixed text is empty, we just return a link
1791 * The result obviously should not be URL-escaped, but does need to be
1792 * HTML-escaped if it's being output in HTML.
1794 * @param array $query
1795 * @param bool $query2
1796 * @param string $proto Protocol to use; setting this will cause a full URL to be used
1797 * @see self::getLocalURL for the arguments.
1798 * @return string The URL
1800 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1801 wfProfileIn( __METHOD__
);
1802 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1803 $ret = $this->getFullURL( $query, $query2, $proto );
1804 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1805 $ret = $this->getFragmentForURL();
1807 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1809 wfProfileOut( __METHOD__
);
1814 * Get the URL form for an internal link.
1815 * - Used in various Squid-related code, in case we have a different
1816 * internal hostname for the server from the exposed one.
1818 * This uses $wgInternalServer to qualify the path, or $wgServer
1819 * if $wgInternalServer is not set. If the server variable used is
1820 * protocol-relative, the URL will be expanded to http://
1822 * @see self::getLocalURL for the arguments.
1823 * @return string The URL
1825 public function getInternalURL( $query = '', $query2 = false ) {
1826 global $wgInternalServer, $wgServer;
1827 $query = self
::fixUrlQueryArgs( $query, $query2 );
1828 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1829 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1830 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1835 * Get the URL for a canonical link, for use in things like IRC and
1836 * e-mail notifications. Uses $wgCanonicalServer and the
1837 * GetCanonicalURL hook.
1839 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1841 * @see self::getLocalURL for the arguments.
1842 * @return string The URL
1845 public function getCanonicalURL( $query = '', $query2 = false ) {
1846 $query = self
::fixUrlQueryArgs( $query, $query2 );
1847 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1848 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1853 * Get the edit URL for this Title
1855 * @return string The URL, or a null string if this is an interwiki link
1857 public function getEditURL() {
1858 if ( $this->isExternal() ) {
1861 $s = $this->getLocalURL( 'action=edit' );
1867 * Is $wgUser watching this page?
1869 * @deprecated since 1.20; use User::isWatched() instead.
1872 public function userIsWatching() {
1875 if ( is_null( $this->mWatched
) ) {
1876 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1877 $this->mWatched
= false;
1879 $this->mWatched
= $wgUser->isWatched( $this );
1882 return $this->mWatched
;
1886 * Can $user perform $action on this page?
1887 * This skips potentially expensive cascading permission checks
1888 * as well as avoids expensive error formatting
1890 * Suitable for use for nonessential UI controls in common cases, but
1891 * _not_ for functional access control.
1893 * May provide false positives, but should never provide a false negative.
1895 * @param string $action Action that permission needs to be checked for
1896 * @param User $user User to check (since 1.19); $wgUser will be used if not provided.
1899 public function quickUserCan( $action, $user = null ) {
1900 return $this->userCan( $action, $user, false );
1904 * Can $user perform $action on this page?
1906 * @param string $action Action that permission needs to be checked for
1907 * @param User $user User to check (since 1.19); $wgUser will be used if not
1909 * @param bool $doExpensiveQueries Set this to false to avoid doing
1910 * unnecessary queries.
1913 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1914 if ( !$user instanceof User
) {
1919 return !count( $this->getUserPermissionsErrorsInternal(
1920 $action, $user, $doExpensiveQueries, true ) );
1924 * Can $user perform $action on this page?
1926 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1928 * @param string $action Action that permission needs to be checked for
1929 * @param User $user User to check
1930 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1931 * queries by skipping checks for cascading protections and user blocks.
1932 * @param array $ignoreErrors Array of Strings Set this to a list of message keys
1933 * whose corresponding errors may be ignored.
1934 * @return array Array of arguments to wfMessage to explain permissions problems.
1936 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true,
1937 $ignoreErrors = array()
1939 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1941 // Remove the errors being ignored.
1942 foreach ( $errors as $index => $error ) {
1943 $error_key = is_array( $error ) ?
$error[0] : $error;
1945 if ( in_array( $error_key, $ignoreErrors ) ) {
1946 unset( $errors[$index] );
1954 * Permissions checks that fail most often, and which are easiest to test.
1956 * @param string $action The action to check
1957 * @param User $user User to check
1958 * @param array $errors List of current errors
1959 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
1960 * @param bool $short Short circuit on first error
1962 * @return array List of errors
1964 private function checkQuickPermissions( $action, $user, $errors,
1965 $doExpensiveQueries, $short
1967 if ( !wfRunHooks( 'TitleQuickPermissions',
1968 array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) )
1973 if ( $action == 'create' ) {
1975 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1976 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1978 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1980 } elseif ( $action == 'move' ) {
1981 if ( !$user->isAllowed( 'move-rootuserpages' )
1982 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1983 // Show user page-specific message only if the user can move other pages
1984 $errors[] = array( 'cant-move-user-page' );
1987 // Check if user is allowed to move files if it's a file
1988 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1989 $errors[] = array( 'movenotallowedfile' );
1992 // Check if user is allowed to move category pages if it's a category page
1993 if ( $this->mNamespace
== NS_CATEGORY
&& !$user->isAllowed( 'move-categorypages' ) ) {
1994 $errors[] = array( 'cant-move-category-page' );
1997 if ( !$user->isAllowed( 'move' ) ) {
1998 // User can't move anything
1999 $userCanMove = User
::groupHasPermission( 'user', 'move' );
2000 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
2001 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
2002 // custom message if logged-in users without any special rights can move
2003 $errors[] = array( 'movenologintext' );
2005 $errors[] = array( 'movenotallowed' );
2008 } elseif ( $action == 'move-target' ) {
2009 if ( !$user->isAllowed( 'move' ) ) {
2010 // User can't move anything
2011 $errors[] = array( 'movenotallowed' );
2012 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
2013 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
2014 // Show user page-specific message only if the user can move other pages
2015 $errors[] = array( 'cant-move-to-user-page' );
2016 } elseif ( !$user->isAllowed( 'move-categorypages' )
2017 && $this->mNamespace
== NS_CATEGORY
) {
2018 // Show category page-specific message only if the user can move other pages
2019 $errors[] = array( 'cant-move-to-category-page' );
2021 } elseif ( !$user->isAllowed( $action ) ) {
2022 $errors[] = $this->missingPermissionError( $action, $short );
2029 * Add the resulting error code to the errors array
2031 * @param array $errors List of current errors
2032 * @param array $result Result of errors
2034 * @return array List of errors
2036 private function resultToError( $errors, $result ) {
2037 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
2038 // A single array representing an error
2039 $errors[] = $result;
2040 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
2041 // A nested array representing multiple errors
2042 $errors = array_merge( $errors, $result );
2043 } elseif ( $result !== '' && is_string( $result ) ) {
2044 // A string representing a message-id
2045 $errors[] = array( $result );
2046 } elseif ( $result === false ) {
2047 // a generic "We don't want them to do that"
2048 $errors[] = array( 'badaccess-group0' );
2054 * Check various permission hooks
2056 * @param string $action The action to check
2057 * @param User $user User to check
2058 * @param array $errors List of current errors
2059 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2060 * @param bool $short Short circuit on first error
2062 * @return array List of errors
2064 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
2065 // Use getUserPermissionsErrors instead
2067 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
2068 return $result ?
array() : array( array( 'badaccess-group0' ) );
2070 // Check getUserPermissionsErrors hook
2071 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2072 $errors = $this->resultToError( $errors, $result );
2074 // Check getUserPermissionsErrorsExpensive hook
2077 && !( $short && count( $errors ) > 0 )
2078 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2080 $errors = $this->resultToError( $errors, $result );
2087 * Check permissions on special pages & namespaces
2089 * @param string $action The action to check
2090 * @param User $user User to check
2091 * @param array $errors List of current errors
2092 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2093 * @param bool $short Short circuit on first error
2095 * @return array List of errors
2097 private function checkSpecialsAndNSPermissions( $action, $user, $errors,
2098 $doExpensiveQueries, $short
2100 # Only 'createaccount' can be performed on special pages,
2101 # which don't actually exist in the DB.
2102 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
2103 $errors[] = array( 'ns-specialprotected' );
2106 # Check $wgNamespaceProtection for restricted namespaces
2107 if ( $this->isNamespaceProtected( $user ) ) {
2108 $ns = $this->mNamespace
== NS_MAIN ?
2109 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2110 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
2111 array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action );
2118 * Check CSS/JS sub-page permissions
2120 * @param string $action The action to check
2121 * @param User $user User to check
2122 * @param array $errors List of current errors
2123 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2124 * @param bool $short Short circuit on first error
2126 * @return array List of errors
2128 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2129 # Protect css/js subpages of user pages
2130 # XXX: this might be better using restrictions
2131 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2132 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2133 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
2134 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2135 $errors[] = array( 'mycustomcssprotected', $action );
2136 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2137 $errors[] = array( 'mycustomjsprotected', $action );
2140 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2141 $errors[] = array( 'customcssprotected', $action );
2142 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2143 $errors[] = array( 'customjsprotected', $action );
2152 * Check against page_restrictions table requirements on this
2153 * page. The user must possess all required rights for this
2156 * @param string $action The action to check
2157 * @param User $user User to check
2158 * @param array $errors List of current errors
2159 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2160 * @param bool $short Short circuit on first error
2162 * @return array List of errors
2164 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2165 foreach ( $this->getRestrictions( $action ) as $right ) {
2166 // Backwards compatibility, rewrite sysop -> editprotected
2167 if ( $right == 'sysop' ) {
2168 $right = 'editprotected';
2170 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2171 if ( $right == 'autoconfirmed' ) {
2172 $right = 'editsemiprotected';
2174 if ( $right == '' ) {
2177 if ( !$user->isAllowed( $right ) ) {
2178 $errors[] = array( 'protectedpagetext', $right, $action );
2179 } elseif ( $this->mCascadeRestriction
&& !$user->isAllowed( 'protect' ) ) {
2180 $errors[] = array( 'protectedpagetext', 'protect', $action );
2188 * Check restrictions on cascading pages.
2190 * @param string $action The action to check
2191 * @param User $user User to check
2192 * @param array $errors List of current errors
2193 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2194 * @param bool $short Short circuit on first error
2196 * @return array List of errors
2198 private function checkCascadingSourcesRestrictions( $action, $user, $errors,
2199 $doExpensiveQueries, $short
2201 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2202 # We /could/ use the protection level on the source page, but it's
2203 # fairly ugly as we have to establish a precedence hierarchy for pages
2204 # included by multiple cascade-protected pages. So just restrict
2205 # it to people with 'protect' permission, as they could remove the
2206 # protection anyway.
2207 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2208 # Cascading protection depends on more than this page...
2209 # Several cascading protected pages may include this page...
2210 # Check each cascading level
2211 # This is only for protection restrictions, not for all actions
2212 if ( isset( $restrictions[$action] ) ) {
2213 foreach ( $restrictions[$action] as $right ) {
2214 // Backwards compatibility, rewrite sysop -> editprotected
2215 if ( $right == 'sysop' ) {
2216 $right = 'editprotected';
2218 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2219 if ( $right == 'autoconfirmed' ) {
2220 $right = 'editsemiprotected';
2222 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2224 foreach ( $cascadingSources as $page ) {
2225 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2227 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action );
2237 * Check action permissions not already checked in checkQuickPermissions
2239 * @param string $action The action to check
2240 * @param User $user User to check
2241 * @param array $errors List of current errors
2242 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2243 * @param bool $short Short circuit on first error
2245 * @return array List of errors
2247 private function checkActionPermissions( $action, $user, $errors,
2248 $doExpensiveQueries, $short
2250 global $wgDeleteRevisionsLimit, $wgLang;
2252 if ( $action == 'protect' ) {
2253 if ( count( $this->getUserPermissionsErrorsInternal( 'edit',
2254 $user, $doExpensiveQueries, true ) )
2256 // If they can't edit, they shouldn't protect.
2257 $errors[] = array( 'protect-cantedit' );
2259 } elseif ( $action == 'create' ) {
2260 $title_protection = $this->getTitleProtection();
2261 if ( $title_protection ) {
2262 if ( $title_protection['permission'] == ''
2263 ||
!$user->isAllowed( $title_protection['permission'] )
2267 User
::whoIs( $title_protection['user'] ),
2268 $title_protection['reason']
2272 } elseif ( $action == 'move' ) {
2273 // Check for immobile pages
2274 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2275 // Specific message for this case
2276 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2277 } elseif ( !$this->isMovable() ) {
2278 // Less specific message for rarer cases
2279 $errors[] = array( 'immobile-source-page' );
2281 } elseif ( $action == 'move-target' ) {
2282 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2283 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2284 } elseif ( !$this->isMovable() ) {
2285 $errors[] = array( 'immobile-target-page' );
2287 } elseif ( $action == 'delete' ) {
2288 $tempErrors = $this->checkPageRestrictions( 'edit',
2289 $user, array(), $doExpensiveQueries, true );
2290 if ( !$tempErrors ) {
2291 $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
2292 $user, $tempErrors, $doExpensiveQueries, true );
2294 if ( $tempErrors ) {
2295 // If protection keeps them from editing, they shouldn't be able to delete.
2296 $errors[] = array( 'deleteprotected' );
2298 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2299 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2301 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2308 * Check that the user isn't blocked from editing.
2310 * @param string $action The action to check
2311 * @param User $user User to check
2312 * @param array $errors List of current errors
2313 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2314 * @param bool $short Short circuit on first error
2316 * @return array List of errors
2318 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2319 // Account creation blocks handled at userlogin.
2320 // Unblocking handled in SpecialUnblock
2321 if ( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2325 global $wgEmailConfirmToEdit;
2327 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2328 $errors[] = array( 'confirmedittext' );
2331 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2332 // Don't block the user from editing their own talk page unless they've been
2333 // explicitly blocked from that too.
2334 } elseif ( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2335 // @todo FIXME: Pass the relevant context into this function.
2336 $errors[] = $user->getBlock()->getPermissionsError( RequestContext
::getMain() );
2343 * Check that the user is allowed to read this page.
2345 * @param string $action The action to check
2346 * @param User $user User to check
2347 * @param array $errors List of current errors
2348 * @param bool $doExpensiveQueries Whether or not to perform expensive queries
2349 * @param bool $short Short circuit on first error
2351 * @return array List of errors
2353 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2354 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2356 $whitelisted = false;
2357 if ( User
::isEveryoneAllowed( 'read' ) ) {
2358 # Shortcut for public wikis, allows skipping quite a bit of code
2359 $whitelisted = true;
2360 } elseif ( $user->isAllowed( 'read' ) ) {
2361 # If the user is allowed to read pages, he is allowed to read all pages
2362 $whitelisted = true;
2363 } elseif ( $this->isSpecial( 'Userlogin' )
2364 ||
$this->isSpecial( 'ChangePassword' )
2365 ||
$this->isSpecial( 'PasswordReset' )
2367 # Always grant access to the login page.
2368 # Even anons need to be able to log in.
2369 $whitelisted = true;
2370 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2371 # Time to check the whitelist
2372 # Only do these checks is there's something to check against
2373 $name = $this->getPrefixedText();
2374 $dbName = $this->getPrefixedDBkey();
2376 // Check for explicit whitelisting with and without underscores
2377 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2378 $whitelisted = true;
2379 } elseif ( $this->getNamespace() == NS_MAIN
) {
2380 # Old settings might have the title prefixed with
2381 # a colon for main-namespace pages
2382 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2383 $whitelisted = true;
2385 } elseif ( $this->isSpecialPage() ) {
2386 # If it's a special page, ditch the subpage bit and check again
2387 $name = $this->getDBkey();
2388 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2390 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2391 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2392 $whitelisted = true;
2398 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2399 $name = $this->getPrefixedText();
2400 // Check for regex whitelisting
2401 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2402 if ( preg_match( $listItem, $name ) ) {
2403 $whitelisted = true;
2409 if ( !$whitelisted ) {
2410 # If the title is not whitelisted, give extensions a chance to do so...
2411 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2412 if ( !$whitelisted ) {
2413 $errors[] = $this->missingPermissionError( $action, $short );
2421 * Get a description array when the user doesn't have the right to perform
2422 * $action (i.e. when User::isAllowed() returns false)
2424 * @param string $action The action to check
2425 * @param bool $short Short circuit on first error
2426 * @return array List of errors
2428 private function missingPermissionError( $action, $short ) {
2429 // We avoid expensive display logic for quickUserCan's and such
2431 return array( 'badaccess-group0' );
2434 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2435 User
::getGroupsWithPermission( $action ) );
2437 if ( count( $groups ) ) {
2441 $wgLang->commaList( $groups ),
2445 return array( 'badaccess-group0' );
2450 * Can $user perform $action on this page? This is an internal function,
2451 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2452 * checks on wfReadOnly() and blocks)
2454 * @param string $action Action that permission needs to be checked for
2455 * @param User $user User to check
2456 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2457 * @param bool $short Set this to true to stop after the first permission error.
2458 * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
2460 protected function getUserPermissionsErrorsInternal( $action, $user,
2461 $doExpensiveQueries = true, $short = false
2463 wfProfileIn( __METHOD__
);
2465 # Read has special handling
2466 if ( $action == 'read' ) {
2468 'checkPermissionHooks',
2469 'checkReadPermissions',
2471 # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions
2472 # here as it will lead to duplicate error messages. This is okay to do
2473 # since anywhere that checks for create will also check for edit, and
2474 # those checks are called for edit.
2475 } elseif ( $action == 'create' ) {
2477 'checkQuickPermissions',
2478 'checkPermissionHooks',
2479 'checkPageRestrictions',
2480 'checkCascadingSourcesRestrictions',
2481 'checkActionPermissions',
2486 'checkQuickPermissions',
2487 'checkPermissionHooks',
2488 'checkSpecialsAndNSPermissions',
2489 'checkCSSandJSPermissions',
2490 'checkPageRestrictions',
2491 'checkCascadingSourcesRestrictions',
2492 'checkActionPermissions',
2498 while ( count( $checks ) > 0 &&
2499 !( $short && count( $errors ) > 0 ) ) {
2500 $method = array_shift( $checks );
2501 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2504 wfProfileOut( __METHOD__
);
2509 * Get a filtered list of all restriction types supported by this wiki.
2510 * @param bool $exists True to get all restriction types that apply to
2511 * titles that do exist, False for all restriction types that apply to
2512 * titles that do not exist
2515 public static function getFilteredRestrictionTypes( $exists = true ) {
2516 global $wgRestrictionTypes;
2517 $types = $wgRestrictionTypes;
2519 # Remove the create restriction for existing titles
2520 $types = array_diff( $types, array( 'create' ) );
2522 # Only the create and upload restrictions apply to non-existing titles
2523 $types = array_intersect( $types, array( 'create', 'upload' ) );
2529 * Returns restriction types for the current Title
2531 * @return array Applicable restriction types
2533 public function getRestrictionTypes() {
2534 if ( $this->isSpecialPage() ) {
2538 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2540 if ( $this->getNamespace() != NS_FILE
) {
2541 # Remove the upload restriction for non-file titles
2542 $types = array_diff( $types, array( 'upload' ) );
2545 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2547 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2548 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2554 * Is this title subject to title protection?
2555 * Title protection is the one applied against creation of such title.
2557 * @return array|bool An associative array representing any existent title
2558 * protection, or false if there's none.
2560 public function getTitleProtection() {
2561 // Can't protect pages in special namespaces
2562 if ( $this->getNamespace() < 0 ) {
2566 // Can't protect pages that exist.
2567 if ( $this->exists() ) {
2571 if ( $this->mTitleProtection
=== null ) {
2572 $dbr = wfGetDB( DB_SLAVE
);
2573 $res = $dbr->select(
2576 'user' => 'pt_user',
2577 'reason' => 'pt_reason',
2578 'expiry' => 'pt_expiry',
2579 'permission' => 'pt_create_perm'
2581 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2585 // fetchRow returns false if there are no rows.
2586 $row = $dbr->fetchRow( $res );
2588 if ( $row['permission'] == 'sysop' ) {
2589 $row['permission'] = 'editprotected'; // B/C
2591 if ( $row['permission'] == 'autoconfirmed' ) {
2592 $row['permission'] = 'editsemiprotected'; // B/C
2595 $this->mTitleProtection
= $row;
2597 return $this->mTitleProtection
;
2601 * Remove any title protection due to page existing
2603 public function deleteTitleProtection() {
2604 $dbw = wfGetDB( DB_MASTER
);
2608 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2611 $this->mTitleProtection
= false;
2615 * Is this page "semi-protected" - the *only* protection levels are listed
2616 * in $wgSemiprotectedRestrictionLevels?
2618 * @param string $action Action to check (default: edit)
2621 public function isSemiProtected( $action = 'edit' ) {
2622 global $wgSemiprotectedRestrictionLevels;
2624 $restrictions = $this->getRestrictions( $action );
2625 $semi = $wgSemiprotectedRestrictionLevels;
2626 if ( !$restrictions ||
!$semi ) {
2627 // Not protected, or all protection is full protection
2631 // Remap autoconfirmed to editsemiprotected for BC
2632 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2633 $semi[$key] = 'editsemiprotected';
2635 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2636 $restrictions[$key] = 'editsemiprotected';
2639 return !array_diff( $restrictions, $semi );
2643 * Does the title correspond to a protected article?
2645 * @param string $action The action the page is protected from,
2646 * by default checks all actions.
2649 public function isProtected( $action = '' ) {
2650 global $wgRestrictionLevels;
2652 $restrictionTypes = $this->getRestrictionTypes();
2654 # Special pages have inherent protection
2655 if ( $this->isSpecialPage() ) {
2659 # Check regular protection levels
2660 foreach ( $restrictionTypes as $type ) {
2661 if ( $action == $type ||
$action == '' ) {
2662 $r = $this->getRestrictions( $type );
2663 foreach ( $wgRestrictionLevels as $level ) {
2664 if ( in_array( $level, $r ) && $level != '' ) {
2675 * Determines if $user is unable to edit this page because it has been protected
2676 * by $wgNamespaceProtection.
2678 * @param User $user User object to check permissions
2681 public function isNamespaceProtected( User
$user ) {
2682 global $wgNamespaceProtection;
2684 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2685 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2686 if ( $right != '' && !$user->isAllowed( $right ) ) {
2695 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2697 * @return bool If the page is subject to cascading restrictions.
2699 public function isCascadeProtected() {
2700 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2701 return ( $sources > 0 );
2705 * Determines whether cascading protection sources have already been loaded from
2708 * @param bool $getPages True to check if the pages are loaded, or false to check
2709 * if the status is loaded.
2710 * @return bool Whether or not the specified information has been loaded
2713 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2714 return $getPages ?
$this->mCascadeSources
!== null : $this->mHasCascadingRestrictions
!== null;
2718 * Cascading protection: Get the source of any cascading restrictions on this page.
2720 * @param bool $getPages Whether or not to retrieve the actual pages
2721 * that the restrictions have come from and the actual restrictions
2723 * @return array Two elements: First is an array of Title objects of the
2724 * pages from which cascading restrictions have come, false for
2725 * none, or true if such restrictions exist but $getPages was not
2726 * set. Second is an array like that returned by
2727 * Title::getAllRestrictions(), or an empty array if $getPages is
2730 public function getCascadeProtectionSources( $getPages = true ) {
2732 $pagerestrictions = array();
2734 if ( $this->mCascadeSources
!== null && $getPages ) {
2735 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2736 } elseif ( $this->mHasCascadingRestrictions
!== null && !$getPages ) {
2737 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2740 wfProfileIn( __METHOD__
);
2742 $dbr = wfGetDB( DB_SLAVE
);
2744 if ( $this->getNamespace() == NS_FILE
) {
2745 $tables = array( 'imagelinks', 'page_restrictions' );
2746 $where_clauses = array(
2747 'il_to' => $this->getDBkey(),
2752 $tables = array( 'templatelinks', 'page_restrictions' );
2753 $where_clauses = array(
2754 'tl_namespace' => $this->getNamespace(),
2755 'tl_title' => $this->getDBkey(),
2762 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2763 'pr_expiry', 'pr_type', 'pr_level' );
2764 $where_clauses[] = 'page_id=pr_page';
2767 $cols = array( 'pr_expiry' );
2770 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2772 $sources = $getPages ?
array() : false;
2773 $now = wfTimestampNow();
2774 $purgeExpired = false;
2776 foreach ( $res as $row ) {
2777 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2778 if ( $expiry > $now ) {
2780 $page_id = $row->pr_page
;
2781 $page_ns = $row->page_namespace
;
2782 $page_title = $row->page_title
;
2783 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2784 # Add groups needed for each restriction type if its not already there
2785 # Make sure this restriction type still exists
2787 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2788 $pagerestrictions[$row->pr_type
] = array();
2792 isset( $pagerestrictions[$row->pr_type
] )
2793 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2795 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2801 // Trigger lazy purge of expired restrictions from the db
2802 $purgeExpired = true;
2805 if ( $purgeExpired ) {
2806 Title
::purgeExpiredRestrictions();
2810 $this->mCascadeSources
= $sources;
2811 $this->mCascadingRestrictions
= $pagerestrictions;
2813 $this->mHasCascadingRestrictions
= $sources;
2816 wfProfileOut( __METHOD__
);
2817 return array( $sources, $pagerestrictions );
2821 * Accessor for mRestrictionsLoaded
2823 * @return bool Whether or not the page's restrictions have already been
2824 * loaded from the database
2827 public function areRestrictionsLoaded() {
2828 return $this->mRestrictionsLoaded
;
2832 * Accessor/initialisation for mRestrictions
2834 * @param string $action Action that permission needs to be checked for
2835 * @return array Restriction levels needed to take the action. All levels
2838 public function getRestrictions( $action ) {
2839 if ( !$this->mRestrictionsLoaded
) {
2840 $this->loadRestrictions();
2842 return isset( $this->mRestrictions
[$action] )
2843 ?
$this->mRestrictions
[$action]
2848 * Accessor/initialisation for mRestrictions
2850 * @return array Keys are actions, values are arrays as returned by
2851 * Title::getRestrictions()
2854 public function getAllRestrictions() {
2855 if ( !$this->mRestrictionsLoaded
) {
2856 $this->loadRestrictions();
2858 return $this->mRestrictions
;
2862 * Get the expiry time for the restriction against a given action
2864 * @param string $action
2865 * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever
2866 * or not protected at all, or false if the action is not recognised.
2868 public function getRestrictionExpiry( $action ) {
2869 if ( !$this->mRestrictionsLoaded
) {
2870 $this->loadRestrictions();
2872 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2876 * Returns cascading restrictions for the current article
2880 function areRestrictionsCascading() {
2881 if ( !$this->mRestrictionsLoaded
) {
2882 $this->loadRestrictions();
2885 return $this->mCascadeRestriction
;
2889 * Loads a string into mRestrictions array
2891 * @param ResultWrapper $res Resource restrictions as an SQL result.
2892 * @param string $oldFashionedRestrictions Comma-separated list of page
2893 * restrictions from page table (pre 1.10)
2895 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2898 foreach ( $res as $row ) {
2902 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2906 * Compiles list of active page restrictions from both page table (pre 1.10)
2907 * and page_restrictions table for this existing page.
2908 * Public for usage by LiquidThreads.
2910 * @param array $rows Array of db result objects
2911 * @param string $oldFashionedRestrictions Comma-separated list of page
2912 * restrictions from page table (pre 1.10)
2914 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2916 $dbr = wfGetDB( DB_SLAVE
);
2918 $restrictionTypes = $this->getRestrictionTypes();
2920 foreach ( $restrictionTypes as $type ) {
2921 $this->mRestrictions
[$type] = array();
2922 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2925 $this->mCascadeRestriction
= false;
2927 # Backwards-compatibility: also load the restrictions from the page record (old format).
2929 if ( $oldFashionedRestrictions === null ) {
2930 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2931 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2934 if ( $oldFashionedRestrictions != '' ) {
2936 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2937 $temp = explode( '=', trim( $restrict ) );
2938 if ( count( $temp ) == 1 ) {
2939 // old old format should be treated as edit/move restriction
2940 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2941 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2943 $restriction = trim( $temp[1] );
2944 if ( $restriction != '' ) { //some old entries are empty
2945 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2950 $this->mOldRestrictions
= true;
2954 if ( count( $rows ) ) {
2955 # Current system - load second to make them override.
2956 $now = wfTimestampNow();
2957 $purgeExpired = false;
2959 # Cycle through all the restrictions.
2960 foreach ( $rows as $row ) {
2962 // Don't take care of restrictions types that aren't allowed
2963 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2967 // This code should be refactored, now that it's being used more generally,
2968 // But I don't really see any harm in leaving it in Block for now -werdna
2969 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2971 // Only apply the restrictions if they haven't expired!
2972 if ( !$expiry ||
$expiry > $now ) {
2973 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2974 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2976 $this->mCascadeRestriction |
= $row->pr_cascade
;
2978 // Trigger a lazy purge of expired restrictions
2979 $purgeExpired = true;
2983 if ( $purgeExpired ) {
2984 Title
::purgeExpiredRestrictions();
2988 $this->mRestrictionsLoaded
= true;
2992 * Load restrictions from the page_restrictions table
2994 * @param string $oldFashionedRestrictions Comma-separated list of page
2995 * restrictions from page table (pre 1.10)
2997 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2999 if ( !$this->mRestrictionsLoaded
) {
3000 if ( $this->exists() ) {
3001 $dbr = wfGetDB( DB_SLAVE
);
3003 $res = $dbr->select(
3004 'page_restrictions',
3005 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
3006 array( 'pr_page' => $this->getArticleID() ),
3010 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
3012 $title_protection = $this->getTitleProtection();
3014 if ( $title_protection ) {
3015 $now = wfTimestampNow();
3016 $expiry = $wgContLang->formatExpiry( $title_protection['expiry'], TS_MW
);
3018 if ( !$expiry ||
$expiry > $now ) {
3019 // Apply the restrictions
3020 $this->mRestrictionsExpiry
['create'] = $expiry;
3021 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['permission'] ) );
3022 } else { // Get rid of the old restrictions
3023 Title
::purgeExpiredRestrictions();
3024 $this->mTitleProtection
= false;
3027 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
3029 $this->mRestrictionsLoaded
= true;
3035 * Flush the protection cache in this object and force reload from the database.
3036 * This is used when updating protection from WikiPage::doUpdateRestrictions().
3038 public function flushRestrictions() {
3039 $this->mRestrictionsLoaded
= false;
3040 $this->mTitleProtection
= null;
3044 * Purge expired restrictions from the page_restrictions table
3046 static function purgeExpiredRestrictions() {
3047 if ( wfReadOnly() ) {
3051 $method = __METHOD__
;
3052 $dbw = wfGetDB( DB_MASTER
);
3053 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
3055 'page_restrictions',
3056 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3061 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
3068 * Does this have subpages? (Warning, usually requires an extra DB query.)
3072 public function hasSubpages() {
3073 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
3078 # We dynamically add a member variable for the purpose of this method
3079 # alone to cache the result. There's no point in having it hanging
3080 # around uninitialized in every Title object; therefore we only add it
3081 # if needed and don't declare it statically.
3082 if ( $this->mHasSubpages
=== null ) {
3083 $this->mHasSubpages
= false;
3084 $subpages = $this->getSubpages( 1 );
3085 if ( $subpages instanceof TitleArray
) {
3086 $this->mHasSubpages
= (bool)$subpages->count();
3090 return $this->mHasSubpages
;
3094 * Get all subpages of this page.
3096 * @param int $limit Maximum number of subpages to fetch; -1 for no limit
3097 * @return TitleArray|array TitleArray, or empty array if this page's namespace
3098 * doesn't allow subpages
3100 public function getSubpages( $limit = -1 ) {
3101 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3105 $dbr = wfGetDB( DB_SLAVE
);
3106 $conds['page_namespace'] = $this->getNamespace();
3107 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3109 if ( $limit > -1 ) {
3110 $options['LIMIT'] = $limit;
3112 $this->mSubpages
= TitleArray
::newFromResult(
3113 $dbr->select( 'page',
3114 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3120 return $this->mSubpages
;
3124 * Is there a version of this page in the deletion archive?
3126 * @return int The number of archived revisions
3128 public function isDeleted() {
3129 if ( $this->getNamespace() < 0 ) {
3132 $dbr = wfGetDB( DB_SLAVE
);
3134 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3135 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3138 if ( $this->getNamespace() == NS_FILE
) {
3139 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
3140 array( 'fa_name' => $this->getDBkey() ),
3149 * Is there a version of this page in the deletion archive?
3153 public function isDeletedQuick() {
3154 if ( $this->getNamespace() < 0 ) {
3157 $dbr = wfGetDB( DB_SLAVE
);
3158 $deleted = (bool)$dbr->selectField( 'archive', '1',
3159 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3162 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
3163 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3164 array( 'fa_name' => $this->getDBkey() ),
3172 * Get the article ID for this Title from the link cache,
3173 * adding it if necessary
3175 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select
3177 * @return int The ID
3179 public function getArticleID( $flags = 0 ) {
3180 if ( $this->getNamespace() < 0 ) {
3181 $this->mArticleID
= 0;
3182 return $this->mArticleID
;
3184 $linkCache = LinkCache
::singleton();
3185 if ( $flags & self
::GAID_FOR_UPDATE
) {
3186 $oldUpdate = $linkCache->forUpdate( true );
3187 $linkCache->clearLink( $this );
3188 $this->mArticleID
= $linkCache->addLinkObj( $this );
3189 $linkCache->forUpdate( $oldUpdate );
3191 if ( -1 == $this->mArticleID
) {
3192 $this->mArticleID
= $linkCache->addLinkObj( $this );
3195 return $this->mArticleID
;
3199 * Is this an article that is a redirect page?
3200 * Uses link cache, adding it if necessary
3202 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3205 public function isRedirect( $flags = 0 ) {
3206 if ( !is_null( $this->mRedirect
) ) {
3207 return $this->mRedirect
;
3209 # Calling getArticleID() loads the field from cache as needed
3210 if ( !$this->getArticleID( $flags ) ) {
3211 $this->mRedirect
= false;
3212 return $this->mRedirect
;
3215 $linkCache = LinkCache
::singleton();
3216 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3217 if ( $cached === null ) {
3218 # Trust LinkCache's state over our own
3219 # LinkCache is telling us that the page doesn't exist, despite there being cached
3220 # data relating to an existing page in $this->mArticleID. Updaters should clear
3221 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3222 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3223 # LinkCache to refresh its data from the master.
3224 $this->mRedirect
= false;
3225 return $this->mRedirect
;
3228 $this->mRedirect
= (bool)$cached;
3230 return $this->mRedirect
;
3234 * What is the length of this page?
3235 * Uses link cache, adding it if necessary
3237 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3240 public function getLength( $flags = 0 ) {
3241 if ( $this->mLength
!= -1 ) {
3242 return $this->mLength
;
3244 # Calling getArticleID() loads the field from cache as needed
3245 if ( !$this->getArticleID( $flags ) ) {
3247 return $this->mLength
;
3249 $linkCache = LinkCache
::singleton();
3250 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3251 if ( $cached === null ) {
3252 # Trust LinkCache's state over our own, as for isRedirect()
3254 return $this->mLength
;
3257 $this->mLength
= intval( $cached );
3259 return $this->mLength
;
3263 * What is the page_latest field for this page?
3265 * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update
3266 * @return int Int or 0 if the page doesn't exist
3268 public function getLatestRevID( $flags = 0 ) {
3269 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3270 return intval( $this->mLatestID
);
3272 # Calling getArticleID() loads the field from cache as needed
3273 if ( !$this->getArticleID( $flags ) ) {
3274 $this->mLatestID
= 0;
3275 return $this->mLatestID
;
3277 $linkCache = LinkCache
::singleton();
3278 $linkCache->addLinkObj( $this );
3279 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3280 if ( $cached === null ) {
3281 # Trust LinkCache's state over our own, as for isRedirect()
3282 $this->mLatestID
= 0;
3283 return $this->mLatestID
;
3286 $this->mLatestID
= intval( $cached );
3288 return $this->mLatestID
;
3292 * This clears some fields in this object, and clears any associated
3293 * keys in the "bad links" section of the link cache.
3295 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3296 * loading of the new page_id. It's also called from
3297 * WikiPage::doDeleteArticleReal()
3299 * @param int $newid The new Article ID
3301 public function resetArticleID( $newid ) {
3302 $linkCache = LinkCache
::singleton();
3303 $linkCache->clearLink( $this );
3305 if ( $newid === false ) {
3306 $this->mArticleID
= -1;
3308 $this->mArticleID
= intval( $newid );
3310 $this->mRestrictionsLoaded
= false;
3311 $this->mRestrictions
= array();
3312 $this->mRedirect
= null;
3313 $this->mLength
= -1;
3314 $this->mLatestID
= false;
3315 $this->mContentModel
= false;
3316 $this->mEstimateRevisions
= null;
3317 $this->mPageLanguage
= false;
3318 $this->mDbPageLanguage
= null;
3319 $this->mIsBigDeletion
= null;
3323 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3325 * @param string $text Containing title to capitalize
3326 * @param int $ns Namespace index, defaults to NS_MAIN
3327 * @return string Containing capitalized title
3329 public static function capitalize( $text, $ns = NS_MAIN
) {
3332 if ( MWNamespace
::isCapitalized( $ns ) ) {
3333 return $wgContLang->ucfirst( $text );
3340 * Secure and split - main initialisation function for this object
3342 * Assumes that mDbkeyform has been set, and is urldecoded
3343 * and uses underscores, but not otherwise munged. This function
3344 * removes illegal characters, splits off the interwiki and
3345 * namespace prefixes, sets the other forms, and canonicalizes
3348 * @return bool True on success
3350 private function secureAndSplit() {
3352 $this->mInterwiki
= '';
3353 $this->mFragment
= '';
3354 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3356 $dbkey = $this->mDbkeyform
;
3359 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3360 // the parsing code with Title, while avoiding massive refactoring.
3361 // @todo: get rid of secureAndSplit, refactor parsing code.
3362 $titleParser = self
::getTitleParser();
3363 $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3364 } catch ( MalformedTitleException
$ex ) {
3369 $this->setFragment( '#' . $parts['fragment'] );
3370 $this->mInterwiki
= $parts['interwiki'];
3371 $this->mLocalInterwiki
= $parts['local_interwiki'];
3372 $this->mNamespace
= $parts['namespace'];
3373 $this->mUserCaseDBKey
= $parts['user_case_dbkey'];
3375 $this->mDbkeyform
= $parts['dbkey'];
3376 $this->mUrlform
= wfUrlencode( $this->mDbkeyform
);
3377 $this->mTextform
= str_replace( '_', ' ', $this->mDbkeyform
);
3379 # We already know that some pages won't be in the database!
3380 if ( $this->isExternal() ||
$this->mNamespace
== NS_SPECIAL
) {
3381 $this->mArticleID
= 0;
3388 * Get an array of Title objects linking to this Title
3389 * Also stores the IDs in the link cache.
3391 * WARNING: do not use this function on arbitrary user-supplied titles!
3392 * On heavily-used templates it will max out the memory.
3394 * @param array $options May be FOR UPDATE
3395 * @param string $table Table name
3396 * @param string $prefix Fields prefix
3397 * @return Title[] Array of Title objects linking here
3399 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3400 if ( count( $options ) > 0 ) {
3401 $db = wfGetDB( DB_MASTER
);
3403 $db = wfGetDB( DB_SLAVE
);
3407 array( 'page', $table ),
3408 self
::getSelectFields(),
3410 "{$prefix}_from=page_id",
3411 "{$prefix}_namespace" => $this->getNamespace(),
3412 "{$prefix}_title" => $this->getDBkey() ),
3418 if ( $res->numRows() ) {
3419 $linkCache = LinkCache
::singleton();
3420 foreach ( $res as $row ) {
3421 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3423 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3424 $retVal[] = $titleObj;
3432 * Get an array of Title objects using this Title as a template
3433 * Also stores the IDs in the link cache.
3435 * WARNING: do not use this function on arbitrary user-supplied titles!
3436 * On heavily-used templates it will max out the memory.
3438 * @param array $options May be FOR UPDATE
3439 * @return Title[] Array of Title the Title objects linking here
3441 public function getTemplateLinksTo( $options = array() ) {
3442 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3446 * Get an array of Title objects linked from this Title
3447 * Also stores the IDs in the link cache.
3449 * WARNING: do not use this function on arbitrary user-supplied titles!
3450 * On heavily-used templates it will max out the memory.
3452 * @param array $options May be FOR UPDATE
3453 * @param string $table Table name
3454 * @param string $prefix Fields prefix
3455 * @return array Array of Title objects linking here
3457 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3458 global $wgContentHandlerUseDB;
3460 $id = $this->getArticleID();
3462 # If the page doesn't exist; there can't be any link from this page
3467 if ( count( $options ) > 0 ) {
3468 $db = wfGetDB( DB_MASTER
);
3470 $db = wfGetDB( DB_SLAVE
);
3473 $namespaceFiled = "{$prefix}_namespace";
3474 $titleField = "{$prefix}_title";
3485 if ( $wgContentHandlerUseDB ) {
3486 $fields[] = 'page_content_model';
3490 array( $table, 'page' ),
3492 array( "{$prefix}_from" => $id ),
3495 array( 'page' => array(
3497 array( "page_namespace=$namespaceFiled", "page_title=$titleField" )
3502 if ( $res->numRows() ) {
3503 $linkCache = LinkCache
::singleton();
3504 foreach ( $res as $row ) {
3505 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3507 if ( $row->page_id
) {
3508 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3510 $linkCache->addBadLinkObj( $titleObj );
3512 $retVal[] = $titleObj;
3520 * Get an array of Title objects used on this Title as a template
3521 * Also stores the IDs in the link cache.
3523 * WARNING: do not use this function on arbitrary user-supplied titles!
3524 * On heavily-used templates it will max out the memory.
3526 * @param array $options May be FOR UPDATE
3527 * @return Title[] Array of Title the Title objects used here
3529 public function getTemplateLinksFrom( $options = array() ) {
3530 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3534 * Get an array of Title objects referring to non-existent articles linked
3537 * @todo check if needed (used only in SpecialBrokenRedirects.php, and
3538 * should use redirect table in this case).
3539 * @return Title[] Array of Title the Title objects
3541 public function getBrokenLinksFrom() {
3542 if ( $this->getArticleID() == 0 ) {
3543 # All links from article ID 0 are false positives
3547 $dbr = wfGetDB( DB_SLAVE
);
3548 $res = $dbr->select(
3549 array( 'page', 'pagelinks' ),
3550 array( 'pl_namespace', 'pl_title' ),
3552 'pl_from' => $this->getArticleID(),
3553 'page_namespace IS NULL'
3555 __METHOD__
, array(),
3559 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3565 foreach ( $res as $row ) {
3566 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3572 * Get a list of URLs to purge from the Squid cache when this
3575 * @return string[] Array of String the URLs
3577 public function getSquidURLs() {
3579 $this->getInternalURL(),
3580 $this->getInternalURL( 'action=history' )
3583 $pageLang = $this->getPageLanguage();
3584 if ( $pageLang->hasVariants() ) {
3585 $variants = $pageLang->getVariants();
3586 foreach ( $variants as $vCode ) {
3587 $urls[] = $this->getInternalURL( '', $vCode );
3591 // If we are looking at a css/js user subpage, purge the action=raw.
3592 if ( $this->isJsSubpage() ) {
3593 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3594 } elseif ( $this->isCssSubpage() ) {
3595 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3598 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3603 * Purge all applicable Squid URLs
3605 public function purgeSquid() {
3607 if ( $wgUseSquid ) {
3608 $urls = $this->getSquidURLs();
3609 $u = new SquidUpdate( $urls );
3615 * Move this page without authentication
3617 * @deprecated since 1.25 use MovePage class instead
3618 * @param Title $nt The new page Title
3619 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3621 public function moveNoAuth( &$nt ) {
3622 wfDeprecated( __METHOD__
, '1.25' );
3623 return $this->moveTo( $nt, false );
3627 * Check whether a given move operation would be valid.
3628 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3630 * @deprecated since 1.25, use MovePage's methods instead
3631 * @param Title $nt The new title
3632 * @param bool $auth Ignored
3633 * @param string $reason Is the log summary of the move, used for spam checking
3634 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3636 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3639 if ( !( $nt instanceof Title
) ) {
3640 // Normally we'd add this to $errors, but we'll get
3641 // lots of syntax errors if $nt is not an object
3642 return array( array( 'badtitletext' ) );
3645 $mp = new MovePage( $this, $nt );
3646 $errors = wfMergeErrorArrays(
3647 $mp->isValidMove()->getErrorsArray(),
3648 $mp->checkPermissions( $wgUser, $reason )->getErrorsArray()
3651 return $errors ?
: true;
3655 * Check if the requested move target is a valid file move target
3656 * @todo move this to MovePage
3657 * @param Title $nt Target title
3658 * @return array List of errors
3660 protected function validateFileMoveOperation( $nt ) {
3665 $destFile = wfLocalFile( $nt );
3666 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3667 $errors[] = array( 'file-exists-sharedrepo' );
3674 * Move a title to a new location
3676 * @deprecated since 1.25, use the MovePage class instead
3677 * @param Title $nt The new title
3678 * @param bool $auth Indicates whether $wgUser's permissions
3680 * @param string $reason The reason for the move
3681 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3682 * Ignored if the user doesn't have the suppressredirect right.
3683 * @return array|bool True on success, getUserPermissionsErrors()-like array on failure
3685 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3687 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3688 if ( is_array( $err ) ) {
3689 // Auto-block user's IP if the account was "hard" blocked
3690 $wgUser->spreadAnyEditBlock();
3693 // Check suppressredirect permission
3694 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3695 $createRedirect = true;
3698 $mp = new MovePage( $this, $nt );
3699 $status = $mp->move( $wgUser, $reason, $createRedirect );
3700 if ( $status->isOK() ) {
3703 return $status->getErrorsArray();
3708 * Move this page's subpages to be subpages of $nt
3710 * @param Title $nt Move target
3711 * @param bool $auth Whether $wgUser's permissions should be checked
3712 * @param string $reason The reason for the move
3713 * @param bool $createRedirect Whether to create redirects from the old subpages to
3714 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3715 * @return array Array with old page titles as keys, and strings (new page titles) or
3716 * arrays (errors) as values, or an error array with numeric indices if no pages
3719 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3720 global $wgMaximumMovedPages;
3721 // Check permissions
3722 if ( !$this->userCan( 'move-subpages' ) ) {
3723 return array( 'cant-move-subpages' );
3725 // Do the source and target namespaces support subpages?
3726 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3727 return array( 'namespace-nosubpages',
3728 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3730 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3731 return array( 'namespace-nosubpages',
3732 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3735 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3738 foreach ( $subpages as $oldSubpage ) {
3740 if ( $count > $wgMaximumMovedPages ) {
3741 $retval[$oldSubpage->getPrefixedText()] =
3742 array( 'movepage-max-pages',
3743 $wgMaximumMovedPages );
3747 // We don't know whether this function was called before
3748 // or after moving the root page, so check both
3750 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3751 ||
$oldSubpage->getArticleID() == $nt->getArticleID()
3753 // When moving a page to a subpage of itself,
3754 // don't move it twice
3757 $newPageName = preg_replace(
3758 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3759 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3760 $oldSubpage->getDBkey() );
3761 if ( $oldSubpage->isTalkPage() ) {
3762 $newNs = $nt->getTalkPage()->getNamespace();
3764 $newNs = $nt->getSubjectPage()->getNamespace();
3766 # Bug 14385: we need makeTitleSafe because the new page names may
3767 # be longer than 255 characters.
3768 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3770 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3771 if ( $success === true ) {
3772 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3774 $retval[$oldSubpage->getPrefixedText()] = $success;
3781 * Checks if this page is just a one-rev redirect.
3782 * Adds lock, so don't use just for light purposes.
3786 public function isSingleRevRedirect() {
3787 global $wgContentHandlerUseDB;
3789 $dbw = wfGetDB( DB_MASTER
);
3792 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3793 if ( $wgContentHandlerUseDB ) {
3794 $fields[] = 'page_content_model';
3797 $row = $dbw->selectRow( 'page',
3801 array( 'FOR UPDATE' )
3803 # Cache some fields we may want
3804 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3805 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3806 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3807 $this->mContentModel
= $row && isset( $row->page_content_model
)
3808 ?
strval( $row->page_content_model
)
3811 if ( !$this->mRedirect
) {
3814 # Does the article have a history?
3815 $row = $dbw->selectField( array( 'page', 'revision' ),
3817 array( 'page_namespace' => $this->getNamespace(),
3818 'page_title' => $this->getDBkey(),
3820 'page_latest != rev_id'
3823 array( 'FOR UPDATE' )
3825 # Return true if there was no history
3826 return ( $row === false );
3830 * Checks if $this can be moved to a given Title
3831 * - Selects for update, so don't call it unless you mean business
3833 * @deprecated since 1.25, use MovePage's methods instead
3834 * @param Title $nt The new title to check
3837 public function isValidMoveTarget( $nt ) {
3838 # Is it an existing file?
3839 if ( $nt->getNamespace() == NS_FILE
) {
3840 $file = wfLocalFile( $nt );
3841 if ( $file->exists() ) {
3842 wfDebug( __METHOD__
. ": file exists\n" );
3846 # Is it a redirect with no history?
3847 if ( !$nt->isSingleRevRedirect() ) {
3848 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3851 # Get the article text
3852 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
3853 if ( !is_object( $rev ) ) {
3856 $content = $rev->getContent();
3857 # Does the redirect point to the source?
3858 # Or is it a broken self-redirect, usually caused by namespace collisions?
3859 $redirTitle = $content ?
$content->getRedirectTarget() : null;
3861 if ( $redirTitle ) {
3862 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3863 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
3864 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3870 # Fail safe (not a redirect after all. strange.)
3871 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
3872 " is a redirect, but it doesn't contain a valid redirect.\n" );
3878 * Get categories to which this Title belongs and return an array of
3879 * categories' names.
3881 * @return array Array of parents in the form:
3882 * $parent => $currentarticle
3884 public function getParentCategories() {
3889 $titleKey = $this->getArticleID();
3891 if ( $titleKey === 0 ) {
3895 $dbr = wfGetDB( DB_SLAVE
);
3897 $res = $dbr->select(
3900 array( 'cl_from' => $titleKey ),
3904 if ( $res->numRows() > 0 ) {
3905 foreach ( $res as $row ) {
3906 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
3907 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3914 * Get a tree of parent categories
3916 * @param array $children Array with the children in the keys, to check for circular refs
3917 * @return array Tree of parent categories
3919 public function getParentCategoryTree( $children = array() ) {
3921 $parents = $this->getParentCategories();
3924 foreach ( $parents as $parent => $current ) {
3925 if ( array_key_exists( $parent, $children ) ) {
3926 # Circular reference
3927 $stack[$parent] = array();
3929 $nt = Title
::newFromText( $parent );
3931 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3941 * Get an associative array for selecting this title from
3944 * @return array Array suitable for the $where parameter of DB::select()
3946 public function pageCond() {
3947 if ( $this->mArticleID
> 0 ) {
3948 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3949 return array( 'page_id' => $this->mArticleID
);
3951 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3956 * Get the revision ID of the previous revision
3958 * @param int $revId Revision ID. Get the revision that was before this one.
3959 * @param int $flags Title::GAID_FOR_UPDATE
3960 * @return int|bool Old revision ID, or false if none exists
3962 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3963 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3964 $revId = $db->selectField( 'revision', 'rev_id',
3966 'rev_page' => $this->getArticleID( $flags ),
3967 'rev_id < ' . intval( $revId )
3970 array( 'ORDER BY' => 'rev_id DESC' )
3973 if ( $revId === false ) {
3976 return intval( $revId );
3981 * Get the revision ID of the next revision
3983 * @param int $revId Revision ID. Get the revision that was after this one.
3984 * @param int $flags Title::GAID_FOR_UPDATE
3985 * @return int|bool Next revision ID, or false if none exists
3987 public function getNextRevisionID( $revId, $flags = 0 ) {
3988 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3989 $revId = $db->selectField( 'revision', 'rev_id',
3991 'rev_page' => $this->getArticleID( $flags ),
3992 'rev_id > ' . intval( $revId )
3995 array( 'ORDER BY' => 'rev_id' )
3998 if ( $revId === false ) {
4001 return intval( $revId );
4006 * Get the first revision of the page
4008 * @param int $flags Title::GAID_FOR_UPDATE
4009 * @return Revision|null If page doesn't exist
4011 public function getFirstRevision( $flags = 0 ) {
4012 $pageId = $this->getArticleID( $flags );
4014 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4015 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4016 array( 'rev_page' => $pageId ),
4018 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4021 return new Revision( $row );
4028 * Get the oldest revision timestamp of this page
4030 * @param int $flags Title::GAID_FOR_UPDATE
4031 * @return string MW timestamp
4033 public function getEarliestRevTime( $flags = 0 ) {
4034 $rev = $this->getFirstRevision( $flags );
4035 return $rev ?
$rev->getTimestamp() : null;
4039 * Check if this is a new page
4043 public function isNewPage() {
4044 $dbr = wfGetDB( DB_SLAVE
);
4045 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4049 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4053 public function isBigDeletion() {
4054 global $wgDeleteRevisionsLimit;
4056 if ( !$wgDeleteRevisionsLimit ) {
4060 if ( $this->mIsBigDeletion
=== null ) {
4061 $dbr = wfGetDB( DB_SLAVE
);
4063 $innerQuery = $dbr->selectSQLText(
4066 array( 'rev_page' => $this->getArticleID() ),
4068 array( 'LIMIT' => $wgDeleteRevisionsLimit +
1 )
4071 $revCount = $dbr->query(
4072 'SELECT COUNT(*) FROM (' . $innerQuery . ') AS innerQuery',
4075 $revCount = $revCount->fetchRow();
4076 $revCount = $revCount['COUNT(*)'];
4078 $this->mIsBigDeletion
= $revCount > $wgDeleteRevisionsLimit;
4081 return $this->mIsBigDeletion
;
4085 * Get the approximate revision count of this page.
4089 public function estimateRevisionCount() {
4090 if ( !$this->exists() ) {
4094 if ( $this->mEstimateRevisions
=== null ) {
4095 $dbr = wfGetDB( DB_SLAVE
);
4096 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4097 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4100 return $this->mEstimateRevisions
;
4104 * Get the number of revisions between the given revision.
4105 * Used for diffs and other things that really need it.
4107 * @param int|Revision $old Old revision or rev ID (first before range)
4108 * @param int|Revision $new New revision or rev ID (first after range)
4109 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4110 * @return int Number of revisions between these revisions.
4112 public function countRevisionsBetween( $old, $new, $max = null ) {
4113 if ( !( $old instanceof Revision
) ) {
4114 $old = Revision
::newFromTitle( $this, (int)$old );
4116 if ( !( $new instanceof Revision
) ) {
4117 $new = Revision
::newFromTitle( $this, (int)$new );
4119 if ( !$old ||
!$new ) {
4120 return 0; // nothing to compare
4122 $dbr = wfGetDB( DB_SLAVE
);
4124 'rev_page' => $this->getArticleID(),
4125 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4126 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4128 if ( $max !== null ) {
4129 $res = $dbr->select( 'revision', '1',
4132 array( 'LIMIT' => $max +
1 ) // extra to detect truncation
4134 return $res->numRows();
4136 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__
);
4141 * Get the authors between the given revisions or revision IDs.
4142 * Used for diffs and other things that really need it.
4146 * @param int|Revision $old Old revision or rev ID (first before range by default)
4147 * @param int|Revision $new New revision or rev ID (first after range by default)
4148 * @param int $limit Maximum number of authors
4149 * @param string|array $options (Optional): Single option, or an array of options:
4150 * 'include_old' Include $old in the range; $new is excluded.
4151 * 'include_new' Include $new in the range; $old is excluded.
4152 * 'include_both' Include both $old and $new in the range.
4153 * Unknown option values are ignored.
4154 * @return array|null Names of revision authors in the range; null if not both revisions exist
4156 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4157 if ( !( $old instanceof Revision
) ) {
4158 $old = Revision
::newFromTitle( $this, (int)$old );
4160 if ( !( $new instanceof Revision
) ) {
4161 $new = Revision
::newFromTitle( $this, (int)$new );
4163 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4164 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4165 // in the sanity check below?
4166 if ( !$old ||
!$new ) {
4167 return null; // nothing to compare
4172 $options = (array)$options;
4173 if ( in_array( 'include_old', $options ) ) {
4176 if ( in_array( 'include_new', $options ) ) {
4179 if ( in_array( 'include_both', $options ) ) {
4183 // No DB query needed if $old and $new are the same or successive revisions:
4184 if ( $old->getId() === $new->getId() ) {
4185 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
array() : array( $old->getRawUserText() );
4186 } elseif ( $old->getId() === $new->getParentId() ) {
4187 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4188 $authors[] = $old->getRawUserText();
4189 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4190 $authors[] = $new->getRawUserText();
4192 } elseif ( $old_cmp === '>=' ) {
4193 $authors[] = $old->getRawUserText();
4194 } elseif ( $new_cmp === '<=' ) {
4195 $authors[] = $new->getRawUserText();
4199 $dbr = wfGetDB( DB_SLAVE
);
4200 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4202 'rev_page' => $this->getArticleID(),
4203 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4204 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4206 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4208 foreach ( $res as $row ) {
4209 $authors[] = $row->rev_user_text
;
4215 * Get the number of authors between the given revisions or revision IDs.
4216 * Used for diffs and other things that really need it.
4218 * @param int|Revision $old Old revision or rev ID (first before range by default)
4219 * @param int|Revision $new New revision or rev ID (first after range by default)
4220 * @param int $limit Maximum number of authors
4221 * @param string|array $options (Optional): Single option, or an array of options:
4222 * 'include_old' Include $old in the range; $new is excluded.
4223 * 'include_new' Include $new in the range; $old is excluded.
4224 * 'include_both' Include both $old and $new in the range.
4225 * Unknown option values are ignored.
4226 * @return int Number of revision authors in the range; zero if not both revisions exist
4228 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4229 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4230 return $authors ?
count( $authors ) : 0;
4234 * Compare with another title.
4236 * @param Title $title
4239 public function equals( Title
$title ) {
4240 // Note: === is necessary for proper matching of number-like titles.
4241 return $this->getInterwiki() === $title->getInterwiki()
4242 && $this->getNamespace() == $title->getNamespace()
4243 && $this->getDBkey() === $title->getDBkey();
4247 * Check if this title is a subpage of another title
4249 * @param Title $title
4252 public function isSubpageOf( Title
$title ) {
4253 return $this->getInterwiki() === $title->getInterwiki()
4254 && $this->getNamespace() == $title->getNamespace()
4255 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4259 * Check if page exists. For historical reasons, this function simply
4260 * checks for the existence of the title in the page table, and will
4261 * thus return false for interwiki links, special pages and the like.
4262 * If you want to know if a title can be meaningfully viewed, you should
4263 * probably call the isKnown() method instead.
4267 public function exists() {
4268 $exists = $this->getArticleID() != 0;
4269 wfRunHooks( 'TitleExists', array( $this, &$exists ) );
4274 * Should links to this title be shown as potentially viewable (i.e. as
4275 * "bluelinks"), even if there's no record by this title in the page
4278 * This function is semi-deprecated for public use, as well as somewhat
4279 * misleadingly named. You probably just want to call isKnown(), which
4280 * calls this function internally.
4282 * (ISSUE: Most of these checks are cheap, but the file existence check
4283 * can potentially be quite expensive. Including it here fixes a lot of
4284 * existing code, but we might want to add an optional parameter to skip
4285 * it and any other expensive checks.)
4289 public function isAlwaysKnown() {
4293 * Allows overriding default behavior for determining if a page exists.
4294 * If $isKnown is kept as null, regular checks happen. If it's
4295 * a boolean, this value is returned by the isKnown method.
4299 * @param Title $title
4300 * @param bool|null $isKnown
4302 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4304 if ( !is_null( $isKnown ) ) {
4308 if ( $this->isExternal() ) {
4309 return true; // any interwiki link might be viewable, for all we know
4312 switch ( $this->mNamespace
) {
4315 // file exists, possibly in a foreign repo
4316 return (bool)wfFindFile( $this );
4318 // valid special page
4319 return SpecialPageFactory
::exists( $this->getDBkey() );
4321 // selflink, possibly with fragment
4322 return $this->mDbkeyform
== '';
4324 // known system message
4325 return $this->hasSourceText() !== false;
4332 * Does this title refer to a page that can (or might) be meaningfully
4333 * viewed? In particular, this function may be used to determine if
4334 * links to the title should be rendered as "bluelinks" (as opposed to
4335 * "redlinks" to non-existent pages).
4336 * Adding something else to this function will cause inconsistency
4337 * since LinkHolderArray calls isAlwaysKnown() and does its own
4338 * page existence check.
4342 public function isKnown() {
4343 return $this->isAlwaysKnown() ||
$this->exists();
4347 * Does this page have source text?
4351 public function hasSourceText() {
4352 if ( $this->exists() ) {
4356 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4357 // If the page doesn't exist but is a known system message, default
4358 // message content will be displayed, same for language subpages-
4359 // Use always content language to avoid loading hundreds of languages
4360 // to get the link color.
4362 list( $name, ) = MessageCache
::singleton()->figureMessage(
4363 $wgContLang->lcfirst( $this->getText() )
4365 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4366 return $message->exists();
4373 * Get the default message text or false if the message doesn't exist
4375 * @return string|bool
4377 public function getDefaultMessageText() {
4380 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4384 list( $name, $lang ) = MessageCache
::singleton()->figureMessage(
4385 $wgContLang->lcfirst( $this->getText() )
4387 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4389 if ( $message->exists() ) {
4390 return $message->plain();
4397 * Updates page_touched for this page; called from LinksUpdate.php
4399 * @return bool True if the update succeeded
4401 public function invalidateCache() {
4402 if ( wfReadOnly() ) {
4406 if ( $this->mArticleID
=== 0 ) {
4407 return true; // avoid gap locking if we know it's not there
4410 $method = __METHOD__
;
4411 $dbw = wfGetDB( DB_MASTER
);
4412 $conds = $this->pageCond();
4413 $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) {
4416 array( 'page_touched' => $dbw->timestamp() ),
4426 * Update page_touched timestamps and send squid purge messages for
4427 * pages linking to this title. May be sent to the job queue depending
4428 * on the number of links. Typically called on create and delete.
4430 public function touchLinks() {
4431 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4434 if ( $this->getNamespace() == NS_CATEGORY
) {
4435 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4441 * Get the last touched timestamp
4443 * @param DatabaseBase $db Optional db
4444 * @return string Last-touched timestamp
4446 public function getTouched( $db = null ) {
4447 if ( $db === null ) {
4448 $db = wfGetDB( DB_SLAVE
);
4450 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4455 * Get the timestamp when this page was updated since the user last saw it.
4458 * @return string|null
4460 public function getNotificationTimestamp( $user = null ) {
4461 global $wgUser, $wgShowUpdatedMarker;
4462 // Assume current user if none given
4466 // Check cache first
4467 $uid = $user->getId();
4468 // avoid isset here, as it'll return false for null entries
4469 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4470 return $this->mNotificationTimestamp
[$uid];
4472 if ( !$uid ||
!$wgShowUpdatedMarker ||
!$user->isAllowed( 'viewmywatchlist' ) ) {
4473 $this->mNotificationTimestamp
[$uid] = false;
4474 return $this->mNotificationTimestamp
[$uid];
4476 // Don't cache too much!
4477 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4478 $this->mNotificationTimestamp
= array();
4480 $dbr = wfGetDB( DB_SLAVE
);
4481 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4482 'wl_notificationtimestamp',
4484 'wl_user' => $user->getId(),
4485 'wl_namespace' => $this->getNamespace(),
4486 'wl_title' => $this->getDBkey(),
4490 return $this->mNotificationTimestamp
[$uid];
4494 * Generate strings used for xml 'id' names in monobook tabs
4496 * @param string $prepend Defaults to 'nstab-'
4497 * @return string XML 'id' name
4499 public function getNamespaceKey( $prepend = 'nstab-' ) {
4501 // Gets the subject namespace if this title
4502 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4503 // Checks if canonical namespace name exists for namespace
4504 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4505 // Uses canonical namespace name
4506 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4508 // Uses text of namespace
4509 $namespaceKey = $this->getSubjectNsText();
4511 // Makes namespace key lowercase
4512 $namespaceKey = $wgContLang->lc( $namespaceKey );
4514 if ( $namespaceKey == '' ) {
4515 $namespaceKey = 'main';
4517 // Changes file to image for backwards compatibility
4518 if ( $namespaceKey == 'file' ) {
4519 $namespaceKey = 'image';
4521 return $prepend . $namespaceKey;
4525 * Get all extant redirects to this Title
4527 * @param int|null $ns Single namespace to consider; null to consider all namespaces
4528 * @return Title[] Array of Title redirects to this title
4530 public function getRedirectsHere( $ns = null ) {
4533 $dbr = wfGetDB( DB_SLAVE
);
4535 'rd_namespace' => $this->getNamespace(),
4536 'rd_title' => $this->getDBkey(),
4539 if ( $this->isExternal() ) {
4540 $where['rd_interwiki'] = $this->getInterwiki();
4542 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4544 if ( !is_null( $ns ) ) {
4545 $where['page_namespace'] = $ns;
4548 $res = $dbr->select(
4549 array( 'redirect', 'page' ),
4550 array( 'page_namespace', 'page_title' ),
4555 foreach ( $res as $row ) {
4556 $redirs[] = self
::newFromRow( $row );
4562 * Check if this Title is a valid redirect target
4566 public function isValidRedirectTarget() {
4567 global $wgInvalidRedirectTargets;
4569 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4570 if ( $this->isSpecial( 'Userlogout' ) ) {
4574 foreach ( $wgInvalidRedirectTargets as $target ) {
4575 if ( $this->isSpecial( $target ) ) {
4584 * Get a backlink cache object
4586 * @return BacklinkCache
4588 public function getBacklinkCache() {
4589 return BacklinkCache
::get( $this );
4593 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4597 public function canUseNoindex() {
4598 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4600 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4601 ?
$wgContentNamespaces
4602 : $wgExemptFromUserRobotsControl;
4604 return !in_array( $this->mNamespace
, $bannedNamespaces );
4609 * Returns the raw sort key to be used for categories, with the specified
4610 * prefix. This will be fed to Collation::getSortKey() to get a
4611 * binary sortkey that can be used for actual sorting.
4613 * @param string $prefix The prefix to be used, specified using
4614 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4618 public function getCategorySortkey( $prefix = '' ) {
4619 $unprefixed = $this->getText();
4621 // Anything that uses this hook should only depend
4622 // on the Title object passed in, and should probably
4623 // tell the users to run updateCollations.php --force
4624 // in order to re-sort existing category relations.
4625 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4626 if ( $prefix !== '' ) {
4627 # Separate with a line feed, so the unprefixed part is only used as
4628 # a tiebreaker when two pages have the exact same prefix.
4629 # In UCA, tab is the only character that can sort above LF
4630 # so we strip both of them from the original prefix.
4631 $prefix = strtr( $prefix, "\n\t", ' ' );
4632 return "$prefix\n$unprefixed";
4638 * Get the language in which the content of this page is written in
4639 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4640 * e.g. $wgLang (such as special pages, which are in the user language).
4645 public function getPageLanguage() {
4646 global $wgLang, $wgLanguageCode;
4647 wfProfileIn( __METHOD__
);
4648 if ( $this->isSpecialPage() ) {
4649 // special pages are in the user language
4650 wfProfileOut( __METHOD__
);
4654 // Checking if DB language is set
4655 if ( $this->mDbPageLanguage
) {
4656 wfProfileOut( __METHOD__
);
4657 return wfGetLangObj( $this->mDbPageLanguage
);
4660 if ( !$this->mPageLanguage ||
$this->mPageLanguage
[1] !== $wgLanguageCode ) {
4661 // Note that this may depend on user settings, so the cache should
4662 // be only per-request.
4663 // NOTE: ContentHandler::getPageLanguage() may need to load the
4664 // content to determine the page language!
4665 // Checking $wgLanguageCode hasn't changed for the benefit of unit
4667 $contentHandler = ContentHandler
::getForTitle( $this );
4668 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4669 $this->mPageLanguage
= array( $langObj->getCode(), $wgLanguageCode );
4671 $langObj = wfGetLangObj( $this->mPageLanguage
[0] );
4674 wfProfileOut( __METHOD__
);
4679 * Get the language in which the content of this page is written when
4680 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4681 * e.g. $wgLang (such as special pages, which are in the user language).
4686 public function getPageViewLanguage() {
4689 if ( $this->isSpecialPage() ) {
4690 // If the user chooses a variant, the content is actually
4691 // in a language whose code is the variant code.
4692 $variant = $wgLang->getPreferredVariant();
4693 if ( $wgLang->getCode() !== $variant ) {
4694 return Language
::factory( $variant );
4700 // @note Can't be cached persistently, depends on user settings.
4701 // @note ContentHandler::getPageViewLanguage() may need to load the
4702 // content to determine the page language!
4703 $contentHandler = ContentHandler
::getForTitle( $this );
4704 $pageLang = $contentHandler->getPageViewLanguage( $this );
4709 * Get a list of rendered edit notices for this page.
4711 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4712 * they will already be wrapped in paragraphs.
4715 * @param int $oldid Revision ID that's being edited
4718 public function getEditNotices( $oldid = 0 ) {
4721 # Optional notices on a per-namespace and per-page basis
4722 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4723 $editnotice_ns_message = wfMessage( $editnotice_ns );
4724 if ( $editnotice_ns_message->exists() ) {
4725 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4727 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4728 $parts = explode( '/', $this->getDBkey() );
4729 $editnotice_base = $editnotice_ns;
4730 while ( count( $parts ) > 0 ) {
4731 $editnotice_base .= '-' . array_shift( $parts );
4732 $editnotice_base_msg = wfMessage( $editnotice_base );
4733 if ( $editnotice_base_msg->exists() ) {
4734 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4738 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4739 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4740 $editnoticeMsg = wfMessage( $editnoticeText );
4741 if ( $editnoticeMsg->exists() ) {
4742 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4746 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );