7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
14 * Title::newFromText maintains a cache to avoid expensive re-normalization of
15 * commonly used titles. On a batch operation this can become a memory leak
16 * if not bounded. After hitting this many titles reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
21 * Constants for pr_cascade bitfield
23 define( 'CASCADE', 1 );
27 * - Represents a title, which may contain an interwiki designation or namespace
28 * - Can fetch various kinds of data from the database, albeit inefficiently.
33 * Static cache variables
35 static private $titleCache=array();
36 static private $interwikiCache=array();
40 * All member variables should be considered private
41 * Please use the accessor functions
48 var $mTextform = ''; # Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; # URL-encoded form of the main part
50 var $mDbkeyform = ''; # Main part with underscores
51 var $mUserCaseDBKey; # DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN
; # Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; # Interwiki prefix (or null string)
54 var $mFragment; # Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; # Article ID, fetched from the link cache on demand
56 var $mLatestID = false; # ID of most recent revision
57 var $mRestrictions = array(); # Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; # Cascade restrictions on this page to included templates and images?
60 var $mRestrictionsExpiry; # When do the restrictions on this page expire?
61 var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page?
62 var $mCascadeRestrictionSources; # Where are the cascading restrictions coming from on this page?
63 var $mRestrictionsLoaded = false; # Boolean for initialisation on demand
64 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
65 # Don't change the following default, NS_MAIN is hardcoded in several
66 # places. See bug 696.
67 var $mDefaultNamespace = NS_MAIN
; # Namespace index when there is no namespace
68 # Zero except in {{transclusion}} tags
69 var $mWatched = null; # Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
70 var $mLength = -1; # The page length, 0 for special pages
71 var $mRedirect = null; # Is the article at this title a redirect?
79 /* private */ function __construct() {}
82 * Create a new Title from a prefixed DB key
83 * @param string $key The database key, which has underscores
84 * instead of spaces, possibly including namespace and
86 * @return Title the new object, or NULL on an error
88 public static function newFromDBkey( $key ) {
90 $t->mDbkeyform
= $key;
91 if( $t->secureAndSplit() )
98 * Create a new Title from text, such as what one would
99 * find in a link. Decodes any HTML entities in the text.
101 * @param string $text the link text; spaces, prefixes,
102 * and an initial ':' indicating the main namespace
104 * @param int $defaultNamespace the namespace to use if
105 * none is specified by a prefix
106 * @return Title the new object, or NULL on an error
108 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
109 if( is_object( $text ) ) {
110 throw new MWException( 'Title::newFromText given an object' );
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
119 * In theory these are value objects and won't get changed...
121 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
122 return Title
::$titleCache[$text];
126 * Convert things like é ā or 〗 into real text...
128 $filteredText = Sanitizer
::decodeCharReferences( $text );
131 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
132 $t->mDefaultNamespace
= $defaultNamespace;
134 static $cachedcount = 0 ;
135 if( $t->secureAndSplit() ) {
136 if( $defaultNamespace == NS_MAIN
) {
137 if( $cachedcount >= MW_TITLECACHE_MAX
) {
138 # Avoid memory leaks on mass operations...
139 Title
::$titleCache = array();
143 Title
::$titleCache[$text] =& $t;
153 * Create a new Title from URL-encoded text. Ensures that
154 * the given title's length does not exceed the maximum.
155 * @param string $url the title, as might be taken from a URL
156 * @return Title the new object, or NULL on an error
158 public static function newFromURL( $url ) {
159 global $wgLegalTitleChars;
162 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
163 # but some URLs used it as a space replacement and they still come
164 # from some external search tools.
165 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
166 $url = str_replace( '+', ' ', $url );
169 $t->mDbkeyform
= str_replace( ' ', '_', $url );
170 if( $t->secureAndSplit() ) {
178 * Create a new Title from an article ID
180 * @todo This is inefficiently implemented, the page row is requested
181 * but not used for anything else
183 * @param int $id the page_id corresponding to the Title to create
184 * @param int $flags, use GAID_FOR_UPDATE to use master
185 * @return Title the new object, or NULL on an error
187 public static function newFromID( $id, $flags = 0 ) {
188 $fname = 'Title::newFromID';
189 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
190 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
191 array( 'page_id' => $id ), $fname );
192 if ( $row !== false ) {
193 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
201 * Make an array of titles from an array of IDs
203 public static function newFromIDs( $ids ) {
204 if ( !count( $ids ) ) {
207 $dbr = wfGetDB( DB_SLAVE
);
208 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
209 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
212 foreach( $res as $row ) {
213 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
219 * Make a Title object from a DB row
220 * @param Row $row (needs at least page_title,page_namespace)
222 public static function newFromRow( $row ) {
223 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
225 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
226 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
227 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
228 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
234 * Create a new Title from a namespace index and a DB key.
235 * It's assumed that $ns and $title are *valid*, for instance when
236 * they came directly from the database or a special page name.
237 * For convenience, spaces are converted to underscores so that
238 * eg user_text fields can be used directly.
240 * @param int $ns the namespace of the article
241 * @param string $title the unprefixed database key form
242 * @param string $fragment The link fragment (after the "#")
243 * @return Title the new object
245 public static function &makeTitle( $ns, $title, $fragment = '' ) {
248 $t->mFragment
= $fragment;
249 $t->mNamespace
= $ns = intval( $ns );
250 $t->mDbkeyform
= str_replace( ' ', '_', $title );
251 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
252 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
253 $t->mTextform
= str_replace( '_', ' ', $title );
258 * Create a new Title from a namespace index and a DB key.
259 * The parameters will be checked for validity, which is a bit slower
260 * than makeTitle() but safer for user-provided data.
262 * @param int $ns the namespace of the article
263 * @param string $title the database key form
264 * @param string $fragment The link fragment (after the "#")
265 * @return Title the new object, or NULL on an error
267 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
269 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
270 if( $t->secureAndSplit() ) {
278 * Create a new Title for the Main Page
279 * @return Title the new object
281 public static function newMainPage() {
282 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
283 // Don't give fatal errors if the message is broken
285 $title = Title
::newFromText( 'Main Page' );
291 * Extract a redirect destination from a string and return the
292 * Title, or null if the text doesn't contain a valid redirect
294 * @param string $text Text with possible redirect
297 public static function newFromRedirect( $text ) {
298 $redir = MagicWord
::get( 'redirect' );
299 if( $redir->matchStart( trim($text) ) ) {
300 // Extract the first link and see if it's usable
302 if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
303 // Strip preceding colon used to "escape" categories, etc.
304 // and URL-decode links
305 if( strpos( $m[1], '%' ) !== false ) {
306 // Match behavior of inline link parsing here;
307 // don't interpret + as " " most of the time!
308 // It might be safe to just use rawurldecode instead, though.
309 $m[1] = urldecode( ltrim( $m[1], ':' ) );
311 $title = Title
::newFromText( $m[1] );
312 // Redirects to Special:Userlogout are not permitted
313 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
320 #----------------------------------------------------------------------------
322 #----------------------------------------------------------------------------
325 * Get the prefixed DB key associated with an ID
326 * @param int $id the page_id of the article
327 * @return Title an object representing the article, or NULL
328 * if no such article was found
330 public static function nameOf( $id ) {
331 $dbr = wfGetDB( DB_SLAVE
);
333 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
334 if ( $s === false ) { return NULL; }
336 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
341 * Get a regex character class describing the legal characters in a link
342 * @return string the list of characters, not delimited
344 public static function legalChars() {
345 global $wgLegalTitleChars;
346 return $wgLegalTitleChars;
350 * Get a string representation of a title suitable for
351 * including in a search index
353 * @param int $ns a namespace index
354 * @param string $title text-form main part
355 * @return string a stripped-down title string ready for the
358 public static function indexTitle( $ns, $title ) {
361 $lc = SearchEngine
::legalSearchChars() . '&#;';
362 $t = $wgContLang->stripForSearch( $title );
363 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
364 $t = $wgContLang->lc( $t );
367 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
368 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
370 $t = preg_replace( "/\\s+/", ' ', $t );
372 if ( $ns == NS_IMAGE
) {
373 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
379 * Make a prefixed DB key from a DB key and a namespace index
380 * @param int $ns numerical representation of the namespace
381 * @param string $title the DB key form the title
382 * @param string $fragment The link fragment (after the "#")
383 * @return string the prefixed form of the title
385 public static function makeName( $ns, $title, $fragment = '' ) {
388 $namespace = $wgContLang->getNsText( $ns );
389 $name = $namespace == '' ?
$title : "$namespace:$title";
390 if ( strval( $fragment ) != '' ) {
391 $name .= '#' . $fragment;
397 * Returns the URL associated with an interwiki prefix
398 * @param string $key the interwiki prefix (e.g. "MeatBall")
399 * @return the associated URL, containing "$1", which should be
400 * replaced by an article title
403 public function getInterwikiLink( $key ) {
404 global $wgMemc, $wgInterwikiExpiry;
405 global $wgInterwikiCache, $wgContLang;
406 $fname = 'Title::getInterwikiLink';
408 $key = $wgContLang->lc( $key );
410 $k = wfMemcKey( 'interwiki', $key );
411 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
412 return Title
::$interwikiCache[$k]->iw_url
;
415 if ($wgInterwikiCache) {
416 return Title
::getInterwikiCached( $key );
419 $s = $wgMemc->get( $k );
420 # Ignore old keys with no iw_local
421 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
422 Title
::$interwikiCache[$k] = $s;
426 $dbr = wfGetDB( DB_SLAVE
);
427 $res = $dbr->select( 'interwiki',
428 array( 'iw_url', 'iw_local', 'iw_trans' ),
429 array( 'iw_prefix' => $key ), $fname );
434 $s = $dbr->fetchObject( $res );
436 # Cache non-existence: create a blank object and save it to memcached
442 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
443 Title
::$interwikiCache[$k] = $s;
449 * Fetch interwiki prefix data from local cache in constant database
451 * More logic is explained in DefaultSettings
453 * @return string URL of interwiki site
455 public static function getInterwikiCached( $key ) {
456 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
460 $db=dba_open($wgInterwikiCache,'r','cdb');
461 /* Resolve site name */
462 if ($wgInterwikiScopes>=3 and !$site) {
463 $site = dba_fetch('__sites:' . wfWikiID(), $db);
465 $site = $wgInterwikiFallbackSite;
467 $value = dba_fetch( wfMemcKey( $key ), $db);
468 if ($value=='' and $wgInterwikiScopes>=3) {
470 $value = dba_fetch("_{$site}:{$key}", $db);
472 if ($value=='' and $wgInterwikiScopes>=2) {
474 $value = dba_fetch("__global:{$key}", $db);
483 list($local,$url)=explode(' ',$value,2);
485 $s->iw_local
=(int)$local;
487 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
491 * Determine whether the object refers to a page within
494 * @return bool TRUE if this is an in-project interwiki link
495 * or a wikilink, FALSE otherwise
497 public function isLocal() {
498 if ( $this->mInterwiki
!= '' ) {
499 # Make sure key is loaded into cache
500 $this->getInterwikiLink( $this->mInterwiki
);
501 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
502 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
509 * Determine whether the object refers to a page within
510 * this project and is transcludable.
512 * @return bool TRUE if this is transcludable
514 public function isTrans() {
515 if ($this->mInterwiki
== '')
517 # Make sure key is loaded into cache
518 $this->getInterwikiLink( $this->mInterwiki
);
519 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
520 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
524 * Escape a text fragment, say from a link, for a URL
526 static function escapeFragmentForURL( $fragment ) {
527 $fragment = str_replace( ' ', '_', $fragment );
528 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
529 $replaceArray = array(
533 return strtr( $fragment, $replaceArray );
536 #----------------------------------------------------------------------------
538 #----------------------------------------------------------------------------
540 /** Simple accessors */
542 * Get the text form (spaces not underscores) of the main part
545 public function getText() { return $this->mTextform
; }
547 * Get the URL-encoded form of the main part
550 public function getPartialURL() { return $this->mUrlform
; }
552 * Get the main part with underscores
555 public function getDBkey() { return $this->mDbkeyform
; }
557 * Get the namespace index, i.e. one of the NS_xxxx constants
560 public function getNamespace() { return $this->mNamespace
; }
562 * Get the namespace text
565 public function getNsText() {
566 global $wgContLang, $wgCanonicalNamespaceNames;
568 if ( '' != $this->mInterwiki
) {
569 // This probably shouldn't even happen. ohh man, oh yuck.
570 // But for interwiki transclusion it sometimes does.
571 // Shit. Shit shit shit.
573 // Use the canonical namespaces if possible to try to
574 // resolve a foreign namespace.
575 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
576 return $wgCanonicalNamespaceNames[$this->mNamespace
];
579 return $wgContLang->getNsText( $this->mNamespace
);
582 * Get the DB key with the initial letter case as specified by the user
584 function getUserCaseDBKey() {
585 return $this->mUserCaseDBKey
;
588 * Get the namespace text of the subject (rather than talk) page
591 public function getSubjectNsText() {
593 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
597 * Get the namespace text of the talk page
600 public function getTalkNsText() {
602 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
606 * Could this title have a corresponding talk page?
609 public function canTalk() {
610 return( MWNamespace
::canTalk( $this->mNamespace
) );
614 * Get the interwiki prefix (or null string)
617 public function getInterwiki() { return $this->mInterwiki
; }
619 * Get the Title fragment (i.e. the bit after the #) in text form
622 public function getFragment() { return $this->mFragment
; }
624 * Get the fragment in URL form, including the "#" character if there is one
627 public function getFragmentForURL() {
628 if ( $this->mFragment
== '' ) {
631 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
635 * Get the default namespace index, for when there is no namespace
638 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
641 * Get title for search index
642 * @return string a stripped-down title string ready for the
645 public function getIndexTitle() {
646 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
650 * Get the prefixed database key form
651 * @return string the prefixed title, with underscores and
652 * any interwiki and namespace prefixes
654 public function getPrefixedDBkey() {
655 $s = $this->prefix( $this->mDbkeyform
);
656 $s = str_replace( ' ', '_', $s );
661 * Get the prefixed title with spaces.
662 * This is the form usually used for display
663 * @return string the prefixed title, with spaces
665 public function getPrefixedText() {
666 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
667 $s = $this->prefix( $this->mTextform
);
668 $s = str_replace( '_', ' ', $s );
669 $this->mPrefixedText
= $s;
671 return $this->mPrefixedText
;
675 * Get the prefixed title with spaces, plus any fragment
676 * (part beginning with '#')
677 * @return string the prefixed title, with spaces and
678 * the fragment, including '#'
680 public function getFullText() {
681 $text = $this->getPrefixedText();
682 if( '' != $this->mFragment
) {
683 $text .= '#' . $this->mFragment
;
689 * Get the base name, i.e. the leftmost parts before the /
690 * @return string Base name
692 public function getBaseText() {
693 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
694 return $this->getText();
697 $parts = explode( '/', $this->getText() );
698 # Don't discard the real title if there's no subpage involved
699 if( count( $parts ) > 1 )
700 unset( $parts[ count( $parts ) - 1 ] );
701 return implode( '/', $parts );
705 * Get the lowest-level subpage name, i.e. the rightmost part after /
706 * @return string Subpage name
708 public function getSubpageText() {
709 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
710 return( $this->mTextform
);
712 $parts = explode( '/', $this->mTextform
);
713 return( $parts[ count( $parts ) - 1 ] );
717 * Get a URL-encoded form of the subpage text
718 * @return string URL-encoded subpage name
720 public function getSubpageUrlForm() {
721 $text = $this->getSubpageText();
722 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
723 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
728 * Get a URL-encoded title (not an actual URL) including interwiki
729 * @return string the URL-encoded form
731 public function getPrefixedURL() {
732 $s = $this->prefix( $this->mDbkeyform
);
733 $s = str_replace( ' ', '_', $s );
735 $s = wfUrlencode ( $s ) ;
737 # Cleaning up URL to make it look nice -- is this safe?
738 $s = str_replace( '%28', '(', $s );
739 $s = str_replace( '%29', ')', $s );
745 * Get a real URL referring to this title, with interwiki link and
748 * @param array $query an optional query string, not used for interwiki
749 * links. Can be specified as an associative array as well, e.g.,
750 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
751 * @param string $variant language variant of url (for sr, zh..)
752 * @return string the URL
754 public function getFullURL( $query = '', $variant = false ) {
755 global $wgContLang, $wgServer, $wgRequest;
757 if( is_array( $query ) ) {
758 $query = wfArrayToCGI( $query );
761 if ( '' == $this->mInterwiki
) {
762 $url = $this->getLocalUrl( $query, $variant );
764 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
765 // Correct fix would be to move the prepending elsewhere.
766 if ($wgRequest->getVal('action') != 'render') {
767 $url = $wgServer . $url;
770 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
772 $namespace = wfUrlencode( $this->getNsText() );
773 if ( '' != $namespace ) {
774 # Can this actually happen? Interwikis shouldn't be parsed.
775 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
778 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
779 $url = wfAppendQuery( $url, $query );
782 # Finally, add the fragment.
783 $url .= $this->getFragmentForURL();
785 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
790 * Get a URL with no fragment or server name. If this page is generated
791 * with action=render, $wgServer is prepended.
792 * @param mixed $query an optional query string; if not specified,
793 * $wgArticlePath will be used. Can be specified as an associative array
794 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
796 * @param string $variant language variant of url (for sr, zh..)
797 * @return string the URL
799 public function getLocalURL( $query = '', $variant = false ) {
800 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
801 global $wgVariantArticlePath, $wgContLang, $wgUser;
803 if( is_array( $query ) ) {
804 $query = wfArrayToCGI( $query );
807 // internal links should point to same variant as current page (only anonymous users)
808 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
809 $pref = $wgContLang->getPreferredVariant(false);
810 if($pref != $wgContLang->getCode())
814 if ( $this->isExternal() ) {
815 $url = $this->getFullURL();
817 // This is currently only used for edit section links in the
818 // context of interwiki transclusion. In theory we should
819 // append the query to the end of any existing query string,
820 // but interwiki transclusion is already broken in that case.
824 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
825 if ( $query == '' ) {
826 if( $variant != false && $wgContLang->hasVariants() ) {
827 if( $wgVariantArticlePath == false ) {
828 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
830 $variantArticlePath = $wgVariantArticlePath;
832 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
833 $url = str_replace( '$1', $dbkey, $url );
835 $url = str_replace( '$1', $dbkey, $wgArticlePath );
838 global $wgActionPaths;
841 if( !empty( $wgActionPaths ) &&
842 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
844 $action = urldecode( $matches[2] );
845 if( isset( $wgActionPaths[$action] ) ) {
846 $query = $matches[1];
847 if( isset( $matches[4] ) ) $query .= $matches[4];
848 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
849 if( $query != '' ) $url .= '?' . $query;
852 if ( $url === false ) {
853 if ( $query == '-' ) {
856 $url = "{$wgScript}?title={$dbkey}&{$query}";
860 // FIXME: this causes breakage in various places when we
861 // actually expected a local URL and end up with dupe prefixes.
862 if ($wgRequest->getVal('action') == 'render') {
863 $url = $wgServer . $url;
866 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
871 * Get a URL that's the simplest URL that will be valid to link, locally,
872 * to the current Title. It includes the fragment, but does not include
873 * the server unless action=render is used (or the link is external). If
874 * there's a fragment but the prefixed text is empty, we just return a link
877 * @param array $query An associative array of key => value pairs for the
878 * query string. Keys and values will be escaped.
879 * @param string $variant Language variant of URL (for sr, zh..). Ignored
880 * for external links. Default is "false" (same variant as current page,
881 * for anonymous users).
882 * @return string the URL
884 public function getLinkUrl( $query = array(), $variant = false ) {
885 if( !is_array( $query ) ) {
886 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
889 if( $this->isExternal() ) {
890 return $this->getFullURL( $query );
891 } elseif( $this->getPrefixedText() === ''
892 and $this->getFragment() !== '' ) {
893 return $this->getFragmentForURL();
895 return $this->getLocalURL( $query, $variant )
896 . $this->getFragmentForURL();
901 * Get an HTML-escaped version of the URL form, suitable for
902 * using in a link, without a server name or fragment
903 * @param string $query an optional query string
904 * @return string the URL
906 public function escapeLocalURL( $query = '' ) {
907 return htmlspecialchars( $this->getLocalURL( $query ) );
911 * Get an HTML-escaped version of the URL form, suitable for
912 * using in a link, including the server name and fragment
914 * @return string the URL
915 * @param string $query an optional query string
917 public function escapeFullURL( $query = '' ) {
918 return htmlspecialchars( $this->getFullURL( $query ) );
922 * Get the URL form for an internal link.
923 * - Used in various Squid-related code, in case we have a different
924 * internal hostname for the server from the exposed one.
926 * @param string $query an optional query string
927 * @param string $variant language variant of url (for sr, zh..)
928 * @return string the URL
930 public function getInternalURL( $query = '', $variant = false ) {
931 global $wgInternalServer;
932 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
933 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
938 * Get the edit URL for this Title
939 * @return string the URL, or a null string if this is an
942 public function getEditURL() {
943 if ( '' != $this->mInterwiki
) { return ''; }
944 $s = $this->getLocalURL( 'action=edit' );
950 * Get the HTML-escaped displayable text form.
951 * Used for the title field in <a> tags.
952 * @return string the text, including any prefixes
954 public function getEscapedText() {
955 return htmlspecialchars( $this->getPrefixedText() );
959 * Is this Title interwiki?
962 public function isExternal() { return ( '' != $this->mInterwiki
); }
965 * Is this page "semi-protected" - the *only* protection is autoconfirm?
967 * @param string Action to check (default: edit)
970 public function isSemiProtected( $action = 'edit' ) {
971 if( $this->exists() ) {
972 $restrictions = $this->getRestrictions( $action );
973 if( count( $restrictions ) > 0 ) {
974 foreach( $restrictions as $restriction ) {
975 if( strtolower( $restriction ) != 'autoconfirmed' )
984 # If it doesn't exist, it can't be protected
990 * Does the title correspond to a protected article?
991 * @param string $what the action the page is protected from,
992 * by default checks move and edit
995 public function isProtected( $action = '' ) {
996 global $wgRestrictionLevels, $wgRestrictionTypes;
998 # Special pages have inherent protection
999 if( $this->getNamespace() == NS_SPECIAL
)
1002 # Check regular protection levels
1003 foreach( $wgRestrictionTypes as $type ){
1004 if( $action == $type ||
$action == '' ) {
1005 $r = $this->getRestrictions( $type );
1006 foreach( $wgRestrictionLevels as $level ) {
1007 if( in_array( $level, $r ) && $level != '' ) {
1018 * Is $wgUser watching this page?
1021 public function userIsWatching() {
1024 if ( is_null( $this->mWatched
) ) {
1025 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1026 $this->mWatched
= false;
1028 $this->mWatched
= $wgUser->isWatched( $this );
1031 return $this->mWatched
;
1035 * Can $wgUser perform $action on this page?
1036 * This skips potentially expensive cascading permission checks.
1038 * Suitable for use for nonessential UI controls in common cases, but
1039 * _not_ for functional access control.
1041 * May provide false positives, but should never provide a false negative.
1043 * @param string $action action that permission needs to be checked for
1046 public function quickUserCan( $action ) {
1047 return $this->userCan( $action, false );
1051 * Determines if $wgUser is unable to edit this page because it has been protected
1052 * by $wgNamespaceProtection.
1056 public function isNamespaceProtected() {
1057 global $wgNamespaceProtection, $wgUser;
1058 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1059 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1060 if( $right != '' && !$wgUser->isAllowed( $right ) )
1068 * Can $wgUser perform $action on this page?
1069 * @param string $action action that permission needs to be checked for
1070 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1073 public function userCan( $action, $doExpensiveQueries = true ) {
1075 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1079 * Can $user perform $action on this page?
1081 * FIXME: This *does not* check throttles (User::pingLimiter()).
1083 * @param string $action action that permission needs to be checked for
1084 * @param User $user user to check
1085 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1086 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1087 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1089 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1090 if( !StubObject
::isRealObject( $user ) ) {
1091 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1093 $wgUser->_unstub( '', 5 );
1096 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1100 global $wgEmailConfirmToEdit;
1102 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1103 $errors[] = array( 'confirmedittext' );
1106 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1107 $block = $user->mBlock
;
1109 // This is from OutputPage::blockedPage
1110 // Copied at r23888 by werdna
1112 $id = $user->blockedBy();
1113 $reason = $user->blockedFor();
1114 if( $reason == '' ) {
1115 $reason = wfMsg( 'blockednoreason' );
1119 if ( is_numeric( $id ) ) {
1120 $name = User
::whoIs( $id );
1125 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1126 $blockid = $block->mId
;
1127 $blockExpiry = $user->mBlock
->mExpiry
;
1128 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1130 if ( $blockExpiry == 'infinity' ) {
1131 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1132 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1134 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1135 if ( strpos( $option, ':' ) == false )
1138 list ($show, $value) = explode( ":", $option );
1140 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1141 $blockExpiry = $show;
1146 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1149 $intended = $user->mBlock
->mAddress
;
1151 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1152 $blockid, $blockExpiry, $intended, $blockTimestamp );
1155 // Remove the errors being ignored.
1157 foreach( $errors as $index => $error ) {
1158 $error_key = is_array($error) ?
$error[0] : $error;
1160 if (in_array( $error_key, $ignoreErrors )) {
1161 unset($errors[$index]);
1169 * Can $user perform $action on this page? This is an internal function,
1170 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1171 * checks on wfReadOnly() and blocks)
1173 * @param string $action action that permission needs to be checked for
1174 * @param User $user user to check
1175 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1176 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1178 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1179 wfProfileIn( __METHOD__
);
1183 // Use getUserPermissionsErrors instead
1184 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1185 wfProfileOut( __METHOD__
);
1186 return $result ?
array() : array( array( 'badaccess-group0' ) );
1189 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1190 if ($result != array() && is_array($result) && !is_array($result[0]))
1191 $errors[] = $result; # A single array representing an error
1192 else if (is_array($result) && is_array($result[0]))
1193 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1194 else if ($result != '' && $result != null && $result !== true && $result !== false)
1195 $errors[] = array($result); # A string representing a message-id
1196 else if ($result === false )
1197 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1199 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1200 if ($result != array() && is_array($result) && !is_array($result[0]))
1201 $errors[] = $result; # A single array representing an error
1202 else if (is_array($result) && is_array($result[0]))
1203 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1204 else if ($result != '' && $result != null && $result !== true && $result !== false)
1205 $errors[] = array($result); # A string representing a message-id
1206 else if ($result === false )
1207 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1210 $specialOKActions = array( 'createaccount', 'execute' );
1211 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1212 $errors[] = array('ns-specialprotected');
1215 if ( $this->isNamespaceProtected() ) {
1216 $ns = $this->getNamespace() == NS_MAIN
1217 ?
wfMsg( 'nstab-main' )
1218 : $this->getNsText();
1219 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1220 ?
array('protectedinterface')
1221 : array( 'namespaceprotected', $ns ) );
1224 if( $this->mDbkeyform
== '_' ) {
1225 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1226 $errors[] = array('badaccess-group0');
1229 # protect css/js subpages of user pages
1230 # XXX: this might be better using restrictions
1231 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1232 if( $this->isCssJsSubpage()
1233 && !$user->isAllowed('editusercssjs')
1234 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1235 $errors[] = array('customcssjsprotected');
1238 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1239 # We /could/ use the protection level on the source page, but it's fairly ugly
1240 # as we have to establish a precedence hierarchy for pages included by multiple
1241 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1242 # as they could remove the protection anyway.
1243 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1244 # Cascading protection depends on more than this page...
1245 # Several cascading protected pages may include this page...
1246 # Check each cascading level
1247 # This is only for protection restrictions, not for all actions
1248 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1249 foreach( $restrictions[$action] as $right ) {
1250 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1251 if( '' != $right && !$user->isAllowed( $right ) ) {
1253 foreach( $cascadingSources as $page )
1254 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1255 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1261 foreach( $this->getRestrictions($action) as $right ) {
1262 // Backwards compatibility, rewrite sysop -> protect
1263 if ( $right == 'sysop' ) {
1266 if( '' != $right && !$user->isAllowed( $right ) ) {
1267 //Users with 'editprotected' permission can edit protected pages
1268 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1269 //Users with 'editprotected' permission cannot edit protected pages
1270 //with cascading option turned on.
1271 if($this->mCascadeRestriction
) {
1272 $errors[] = array( 'protectedpagetext', $right );
1274 //Nothing, user can edit!
1277 $errors[] = array( 'protectedpagetext', $right );
1282 if ($action == 'protect') {
1283 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1284 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1288 if ($action == 'create') {
1289 $title_protection = $this->getTitleProtection();
1291 if (is_array($title_protection)) {
1292 extract($title_protection);
1294 if ($pt_create_perm == 'sysop')
1295 $pt_create_perm = 'protect';
1297 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1298 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1302 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1303 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1304 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1306 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1307 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1308 } elseif ( !$user->isAllowed( $action ) ) {
1310 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1311 User
::getGroupsWithPermission( $action ) );
1313 $return = array( 'badaccess-groups',
1315 implode( ', ', $groups ),
1316 count( $groups ) ) );
1319 $return = array( "badaccess-group0" );
1321 $errors[] = $return;
1324 wfProfileOut( __METHOD__
);
1329 * Is this title subject to title protection?
1330 * @return mixed An associative array representing any existent title
1331 * protection, or false if there's none.
1333 private function getTitleProtection() {
1334 // Can't protect pages in special namespaces
1335 if ( $this->getNamespace() < 0 ) {
1339 $dbr = wfGetDB( DB_SLAVE
);
1340 $res = $dbr->select( 'protected_titles', '*',
1341 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1343 if ($row = $dbr->fetchRow( $res )) {
1350 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1351 global $wgUser,$wgContLang;
1353 if ($create_perm == implode(',',$this->getRestrictions('create'))
1354 && $expiry == $this->mRestrictionsExpiry
) {
1359 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1361 $dbw = wfGetDB( DB_MASTER
);
1363 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1365 $expiry_description = '';
1366 if ( $encodedExpiry != 'infinity' ) {
1367 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1370 # Update protection table
1371 if ($create_perm != '' ) {
1372 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1373 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1374 , 'pt_create_perm' => $create_perm
1375 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1376 , 'pt_expiry' => $encodedExpiry
1377 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1379 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1380 'pt_title' => $title ), __METHOD__
);
1382 # Update the protection log
1383 $log = new LogPage( 'protect' );
1385 if( $create_perm ) {
1386 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1388 $log->addEntry( 'unprotect', $this, $reason );
1395 * Remove any title protection (due to page existing
1397 public function deleteTitleProtection() {
1398 $dbw = wfGetDB( DB_MASTER
);
1400 $dbw->delete( 'protected_titles',
1401 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1405 * Can $wgUser edit this page?
1407 * @deprecated use userCan('edit')
1409 public function userCanEdit( $doExpensiveQueries = true ) {
1410 return $this->userCan( 'edit', $doExpensiveQueries );
1414 * Can $wgUser create this page?
1416 * @deprecated use userCan('create')
1418 public function userCanCreate( $doExpensiveQueries = true ) {
1419 return $this->userCan( 'create', $doExpensiveQueries );
1423 * Can $wgUser move this page?
1425 * @deprecated use userCan('move')
1427 public function userCanMove( $doExpensiveQueries = true ) {
1428 return $this->userCan( 'move', $doExpensiveQueries );
1432 * Would anybody with sufficient privileges be able to move this page?
1433 * Some pages just aren't movable.
1437 public function isMovable() {
1438 return MWNamespace
::isMovable( $this->getNamespace() )
1439 && $this->getInterwiki() == '';
1443 * Can $wgUser read this page?
1445 * @todo fold these checks into userCan()
1447 public function userCanRead() {
1448 global $wgUser, $wgGroupPermissions;
1451 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1452 if ( $result !== null ) {
1456 # Shortcut for public wikis, allows skipping quite a bit of code
1457 if ($wgGroupPermissions['*']['read'])
1460 if( $wgUser->isAllowed( 'read' ) ) {
1463 global $wgWhitelistRead;
1466 * Always grant access to the login page.
1467 * Even anons need to be able to log in.
1469 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1474 * Bail out if there isn't whitelist
1476 if( !is_array($wgWhitelistRead) ) {
1481 * Check for explicit whitelisting
1483 $name = $this->getPrefixedText();
1484 $dbName = $this->getPrefixedDBKey();
1485 // Check with and without underscores
1486 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1490 * Old settings might have the title prefixed with
1491 * a colon for main-namespace pages
1493 if( $this->getNamespace() == NS_MAIN
) {
1494 if( in_array( ':' . $name, $wgWhitelistRead ) )
1499 * If it's a special page, ditch the subpage bit
1502 if( $this->getNamespace() == NS_SPECIAL
) {
1503 $name = $this->getDBkey();
1504 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1505 if ( $name === false ) {
1506 # Invalid special page, but we show standard login required message
1510 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1511 if( in_array( $pure, $wgWhitelistRead, true ) )
1520 * Is this a talk page of some sort?
1523 public function isTalkPage() {
1524 return MWNamespace
::isTalk( $this->getNamespace() );
1528 * Is this a subpage?
1531 public function isSubpage() {
1532 return MWNamespace
::hasSubpages( $this->mNamespace
)
1533 ?
strpos( $this->getText(), '/' ) !== false
1538 * Does this have subpages? (Warning, usually requires an extra DB query.)
1541 public function hasSubpages() {
1542 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1547 # We dynamically add a member variable for the purpose of this method
1548 # alone to cache the result. There's no point in having it hanging
1549 # around uninitialized in every Title object; therefore we only add it
1550 # if needed and don't declare it statically.
1551 if( isset( $this->mHasSubpages
) ) {
1552 return $this->mHasSubpages
;
1555 $db = wfGetDB( DB_SLAVE
);
1556 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1557 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1558 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1564 * Could this page contain custom CSS or JavaScript, based
1569 public function isCssOrJsPage() {
1570 return $this->mNamespace
== NS_MEDIAWIKI
1571 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1575 * Is this a .css or .js subpage of a user page?
1578 public function isCssJsSubpage() {
1579 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1582 * Is this a *valid* .css or .js subpage of a user page?
1583 * Check that the corresponding skin exists
1585 public function isValidCssJsSubpage() {
1586 if ( $this->isCssJsSubpage() ) {
1587 $skinNames = Skin
::getSkinNames();
1588 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1594 * Trim down a .css or .js subpage title to get the corresponding skin name
1596 public function getSkinFromCssJsSubpage() {
1597 $subpage = explode( '/', $this->mTextform
);
1598 $subpage = $subpage[ count( $subpage ) - 1 ];
1599 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1602 * Is this a .css subpage of a user page?
1605 public function isCssSubpage() {
1606 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1609 * Is this a .js subpage of a user page?
1612 public function isJsSubpage() {
1613 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1616 * Protect css/js subpages of user pages: can $wgUser edit
1620 * @todo XXX: this might be better using restrictions
1622 public function userCanEditCssJsSubpage() {
1624 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1628 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1630 * @return bool If the page is subject to cascading restrictions.
1632 public function isCascadeProtected() {
1633 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1634 return ( $sources > 0 );
1638 * Cascading protection: Get the source of any cascading restrictions on this page.
1640 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1641 * @return array( mixed title array, restriction array)
1642 * Array of the Title objects of the pages from which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1643 * The restriction array is an array of each type, each of which contains an array of unique groups
1645 public function getCascadeProtectionSources( $get_pages = true ) {
1646 global $wgRestrictionTypes;
1648 # Define our dimension of restrictions types
1649 $pagerestrictions = array();
1650 foreach( $wgRestrictionTypes as $action )
1651 $pagerestrictions[$action] = array();
1653 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1654 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1655 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1656 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1659 wfProfileIn( __METHOD__
);
1661 $dbr = wfGetDb( DB_SLAVE
);
1663 if ( $this->getNamespace() == NS_IMAGE
) {
1664 $tables = array ('imagelinks', 'page_restrictions');
1665 $where_clauses = array(
1666 'il_to' => $this->getDBkey(),
1668 'pr_cascade' => 1 );
1670 $tables = array ('templatelinks', 'page_restrictions');
1671 $where_clauses = array(
1672 'tl_namespace' => $this->getNamespace(),
1673 'tl_title' => $this->getDBkey(),
1675 'pr_cascade' => 1 );
1679 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1680 $where_clauses[] = 'page_id=pr_page';
1683 $cols = array( 'pr_expiry' );
1686 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1688 $sources = $get_pages ?
array() : false;
1689 $now = wfTimestampNow();
1690 $purgeExpired = false;
1692 foreach( $res as $row ) {
1693 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1694 if( $expiry > $now ) {
1696 $page_id = $row->pr_page
;
1697 $page_ns = $row->page_namespace
;
1698 $page_title = $row->page_title
;
1699 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1700 # Add groups needed for each restriction type if its not already there
1701 # Make sure this restriction type still exists
1702 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1703 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1709 // Trigger lazy purge of expired restrictions from the db
1710 $purgeExpired = true;
1713 if( $purgeExpired ) {
1714 Title
::purgeExpiredRestrictions();
1717 wfProfileOut( __METHOD__
);
1720 $this->mCascadeSources
= $sources;
1721 $this->mCascadingRestrictions
= $pagerestrictions;
1723 $this->mHasCascadingRestrictions
= $sources;
1726 return array( $sources, $pagerestrictions );
1729 function areRestrictionsCascading() {
1730 if (!$this->mRestrictionsLoaded
) {
1731 $this->loadRestrictions();
1734 return $this->mCascadeRestriction
;
1738 * Loads a string into mRestrictions array
1739 * @param resource $res restrictions as an SQL result.
1741 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1742 global $wgRestrictionTypes;
1743 $dbr = wfGetDB( DB_SLAVE
);
1745 foreach( $wgRestrictionTypes as $type ){
1746 $this->mRestrictions
[$type] = array();
1749 $this->mCascadeRestriction
= false;
1750 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1752 # Backwards-compatibility: also load the restrictions from the page record (old format).
1754 if ( $oldFashionedRestrictions === NULL ) {
1755 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1756 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1759 if ($oldFashionedRestrictions != '') {
1761 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1762 $temp = explode( '=', trim( $restrict ) );
1763 if(count($temp) == 1) {
1764 // old old format should be treated as edit/move restriction
1765 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1766 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1768 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1772 $this->mOldRestrictions
= true;
1776 if( $dbr->numRows( $res ) ) {
1777 # Current system - load second to make them override.
1778 $now = wfTimestampNow();
1779 $purgeExpired = false;
1781 foreach( $res as $row ) {
1782 # Cycle through all the restrictions.
1784 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1785 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1788 // This code should be refactored, now that it's being used more generally,
1789 // But I don't really see any harm in leaving it in Block for now -werdna
1790 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1792 // Only apply the restrictions if they haven't expired!
1793 if ( !$expiry ||
$expiry > $now ) {
1794 $this->mRestrictionsExpiry
= $expiry;
1795 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1797 $this->mCascadeRestriction |
= $row->pr_cascade
;
1799 // Trigger a lazy purge of expired restrictions
1800 $purgeExpired = true;
1804 if( $purgeExpired ) {
1805 Title
::purgeExpiredRestrictions();
1809 $this->mRestrictionsLoaded
= true;
1812 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1813 if( !$this->mRestrictionsLoaded
) {
1814 if ($this->exists()) {
1815 $dbr = wfGetDB( DB_SLAVE
);
1817 $res = $dbr->select( 'page_restrictions', '*',
1818 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1820 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1822 $title_protection = $this->getTitleProtection();
1824 if (is_array($title_protection)) {
1825 extract($title_protection);
1827 $now = wfTimestampNow();
1828 $expiry = Block
::decodeExpiry($pt_expiry);
1830 if (!$expiry ||
$expiry > $now) {
1831 // Apply the restrictions
1832 $this->mRestrictionsExpiry
= $expiry;
1833 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1834 } else { // Get rid of the old restrictions
1835 Title
::purgeExpiredRestrictions();
1838 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1840 $this->mRestrictionsLoaded
= true;
1846 * Purge expired restrictions from the page_restrictions table
1848 static function purgeExpiredRestrictions() {
1849 $dbw = wfGetDB( DB_MASTER
);
1850 $dbw->delete( 'page_restrictions',
1851 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1854 $dbw->delete( 'protected_titles',
1855 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1860 * Accessor/initialisation for mRestrictions
1862 * @param string $action action that permission needs to be checked for
1863 * @return array the array of groups allowed to edit this article
1865 public function getRestrictions( $action ) {
1866 if( !$this->mRestrictionsLoaded
) {
1867 $this->loadRestrictions();
1869 return isset( $this->mRestrictions
[$action] )
1870 ?
$this->mRestrictions
[$action]
1875 * Is there a version of this page in the deletion archive?
1876 * @return int the number of archived revisions
1878 public function isDeleted() {
1879 $fname = 'Title::isDeleted';
1880 if ( $this->getNamespace() < 0 ) {
1883 $dbr = wfGetDB( DB_SLAVE
);
1884 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1885 'ar_title' => $this->getDBkey() ), $fname );
1886 if( $this->getNamespace() == NS_IMAGE
) {
1887 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1888 array( 'fa_name' => $this->getDBkey() ), $fname );
1895 * Get the article ID for this Title from the link cache,
1896 * adding it if necessary
1897 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1899 * @return int the ID
1901 public function getArticleID( $flags = 0 ) {
1902 $linkCache = LinkCache
::singleton();
1903 if ( $flags & GAID_FOR_UPDATE
) {
1904 $oldUpdate = $linkCache->forUpdate( true );
1905 $this->mArticleID
= $linkCache->addLinkObj( $this );
1906 $linkCache->forUpdate( $oldUpdate );
1908 if ( -1 == $this->mArticleID
) {
1909 $this->mArticleID
= $linkCache->addLinkObj( $this );
1912 return $this->mArticleID
;
1916 * Is this an article that is a redirect page?
1917 * Uses link cache, adding it if necessary
1918 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1921 public function isRedirect( $flags = 0 ) {
1922 if( !is_null($this->mRedirect
) )
1923 return $this->mRedirect
;
1924 # Zero for special pages.
1925 # Also, calling getArticleID() loads the field from cache!
1926 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1929 $linkCache = LinkCache
::singleton();
1930 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1932 return $this->mRedirect
;
1936 * What is the length of this page?
1937 * Uses link cache, adding it if necessary
1938 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1941 public function getLength( $flags = 0 ) {
1942 if( $this->mLength
!= -1 )
1943 return $this->mLength
;
1944 # Zero for special pages.
1945 # Also, calling getArticleID() loads the field from cache!
1946 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1949 $linkCache = LinkCache
::singleton();
1950 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1952 return $this->mLength
;
1956 * What is the page_latest field for this page?
1957 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1960 public function getLatestRevID( $flags = 0 ) {
1961 if ($this->mLatestID
!== false)
1962 return $this->mLatestID
;
1964 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1965 return $this->mLatestID
= $db->selectField( 'revision',
1967 array('rev_page' => $this->getArticleID($flags)),
1968 'Title::getLatestRevID' );
1972 * This clears some fields in this object, and clears any associated
1973 * keys in the "bad links" section of the link cache.
1975 * - This is called from Article::insertNewArticle() to allow
1976 * loading of the new page_id. It's also called from
1977 * Article::doDeleteArticle()
1979 * @param int $newid the new Article ID
1981 public function resetArticleID( $newid ) {
1982 $linkCache = LinkCache
::singleton();
1983 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1985 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1986 else { $this->mArticleID
= $newid; }
1987 $this->mRestrictionsLoaded
= false;
1988 $this->mRestrictions
= array();
1992 * Updates page_touched for this page; called from LinksUpdate.php
1993 * @return bool true if the update succeded
1995 public function invalidateCache() {
1996 global $wgUseFileCache;
1998 if ( wfReadOnly() ) {
2002 $dbw = wfGetDB( DB_MASTER
);
2003 $success = $dbw->update( 'page',
2005 'page_touched' => $dbw->timestamp()
2006 ), array( /* WHERE */
2007 'page_namespace' => $this->getNamespace() ,
2008 'page_title' => $this->getDBkey()
2009 ), 'Title::invalidateCache'
2012 if ($wgUseFileCache) {
2013 $cache = new HTMLFileCache($this);
2014 @unlink
($cache->fileCacheName());
2021 * Prefix some arbitrary text with the namespace or interwiki prefix
2024 * @param string $name the text
2025 * @return string the prefixed text
2028 /* private */ function prefix( $name ) {
2030 if ( '' != $this->mInterwiki
) {
2031 $p = $this->mInterwiki
. ':';
2033 if ( 0 != $this->mNamespace
) {
2034 $p .= $this->getNsText() . ':';
2040 * Secure and split - main initialisation function for this object
2042 * Assumes that mDbkeyform has been set, and is urldecoded
2043 * and uses underscores, but not otherwise munged. This function
2044 * removes illegal characters, splits off the interwiki and
2045 * namespace prefixes, sets the other forms, and canonicalizes
2047 * @return bool true on success
2049 private function secureAndSplit() {
2050 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2053 static $rxTc = false;
2055 # Matching titles will be held as illegal.
2057 # Any character not allowed is forbidden...
2058 '[^' . Title
::legalChars() . ']' .
2059 # URL percent encoding sequences interfere with the ability
2060 # to round-trip titles -- you can't link to them consistently.
2061 '|%[0-9A-Fa-f]{2}' .
2062 # XML/HTML character references produce similar issues.
2063 '|&[A-Za-z0-9\x80-\xff]+;' .
2065 '|&#x[0-9A-Fa-f]+;' .
2069 $this->mInterwiki
= $this->mFragment
= '';
2070 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2072 $dbkey = $this->mDbkeyform
;
2074 # Strip Unicode bidi override characters.
2075 # Sometimes they slip into cut-n-pasted page titles, where the
2076 # override chars get included in list displays.
2077 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2078 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2080 # Clean up whitespace
2082 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2083 $dbkey = trim( $dbkey, '_' );
2085 if ( '' == $dbkey ) {
2089 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2090 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2094 $this->mDbkeyform
= $dbkey;
2096 # Initial colon indicates main namespace rather than specified default
2097 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2098 if ( ':' == $dbkey{0} ) {
2099 $this->mNamespace
= NS_MAIN
;
2100 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2101 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2104 # Namespace or interwiki prefix
2108 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2110 if ( $ns = $wgContLang->getNsIndex( $p )) {
2111 # Ordinary namespace
2113 $this->mNamespace
= $ns;
2114 } elseif( $this->getInterwikiLink( $p ) ) {
2116 # Can't make a local interwiki link to an interwiki link.
2117 # That's just crazy!
2123 $this->mInterwiki
= $wgContLang->lc( $p );
2125 # Redundant interwiki prefix to the local wiki
2126 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2127 if( $dbkey == '' ) {
2128 # Can't have an empty self-link
2131 $this->mInterwiki
= '';
2133 # Do another namespace split...
2137 # If there's an initial colon after the interwiki, that also
2138 # resets the default namespace
2139 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2140 $this->mNamespace
= NS_MAIN
;
2141 $dbkey = substr( $dbkey, 1 );
2144 # If there's no recognized interwiki or namespace,
2145 # then let the colon expression be part of the title.
2150 # We already know that some pages won't be in the database!
2152 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2153 $this->mArticleID
= 0;
2155 $fragment = strstr( $dbkey, '#' );
2156 if ( false !== $fragment ) {
2157 $this->setFragment( $fragment );
2158 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2159 # remove whitespace again: prevents "Foo_bar_#"
2160 # becoming "Foo_bar_"
2161 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2164 # Reject illegal characters.
2166 if( preg_match( $rxTc, $dbkey ) ) {
2171 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2172 * reachable due to the way web browsers deal with 'relative' URLs.
2173 * Also, they conflict with subpage syntax. Forbid them explicitly.
2175 if ( strpos( $dbkey, '.' ) !== false &&
2176 ( $dbkey === '.' ||
$dbkey === '..' ||
2177 strpos( $dbkey, './' ) === 0 ||
2178 strpos( $dbkey, '../' ) === 0 ||
2179 strpos( $dbkey, '/./' ) !== false ||
2180 strpos( $dbkey, '/../' ) !== false ||
2181 substr( $dbkey, -2 ) == '/.' ||
2182 substr( $dbkey, -3 ) == '/..' ) )
2188 * Magic tilde sequences? Nu-uh!
2190 if( strpos( $dbkey, '~~~' ) !== false ) {
2195 * Limit the size of titles to 255 bytes.
2196 * This is typically the size of the underlying database field.
2197 * We make an exception for special pages, which don't need to be stored
2198 * in the database, and may edge over 255 bytes due to subpage syntax
2199 * for long titles, e.g. [[Special:Block/Long name]]
2201 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2202 strlen( $dbkey ) > 512 )
2208 * Normally, all wiki links are forced to have
2209 * an initial capital letter so [[foo]] and [[Foo]]
2210 * point to the same place.
2212 * Don't force it for interwikis, since the other
2213 * site might be case-sensitive.
2215 $this->mUserCaseDBKey
= $dbkey;
2216 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2217 $dbkey = $wgContLang->ucfirst( $dbkey );
2221 * Can't make a link to a namespace alone...
2222 * "empty" local links can only be self-links
2223 * with a fragment identifier.
2226 $this->mInterwiki
== '' &&
2227 $this->mNamespace
!= NS_MAIN
) {
2230 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2231 // IP names are not allowed for accounts, and can only be referring to
2232 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2233 // there are numerous ways to present the same IP. Having sp:contribs scan
2234 // them all is silly and having some show the edits and others not is
2235 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2236 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2237 IP
::sanitizeIP( $dbkey ) : $dbkey;
2238 // Any remaining initial :s are illegal.
2239 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2244 $this->mDbkeyform
= $dbkey;
2245 $this->mUrlform
= wfUrlencode( $dbkey );
2247 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2253 * Set the fragment for this title
2254 * This is kind of bad, since except for this rarely-used function, Title objects
2255 * are immutable. The reason this is here is because it's better than setting the
2256 * members directly, which is what Linker::formatComment was doing previously.
2258 * @param string $fragment text
2259 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2261 public function setFragment( $fragment ) {
2262 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2266 * Get a Title object associated with the talk page of this article
2267 * @return Title the object for the talk page
2269 public function getTalkPage() {
2270 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2274 * Get a title object associated with the subject page of this
2277 * @return Title the object for the subject page
2279 public function getSubjectPage() {
2280 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2284 * Get an array of Title objects linking to this Title
2285 * Also stores the IDs in the link cache.
2287 * WARNING: do not use this function on arbitrary user-supplied titles!
2288 * On heavily-used templates it will max out the memory.
2290 * @param string $options may be FOR UPDATE
2291 * @return array the Title objects linking here
2293 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2294 $linkCache = LinkCache
::singleton();
2297 $db = wfGetDB( DB_MASTER
);
2299 $db = wfGetDB( DB_SLAVE
);
2302 $res = $db->select( array( 'page', $table ),
2303 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2305 "{$prefix}_from=page_id",
2306 "{$prefix}_namespace" => $this->getNamespace(),
2307 "{$prefix}_title" => $this->getDBkey() ),
2312 if ( $db->numRows( $res ) ) {
2313 foreach( $res as $row ) {
2314 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2315 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2316 $retVal[] = $titleObj;
2320 $db->freeResult( $res );
2325 * Get an array of Title objects using this Title as a template
2326 * Also stores the IDs in the link cache.
2328 * WARNING: do not use this function on arbitrary user-supplied titles!
2329 * On heavily-used templates it will max out the memory.
2331 * @param string $options may be FOR UPDATE
2332 * @return array the Title objects linking here
2334 public function getTemplateLinksTo( $options = '' ) {
2335 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2339 * Get an array of Title objects referring to non-existent articles linked from this page
2341 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2342 * @param string $options may be FOR UPDATE
2343 * @return array the Title objects
2345 public function getBrokenLinksFrom( $options = '' ) {
2346 if ( $this->getArticleId() == 0 ) {
2347 # All links from article ID 0 are false positives
2352 $db = wfGetDB( DB_MASTER
);
2354 $db = wfGetDB( DB_SLAVE
);
2357 $res = $db->safeQuery(
2358 "SELECT pl_namespace, pl_title
2361 ON pl_namespace=page_namespace
2362 AND pl_title=page_title
2364 AND page_namespace IS NULL
2366 $db->tableName( 'pagelinks' ),
2367 $db->tableName( 'page' ),
2368 $this->getArticleId(),
2372 if ( $db->numRows( $res ) ) {
2373 foreach( $res as $row ) {
2374 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2377 $db->freeResult( $res );
2383 * Get a list of URLs to purge from the Squid cache when this
2386 * @return array the URLs
2388 public function getSquidURLs() {
2392 $this->getInternalURL(),
2393 $this->getInternalURL( 'action=history' )
2396 // purge variant urls as well
2397 if($wgContLang->hasVariants()){
2398 $variants = $wgContLang->getVariants();
2399 foreach($variants as $vCode){
2400 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2401 $urls[] = $this->getInternalURL('',$vCode);
2408 public function purgeSquid() {
2410 if ( $wgUseSquid ) {
2411 $urls = $this->getSquidURLs();
2412 $u = new SquidUpdate( $urls );
2418 * Move this page without authentication
2419 * @param Title &$nt the new page Title
2421 public function moveNoAuth( &$nt ) {
2422 return $this->moveTo( $nt, false );
2426 * Check whether a given move operation would be valid.
2427 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2428 * @param Title &$nt the new title
2429 * @param bool $auth indicates whether $wgUser's permissions
2431 * @param string $reason is the log summary of the move, used for spam checking
2432 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2434 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2437 // Normally we'd add this to $errors, but we'll get
2438 // lots of syntax errors if $nt is not an object
2439 return array(array('badtitletext'));
2441 if( $this->equals( $nt ) ) {
2442 $errors[] = array('selfmove');
2444 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2445 $errors[] = array('immobile_namespace');
2448 $oldid = $this->getArticleID();
2449 $newid = $nt->getArticleID();
2451 if ( strlen( $nt->getDBkey() ) < 1 ) {
2452 $errors[] = array('articleexists');
2454 if ( ( '' == $this->getDBkey() ) ||
2456 ( '' == $nt->getDBkey() ) ) {
2457 $errors[] = array('badarticleerror');
2460 // Image-specific checks
2461 if( $this->getNamespace() == NS_IMAGE
) {
2462 $file = wfLocalFile( $this );
2463 if( $file->exists() ) {
2464 if( $nt->getNamespace() != NS_IMAGE
) {
2465 $errors[] = array('imagenocrossnamespace');
2467 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2468 $errors[] = array('imageinvalidfilename');
2470 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2471 $errors[] = array('imagetypemismatch');
2478 $errors = array_merge($errors,
2479 $this->getUserPermissionsErrors('move', $wgUser),
2480 $this->getUserPermissionsErrors('edit', $wgUser),
2481 $nt->getUserPermissionsErrors('move', $wgUser),
2482 $nt->getUserPermissionsErrors('edit', $wgUser));
2487 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2488 $errors[] = array('hookaborted', $err);
2491 # The move is allowed only if (1) the target doesn't exist, or
2492 # (2) the target is a redirect to the source, and has no history
2493 # (so we can undo bad moves right after they're done).
2495 if ( 0 != $newid ) { # Target exists; check for validity
2496 if ( ! $this->isValidMoveTarget( $nt ) ) {
2497 $errors[] = array('articleexists');
2500 $tp = $nt->getTitleProtection();
2501 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2502 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2503 $errors[] = array('cantmove-titleprotected');
2512 * Move a title to a new location
2513 * @param Title &$nt the new title
2514 * @param bool $auth indicates whether $wgUser's permissions
2516 * @param string $reason The reason for the move
2517 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2518 * Ignored if the user doesn't have the suppressredirect right.
2519 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2521 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2522 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2523 if( is_array( $err ) ) {
2527 $pageid = $this->getArticleID();
2528 if( $nt->exists() ) {
2529 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2530 $pageCountChange = ($createRedirect ?
0 : -1);
2531 } else { # Target didn't exist, do normal move.
2532 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2533 $pageCountChange = ($createRedirect ?
1 : 0);
2536 if( is_array( $err ) ) {
2539 $redirid = $this->getArticleID();
2541 // Category memberships include a sort key which may be customized.
2542 // If it's left as the default (the page title), we need to update
2543 // the sort key to match the new title.
2545 // Be careful to avoid resetting cl_timestamp, which may disturb
2546 // time-based lists on some sites.
2548 // Warning -- if the sort key is *explicitly* set to the old title,
2549 // we can't actually distinguish it from a default here, and it'll
2550 // be set to the new title even though it really shouldn't.
2551 // It'll get corrected on the next edit, but resetting cl_timestamp.
2552 $dbw = wfGetDB( DB_MASTER
);
2553 $dbw->update( 'categorylinks',
2555 'cl_sortkey' => $nt->getPrefixedText(),
2556 'cl_timestamp=cl_timestamp' ),
2558 'cl_from' => $pageid,
2559 'cl_sortkey' => $this->getPrefixedText() ),
2564 $oldnamespace = $this->getNamespace() & ~
1;
2565 $newnamespace = $nt->getNamespace() & ~
1;
2566 $oldtitle = $this->getDBkey();
2567 $newtitle = $nt->getDBkey();
2569 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2570 WatchedItem
::duplicateEntries( $this, $nt );
2573 # Update search engine
2574 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2576 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2580 if( $this->isContentPage() && !$nt->isContentPage() ) {
2581 # No longer a content page
2582 # Not viewed, edited, removing
2583 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2584 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2585 # Now a content page
2586 # Not viewed, edited, adding
2587 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2588 } elseif( $pageCountChange ) {
2590 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2597 # Update message cache for interface messages
2598 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2599 global $wgMessageCache;
2600 $oldarticle = new Article( $this );
2601 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2602 $newarticle = new Article( $nt );
2603 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2607 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2612 * Move page to a title which is at present a redirect to the
2615 * @param Title &$nt the page to move to, which should currently
2617 * @param string $reason The reason for the move
2618 * @param bool $createRedirect Whether to leave a redirect at the old title.
2619 * Ignored if the user doesn't have the suppressredirect right
2621 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2622 global $wgUseSquid, $wgUser;
2623 $fname = 'Title::moveOverExistingRedirect';
2624 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2627 $comment .= ": $reason";
2630 $now = wfTimestampNow();
2631 $newid = $nt->getArticleID();
2632 $oldid = $this->getArticleID();
2633 $latest = $this->getLatestRevID();
2635 $dbw = wfGetDB( DB_MASTER
);
2638 # Delete the old redirect. We don't save it to history since
2639 # by definition if we've got here it's rather uninteresting.
2640 # We have to remove it so that the next step doesn't trigger
2641 # a conflict on the unique namespace+title index...
2642 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2643 if ( !$dbw->cascadingDeletes() ) {
2644 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2645 global $wgUseTrackbacks;
2646 if ($wgUseTrackbacks)
2647 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2648 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2649 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2650 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2651 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2652 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2653 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2654 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2657 # Save a null revision in the page's history notifying of the move
2658 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2659 $nullRevId = $nullRevision->insertOn( $dbw );
2661 $article = new Article( $this );
2662 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2664 # Change the name of the target page:
2665 $dbw->update( 'page',
2667 'page_touched' => $dbw->timestamp($now),
2668 'page_namespace' => $nt->getNamespace(),
2669 'page_title' => $nt->getDBkey(),
2670 'page_latest' => $nullRevId,
2672 /* WHERE */ array( 'page_id' => $oldid ),
2675 $nt->resetArticleID( $oldid );
2677 # Recreate the redirect, this time in the other direction.
2678 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2679 $mwRedir = MagicWord
::get( 'redirect' );
2680 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2681 $redirectArticle = new Article( $this );
2682 $newid = $redirectArticle->insertOn( $dbw );
2683 $redirectRevision = new Revision( array(
2685 'comment' => $comment,
2686 'text' => $redirectText ) );
2687 $redirectRevision->insertOn( $dbw );
2688 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2690 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2692 # Now, we record the link from the redirect to the new title.
2693 # It should have no other outgoing links...
2694 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2695 $dbw->insert( 'pagelinks',
2697 'pl_from' => $newid,
2698 'pl_namespace' => $nt->getNamespace(),
2699 'pl_title' => $nt->getDBkey() ),
2702 $this->resetArticleID( 0 );
2705 # Move an image if this is a file
2706 if( $this->getNamespace() == NS_IMAGE
) {
2707 $file = wfLocalFile( $this );
2708 if( $file->exists() ) {
2709 $status = $file->move( $nt );
2710 if( !$status->isOk() ) {
2712 return $status->getErrorsArray();
2719 $log = new LogPage( 'move' );
2720 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2723 if ( $wgUseSquid ) {
2724 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2725 $u = new SquidUpdate( $urls );
2732 * Move page to non-existing title.
2733 * @param Title &$nt the new Title
2734 * @param string $reason The reason for the move
2735 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2736 * Ignored if the user doesn't have the suppressredirect right
2738 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2739 global $wgUseSquid, $wgUser;
2740 $fname = 'MovePageForm::moveToNewTitle';
2741 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2743 $comment .= ": $reason";
2746 $newid = $nt->getArticleID();
2747 $oldid = $this->getArticleID();
2748 $latest = $this->getLatestRevId();
2750 $dbw = wfGetDB( DB_MASTER
);
2752 $now = $dbw->timestamp();
2754 # Save a null revision in the page's history notifying of the move
2755 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2756 $nullRevId = $nullRevision->insertOn( $dbw );
2758 $article = new Article( $this );
2759 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2762 $dbw->update( 'page',
2764 'page_touched' => $now,
2765 'page_namespace' => $nt->getNamespace(),
2766 'page_title' => $nt->getDBkey(),
2767 'page_latest' => $nullRevId,
2769 /* WHERE */ array( 'page_id' => $oldid ),
2772 $nt->resetArticleID( $oldid );
2774 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2776 $mwRedir = MagicWord
::get( 'redirect' );
2777 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2778 $redirectArticle = new Article( $this );
2779 $newid = $redirectArticle->insertOn( $dbw );
2780 $redirectRevision = new Revision( array(
2782 'comment' => $comment,
2783 'text' => $redirectText ) );
2784 $redirectRevision->insertOn( $dbw );
2785 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2787 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2789 # Record the just-created redirect's linking to the page
2790 $dbw->insert( 'pagelinks',
2792 'pl_from' => $newid,
2793 'pl_namespace' => $nt->getNamespace(),
2794 'pl_title' => $nt->getDBkey() ),
2797 $this->resetArticleID( 0 );
2800 # Move an image if this is a file
2801 if( $this->getNamespace() == NS_IMAGE
) {
2802 $file = wfLocalFile( $this );
2803 if( $file->exists() ) {
2804 $status = $file->move( $nt );
2805 if( !$status->isOk() ) {
2807 return $status->getErrorsArray();
2814 $log = new LogPage( 'move' );
2815 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2817 # Purge caches as per article creation
2818 Article
::onArticleCreate( $nt );
2820 # Purge old title from squid
2821 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2822 $this->purgeSquid();
2827 * Checks if $this can be moved to a given Title
2828 * - Selects for update, so don't call it unless you mean business
2830 * @param Title &$nt the new title to check
2832 public function isValidMoveTarget( $nt ) {
2834 $fname = 'Title::isValidMoveTarget';
2835 $dbw = wfGetDB( DB_MASTER
);
2837 # Is it an existsing file?
2838 if( $nt->getNamespace() == NS_IMAGE
) {
2839 $file = wfLocalFile( $nt );
2840 if( $file->exists() ) {
2841 wfDebug( __METHOD__
. ": file exists\n" );
2847 $id = $nt->getArticleID();
2848 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2849 array( 'page_is_redirect','old_text','old_flags' ),
2850 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2851 $fname, 'FOR UPDATE' );
2853 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2855 wfDebug( __METHOD__
. ": not a redirect\n" );
2858 $text = Revision
::getRevisionText( $obj );
2860 # Does the redirect point to the source?
2861 # Or is it a broken self-redirect, usually caused by namespace collisions?
2863 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2864 $redirTitle = Title
::newFromText( $m[1] );
2865 if( !is_object( $redirTitle ) ||
2866 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2867 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2868 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2873 wfDebug( __METHOD__
. ": failsafe\n" );
2877 # Does the article have a history?
2878 $row = $dbw->selectRow( array( 'page', 'revision'),
2880 array( 'page_namespace' => $nt->getNamespace(),
2881 'page_title' => $nt->getDBkey(),
2882 'page_id=rev_page AND page_latest != rev_id'
2883 ), $fname, 'FOR UPDATE'
2886 # Return true if there was no history
2887 return $row === false;
2891 * Can this title be added to a user's watchlist?
2895 public function isWatchable() {
2896 return !$this->isExternal()
2897 && MWNamespace
::isWatchable( $this->getNamespace() );
2901 * Get categories to which this Title belongs and return an array of
2902 * categories' names.
2904 * @return array an array of parents in the form:
2905 * $parent => $currentarticle
2907 public function getParentCategories() {
2910 $titlekey = $this->getArticleId();
2911 $dbr = wfGetDB( DB_SLAVE
);
2912 $categorylinks = $dbr->tableName( 'categorylinks' );
2915 $sql = "SELECT * FROM $categorylinks"
2916 ." WHERE cl_from='$titlekey'"
2917 ." AND cl_from <> '0'"
2918 ." ORDER BY cl_sortkey";
2920 $res = $dbr->query( $sql );
2922 if( $dbr->numRows( $res ) > 0 ) {
2923 foreach( $res as $row )
2924 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2925 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2926 $dbr->freeResult( $res );
2934 * Get a tree of parent categories
2935 * @param array $children an array with the children in the keys, to check for circular refs
2938 public function getParentCategoryTree( $children = array() ) {
2940 $parents = $this->getParentCategories();
2943 foreach( $parents as $parent => $current ) {
2944 if ( array_key_exists( $parent, $children ) ) {
2945 # Circular reference
2946 $stack[$parent] = array();
2948 $nt = Title
::newFromText($parent);
2950 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2962 * Get an associative array for selecting this title from
2967 public function pageCond() {
2968 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2972 * Get the revision ID of the previous revision
2974 * @param integer $revId Revision ID. Get the revision that was before this one.
2975 * @param integer $flags, GAID_FOR_UPDATE
2976 * @return integer $oldrevision|false
2978 public function getPreviousRevisionID( $revId, $flags=0 ) {
2979 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2980 return $db->selectField( 'revision', 'rev_id',
2982 'rev_page' => $this->getArticleId($flags),
2983 'rev_id < ' . intval( $revId )
2986 array( 'ORDER BY' => 'rev_id DESC' )
2991 * Get the revision ID of the next revision
2993 * @param integer $revId Revision ID. Get the revision that was after this one.
2994 * @param integer $flags, GAID_FOR_UPDATE
2995 * @return integer $oldrevision|false
2997 public function getNextRevisionID( $revId, $flags=0 ) {
2998 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2999 return $db->selectField( 'revision', 'rev_id',
3001 'rev_page' => $this->getArticleId($flags),
3002 'rev_id > ' . intval( $revId )
3005 array( 'ORDER BY' => 'rev_id' )
3010 * Get the number of revisions between the given revision IDs.
3011 * Used for diffs and other things that really need it.
3013 * @param integer $old Revision ID.
3014 * @param integer $new Revision ID.
3015 * @return integer Number of revisions between these IDs.
3017 public function countRevisionsBetween( $old, $new ) {
3018 $dbr = wfGetDB( DB_SLAVE
);
3019 return $dbr->selectField( 'revision', 'count(*)',
3020 'rev_page = ' . intval( $this->getArticleId() ) .
3021 ' AND rev_id > ' . intval( $old ) .
3022 ' AND rev_id < ' . intval( $new ),
3024 array( 'USE INDEX' => 'PRIMARY' ) );
3028 * Compare with another title.
3030 * @param Title $title
3033 public function equals( Title
$title ) {
3034 // Note: === is necessary for proper matching of number-like titles.
3035 return $this->getInterwiki() === $title->getInterwiki()
3036 && $this->getNamespace() == $title->getNamespace()
3037 && $this->getDBkey() === $title->getDBkey();
3041 * Callback for usort() to do title sorts by (namespace, title)
3043 static function compare( $a, $b ) {
3044 if( $a->getNamespace() == $b->getNamespace() ) {
3045 return strcmp( $a->getText(), $b->getText() );
3047 return $a->getNamespace() - $b->getNamespace();
3052 * Return a string representation of this title
3056 public function __toString() {
3057 return $this->getPrefixedText();
3061 * Check if page exists
3064 public function exists() {
3065 return $this->getArticleId() != 0;
3069 * Do we know that this title definitely exists, or should we otherwise
3070 * consider that it exists?
3074 public function isAlwaysKnown() {
3075 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3076 // the full l10n of that language to be loaded. That takes much memory and
3077 // isn't needed. So we strip the language part away.
3078 // Also, extension messages which are not loaded, are shown as red, because
3079 // we don't call MessageCache::loadAllMessages.
3080 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3081 return $this->isExternal()
3082 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3083 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3087 * Update page_touched timestamps and send squid purge messages for
3088 * pages linking to this title. May be sent to the job queue depending
3089 * on the number of links. Typically called on create and delete.
3091 public function touchLinks() {
3092 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3095 if ( $this->getNamespace() == NS_CATEGORY
) {
3096 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3102 * Get the last touched timestamp
3104 public function getTouched() {
3105 $dbr = wfGetDB( DB_SLAVE
);
3106 $touched = $dbr->selectField( 'page', 'page_touched',
3108 'page_namespace' => $this->getNamespace(),
3109 'page_title' => $this->getDBkey()
3115 public function trackbackURL() {
3116 global $wgTitle, $wgScriptPath, $wgServer;
3118 return "$wgServer$wgScriptPath/trackback.php?article="
3119 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3122 public function trackbackRDF() {
3123 $url = htmlspecialchars($this->getFullURL());
3124 $title = htmlspecialchars($this->getText());
3125 $tburl = $this->trackbackURL();
3127 // Autodiscovery RDF is placed in comments so HTML validator
3128 // won't barf. This is a rather icky workaround, but seems
3129 // frequently used by this kind of RDF thingy.
3131 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3133 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3134 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3135 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3138 dc:identifier=\"$url\"
3140 trackback:ping=\"$tburl\" />
3146 * Generate strings used for xml 'id' names in monobook tabs
3149 public function getNamespaceKey() {
3151 switch ($this->getNamespace()) {
3154 return 'nstab-main';
3157 return 'nstab-user';
3159 return 'nstab-media';
3161 return 'nstab-special';
3163 case NS_PROJECT_TALK
:
3164 return 'nstab-project';
3167 return 'nstab-image';
3169 case NS_MEDIAWIKI_TALK
:
3170 return 'nstab-mediawiki';
3172 case NS_TEMPLATE_TALK
:
3173 return 'nstab-template';
3176 return 'nstab-help';
3178 case NS_CATEGORY_TALK
:
3179 return 'nstab-category';
3181 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3186 * Returns true if this title resolves to the named special page
3187 * @param string $name The special page name
3189 public function isSpecial( $name ) {
3190 if ( $this->getNamespace() == NS_SPECIAL
) {
3191 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3192 if ( $name == $thisName ) {
3200 * If the Title refers to a special page alias which is not the local default,
3201 * returns a new Title which points to the local default. Otherwise, returns $this.
3203 public function fixSpecialName() {
3204 if ( $this->getNamespace() == NS_SPECIAL
) {
3205 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3206 if ( $canonicalName ) {
3207 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3208 if ( $localName != $this->mDbkeyform
) {
3209 return Title
::makeTitle( NS_SPECIAL
, $localName );
3217 * Is this Title in a namespace which contains content?
3218 * In other words, is this a content page, for the purposes of calculating
3223 public function isContentPage() {
3224 return MWNamespace
::isContent( $this->getNamespace() );
3227 public function getRedirectsHere( $ns = null ) {
3230 $dbr = wfGetDB( DB_SLAVE
);
3232 'rd_namespace' => $this->getNamespace(),
3233 'rd_title' => $this->getDBkey(),
3236 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3238 $res = $dbr->select(
3239 array( 'redirect', 'page' ),
3240 array( 'page_namespace', 'page_title' ),
3246 foreach( $res as $row ) {
3247 $redirs[] = self
::newFromRow( $row );