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' );
300 if( $redir->matchStartAndRemove( $text ) ) {
301 // Extract the first link and see if it's usable
302 // Ensure that it really does come directly after #REDIRECT
303 // Some older redirects included a colon, so don't freak about that!
305 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
306 // Strip preceding colon used to "escape" categories, etc.
307 // and URL-decode links
308 if( strpos( $m[1], '%' ) !== false ) {
309 // Match behavior of inline link parsing here;
310 // don't interpret + as " " most of the time!
311 // It might be safe to just use rawurldecode instead, though.
312 $m[1] = urldecode( ltrim( $m[1], ':' ) );
314 $title = Title
::newFromText( $m[1] );
315 // Redirects to Special:Userlogout are not permitted
316 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
323 #----------------------------------------------------------------------------
325 #----------------------------------------------------------------------------
328 * Get the prefixed DB key associated with an ID
329 * @param int $id the page_id of the article
330 * @return Title an object representing the article, or NULL
331 * if no such article was found
333 public static function nameOf( $id ) {
334 $dbr = wfGetDB( DB_SLAVE
);
336 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
337 if ( $s === false ) { return NULL; }
339 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
344 * Get a regex character class describing the legal characters in a link
345 * @return string the list of characters, not delimited
347 public static function legalChars() {
348 global $wgLegalTitleChars;
349 return $wgLegalTitleChars;
353 * Get a string representation of a title suitable for
354 * including in a search index
356 * @param int $ns a namespace index
357 * @param string $title text-form main part
358 * @return string a stripped-down title string ready for the
361 public static function indexTitle( $ns, $title ) {
364 $lc = SearchEngine
::legalSearchChars() . '&#;';
365 $t = $wgContLang->stripForSearch( $title );
366 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
367 $t = $wgContLang->lc( $t );
370 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
371 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
373 $t = preg_replace( "/\\s+/", ' ', $t );
375 if ( $ns == NS_IMAGE
) {
376 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
382 * Make a prefixed DB key from a DB key and a namespace index
383 * @param int $ns numerical representation of the namespace
384 * @param string $title the DB key form the title
385 * @param string $fragment The link fragment (after the "#")
386 * @return string the prefixed form of the title
388 public static function makeName( $ns, $title, $fragment = '' ) {
391 $namespace = $wgContLang->getNsText( $ns );
392 $name = $namespace == '' ?
$title : "$namespace:$title";
393 if ( strval( $fragment ) != '' ) {
394 $name .= '#' . $fragment;
400 * Returns the URL associated with an interwiki prefix
401 * @param string $key the interwiki prefix (e.g. "MeatBall")
402 * @return the associated URL, containing "$1", which should be
403 * replaced by an article title
406 public function getInterwikiLink( $key ) {
407 global $wgMemc, $wgInterwikiExpiry;
408 global $wgInterwikiCache, $wgContLang;
409 $fname = 'Title::getInterwikiLink';
411 $key = $wgContLang->lc( $key );
413 $k = wfMemcKey( 'interwiki', $key );
414 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
415 return Title
::$interwikiCache[$k]->iw_url
;
418 if ($wgInterwikiCache) {
419 return Title
::getInterwikiCached( $key );
422 $s = $wgMemc->get( $k );
423 # Ignore old keys with no iw_local
424 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
425 Title
::$interwikiCache[$k] = $s;
429 $dbr = wfGetDB( DB_SLAVE
);
430 $res = $dbr->select( 'interwiki',
431 array( 'iw_url', 'iw_local', 'iw_trans' ),
432 array( 'iw_prefix' => $key ), $fname );
437 $s = $dbr->fetchObject( $res );
439 # Cache non-existence: create a blank object and save it to memcached
445 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
446 Title
::$interwikiCache[$k] = $s;
452 * Fetch interwiki prefix data from local cache in constant database
454 * More logic is explained in DefaultSettings
456 * @return string URL of interwiki site
458 public static function getInterwikiCached( $key ) {
459 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
463 $db=dba_open($wgInterwikiCache,'r','cdb');
464 /* Resolve site name */
465 if ($wgInterwikiScopes>=3 and !$site) {
466 $site = dba_fetch('__sites:' . wfWikiID(), $db);
468 $site = $wgInterwikiFallbackSite;
470 $value = dba_fetch( wfMemcKey( $key ), $db);
471 if ($value=='' and $wgInterwikiScopes>=3) {
473 $value = dba_fetch("_{$site}:{$key}", $db);
475 if ($value=='' and $wgInterwikiScopes>=2) {
477 $value = dba_fetch("__global:{$key}", $db);
486 list($local,$url)=explode(' ',$value,2);
488 $s->iw_local
=(int)$local;
490 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
494 * Determine whether the object refers to a page within
497 * @return bool TRUE if this is an in-project interwiki link
498 * or a wikilink, FALSE otherwise
500 public function isLocal() {
501 if ( $this->mInterwiki
!= '' ) {
502 # Make sure key is loaded into cache
503 $this->getInterwikiLink( $this->mInterwiki
);
504 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
505 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
512 * Determine whether the object refers to a page within
513 * this project and is transcludable.
515 * @return bool TRUE if this is transcludable
517 public function isTrans() {
518 if ($this->mInterwiki
== '')
520 # Make sure key is loaded into cache
521 $this->getInterwikiLink( $this->mInterwiki
);
522 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
523 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
527 * Escape a text fragment, say from a link, for a URL
529 static function escapeFragmentForURL( $fragment ) {
530 $fragment = str_replace( ' ', '_', $fragment );
531 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
532 $replaceArray = array(
536 return strtr( $fragment, $replaceArray );
539 #----------------------------------------------------------------------------
541 #----------------------------------------------------------------------------
543 /** Simple accessors */
545 * Get the text form (spaces not underscores) of the main part
548 public function getText() { return $this->mTextform
; }
550 * Get the URL-encoded form of the main part
553 public function getPartialURL() { return $this->mUrlform
; }
555 * Get the main part with underscores
558 public function getDBkey() { return $this->mDbkeyform
; }
560 * Get the namespace index, i.e. one of the NS_xxxx constants
563 public function getNamespace() { return $this->mNamespace
; }
565 * Get the namespace text
568 public function getNsText() {
569 global $wgContLang, $wgCanonicalNamespaceNames;
571 if ( '' != $this->mInterwiki
) {
572 // This probably shouldn't even happen. ohh man, oh yuck.
573 // But for interwiki transclusion it sometimes does.
574 // Shit. Shit shit shit.
576 // Use the canonical namespaces if possible to try to
577 // resolve a foreign namespace.
578 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
579 return $wgCanonicalNamespaceNames[$this->mNamespace
];
582 return $wgContLang->getNsText( $this->mNamespace
);
585 * Get the DB key with the initial letter case as specified by the user
587 function getUserCaseDBKey() {
588 return $this->mUserCaseDBKey
;
591 * Get the namespace text of the subject (rather than talk) page
594 public function getSubjectNsText() {
596 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
600 * Get the namespace text of the talk page
603 public function getTalkNsText() {
605 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
609 * Could this title have a corresponding talk page?
612 public function canTalk() {
613 return( MWNamespace
::canTalk( $this->mNamespace
) );
617 * Get the interwiki prefix (or null string)
620 public function getInterwiki() { return $this->mInterwiki
; }
622 * Get the Title fragment (i.e. the bit after the #) in text form
625 public function getFragment() { return $this->mFragment
; }
627 * Get the fragment in URL form, including the "#" character if there is one
630 public function getFragmentForURL() {
631 if ( $this->mFragment
== '' ) {
634 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
638 * Get the default namespace index, for when there is no namespace
641 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
644 * Get title for search index
645 * @return string a stripped-down title string ready for the
648 public function getIndexTitle() {
649 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
653 * Get the prefixed database key form
654 * @return string the prefixed title, with underscores and
655 * any interwiki and namespace prefixes
657 public function getPrefixedDBkey() {
658 $s = $this->prefix( $this->mDbkeyform
);
659 $s = str_replace( ' ', '_', $s );
664 * Get the prefixed title with spaces.
665 * This is the form usually used for display
666 * @return string the prefixed title, with spaces
668 public function getPrefixedText() {
669 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
670 $s = $this->prefix( $this->mTextform
);
671 $s = str_replace( '_', ' ', $s );
672 $this->mPrefixedText
= $s;
674 return $this->mPrefixedText
;
678 * Get the prefixed title with spaces, plus any fragment
679 * (part beginning with '#')
680 * @return string the prefixed title, with spaces and
681 * the fragment, including '#'
683 public function getFullText() {
684 $text = $this->getPrefixedText();
685 if( '' != $this->mFragment
) {
686 $text .= '#' . $this->mFragment
;
692 * Get the base name, i.e. the leftmost parts before the /
693 * @return string Base name
695 public function getBaseText() {
696 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
697 return $this->getText();
700 $parts = explode( '/', $this->getText() );
701 # Don't discard the real title if there's no subpage involved
702 if( count( $parts ) > 1 )
703 unset( $parts[ count( $parts ) - 1 ] );
704 return implode( '/', $parts );
708 * Get the lowest-level subpage name, i.e. the rightmost part after /
709 * @return string Subpage name
711 public function getSubpageText() {
712 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
713 return( $this->mTextform
);
715 $parts = explode( '/', $this->mTextform
);
716 return( $parts[ count( $parts ) - 1 ] );
720 * Get a URL-encoded form of the subpage text
721 * @return string URL-encoded subpage name
723 public function getSubpageUrlForm() {
724 $text = $this->getSubpageText();
725 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
726 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
731 * Get a URL-encoded title (not an actual URL) including interwiki
732 * @return string the URL-encoded form
734 public function getPrefixedURL() {
735 $s = $this->prefix( $this->mDbkeyform
);
736 $s = str_replace( ' ', '_', $s );
738 $s = wfUrlencode ( $s ) ;
740 # Cleaning up URL to make it look nice -- is this safe?
741 $s = str_replace( '%28', '(', $s );
742 $s = str_replace( '%29', ')', $s );
748 * Get a real URL referring to this title, with interwiki link and
751 * @param array $query an optional query string, not used for interwiki
752 * links. Can be specified as an associative array as well, e.g.,
753 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
754 * @param string $variant language variant of url (for sr, zh..)
755 * @return string the URL
757 public function getFullURL( $query = '', $variant = false ) {
758 global $wgContLang, $wgServer, $wgRequest;
760 if( is_array( $query ) ) {
761 $query = wfArrayToCGI( $query );
764 if ( '' == $this->mInterwiki
) {
765 $url = $this->getLocalUrl( $query, $variant );
767 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
768 // Correct fix would be to move the prepending elsewhere.
769 if ($wgRequest->getVal('action') != 'render') {
770 $url = $wgServer . $url;
773 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
775 $namespace = wfUrlencode( $this->getNsText() );
776 if ( '' != $namespace ) {
777 # Can this actually happen? Interwikis shouldn't be parsed.
778 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
781 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
782 $url = wfAppendQuery( $url, $query );
785 # Finally, add the fragment.
786 $url .= $this->getFragmentForURL();
788 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
793 * Get a URL with no fragment or server name. If this page is generated
794 * with action=render, $wgServer is prepended.
795 * @param mixed $query an optional query string; if not specified,
796 * $wgArticlePath will be used. Can be specified as an associative array
797 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
799 * @param string $variant language variant of url (for sr, zh..)
800 * @return string the URL
802 public function getLocalURL( $query = '', $variant = false ) {
803 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
804 global $wgVariantArticlePath, $wgContLang, $wgUser;
806 if( is_array( $query ) ) {
807 $query = wfArrayToCGI( $query );
810 // internal links should point to same variant as current page (only anonymous users)
811 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
812 $pref = $wgContLang->getPreferredVariant(false);
813 if($pref != $wgContLang->getCode())
817 if ( $this->isExternal() ) {
818 $url = $this->getFullURL();
820 // This is currently only used for edit section links in the
821 // context of interwiki transclusion. In theory we should
822 // append the query to the end of any existing query string,
823 // but interwiki transclusion is already broken in that case.
827 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
828 if ( $query == '' ) {
829 if( $variant != false && $wgContLang->hasVariants() ) {
830 if( $wgVariantArticlePath == false ) {
831 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
833 $variantArticlePath = $wgVariantArticlePath;
835 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
836 $url = str_replace( '$1', $dbkey, $url );
838 $url = str_replace( '$1', $dbkey, $wgArticlePath );
841 global $wgActionPaths;
844 if( !empty( $wgActionPaths ) &&
845 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
847 $action = urldecode( $matches[2] );
848 if( isset( $wgActionPaths[$action] ) ) {
849 $query = $matches[1];
850 if( isset( $matches[4] ) ) $query .= $matches[4];
851 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
852 if( $query != '' ) $url .= '?' . $query;
855 if ( $url === false ) {
856 if ( $query == '-' ) {
859 $url = "{$wgScript}?title={$dbkey}&{$query}";
863 // FIXME: this causes breakage in various places when we
864 // actually expected a local URL and end up with dupe prefixes.
865 if ($wgRequest->getVal('action') == 'render') {
866 $url = $wgServer . $url;
869 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
874 * Get a URL that's the simplest URL that will be valid to link, locally,
875 * to the current Title. It includes the fragment, but does not include
876 * the server unless action=render is used (or the link is external). If
877 * there's a fragment but the prefixed text is empty, we just return a link
880 * @param array $query An associative array of key => value pairs for the
881 * query string. Keys and values will be escaped.
882 * @param string $variant Language variant of URL (for sr, zh..). Ignored
883 * for external links. Default is "false" (same variant as current page,
884 * for anonymous users).
885 * @return string the URL
887 public function getLinkUrl( $query = array(), $variant = false ) {
888 if( !is_array( $query ) ) {
889 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
892 if( $this->isExternal() ) {
893 return $this->getFullURL( $query );
894 } elseif( $this->getPrefixedText() === ''
895 and $this->getFragment() !== '' ) {
896 return $this->getFragmentForURL();
898 return $this->getLocalURL( $query, $variant )
899 . $this->getFragmentForURL();
904 * Get an HTML-escaped version of the URL form, suitable for
905 * using in a link, without a server name or fragment
906 * @param string $query an optional query string
907 * @return string the URL
909 public function escapeLocalURL( $query = '' ) {
910 return htmlspecialchars( $this->getLocalURL( $query ) );
914 * Get an HTML-escaped version of the URL form, suitable for
915 * using in a link, including the server name and fragment
917 * @return string the URL
918 * @param string $query an optional query string
920 public function escapeFullURL( $query = '' ) {
921 return htmlspecialchars( $this->getFullURL( $query ) );
925 * Get the URL form for an internal link.
926 * - Used in various Squid-related code, in case we have a different
927 * internal hostname for the server from the exposed one.
929 * @param string $query an optional query string
930 * @param string $variant language variant of url (for sr, zh..)
931 * @return string the URL
933 public function getInternalURL( $query = '', $variant = false ) {
934 global $wgInternalServer;
935 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
936 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
941 * Get the edit URL for this Title
942 * @return string the URL, or a null string if this is an
945 public function getEditURL() {
946 if ( '' != $this->mInterwiki
) { return ''; }
947 $s = $this->getLocalURL( 'action=edit' );
953 * Get the HTML-escaped displayable text form.
954 * Used for the title field in <a> tags.
955 * @return string the text, including any prefixes
957 public function getEscapedText() {
958 return htmlspecialchars( $this->getPrefixedText() );
962 * Is this Title interwiki?
965 public function isExternal() { return ( '' != $this->mInterwiki
); }
968 * Is this page "semi-protected" - the *only* protection is autoconfirm?
970 * @param string Action to check (default: edit)
973 public function isSemiProtected( $action = 'edit' ) {
974 if( $this->exists() ) {
975 $restrictions = $this->getRestrictions( $action );
976 if( count( $restrictions ) > 0 ) {
977 foreach( $restrictions as $restriction ) {
978 if( strtolower( $restriction ) != 'autoconfirmed' )
987 # If it doesn't exist, it can't be protected
993 * Does the title correspond to a protected article?
994 * @param string $what the action the page is protected from,
995 * by default checks move and edit
998 public function isProtected( $action = '' ) {
999 global $wgRestrictionLevels, $wgRestrictionTypes;
1001 # Special pages have inherent protection
1002 if( $this->getNamespace() == NS_SPECIAL
)
1005 # Check regular protection levels
1006 foreach( $wgRestrictionTypes as $type ){
1007 if( $action == $type ||
$action == '' ) {
1008 $r = $this->getRestrictions( $type );
1009 foreach( $wgRestrictionLevels as $level ) {
1010 if( in_array( $level, $r ) && $level != '' ) {
1021 * Is $wgUser watching this page?
1024 public function userIsWatching() {
1027 if ( is_null( $this->mWatched
) ) {
1028 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1029 $this->mWatched
= false;
1031 $this->mWatched
= $wgUser->isWatched( $this );
1034 return $this->mWatched
;
1038 * Can $wgUser perform $action on this page?
1039 * This skips potentially expensive cascading permission checks.
1041 * Suitable for use for nonessential UI controls in common cases, but
1042 * _not_ for functional access control.
1044 * May provide false positives, but should never provide a false negative.
1046 * @param string $action action that permission needs to be checked for
1049 public function quickUserCan( $action ) {
1050 return $this->userCan( $action, false );
1054 * Determines if $wgUser is unable to edit this page because it has been protected
1055 * by $wgNamespaceProtection.
1059 public function isNamespaceProtected() {
1060 global $wgNamespaceProtection, $wgUser;
1061 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1062 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1063 if( $right != '' && !$wgUser->isAllowed( $right ) )
1071 * Can $wgUser perform $action on this page?
1072 * @param string $action action that permission needs to be checked for
1073 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1076 public function userCan( $action, $doExpensiveQueries = true ) {
1078 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1082 * Can $user perform $action on this page?
1084 * FIXME: This *does not* check throttles (User::pingLimiter()).
1086 * @param string $action action that permission needs to be checked for
1087 * @param User $user user to check
1088 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1089 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1090 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1092 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1093 if( !StubObject
::isRealObject( $user ) ) {
1094 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1096 $wgUser->_unstub( '', 5 );
1099 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1103 global $wgEmailConfirmToEdit;
1105 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1106 $errors[] = array( 'confirmedittext' );
1109 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1110 $block = $user->mBlock
;
1112 // This is from OutputPage::blockedPage
1113 // Copied at r23888 by werdna
1115 $id = $user->blockedBy();
1116 $reason = $user->blockedFor();
1117 if( $reason == '' ) {
1118 $reason = wfMsg( 'blockednoreason' );
1122 if ( is_numeric( $id ) ) {
1123 $name = User
::whoIs( $id );
1128 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1129 $blockid = $block->mId
;
1130 $blockExpiry = $user->mBlock
->mExpiry
;
1131 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1133 if ( $blockExpiry == 'infinity' ) {
1134 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1135 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1137 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1138 if ( strpos( $option, ':' ) == false )
1141 list ($show, $value) = explode( ":", $option );
1143 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1144 $blockExpiry = $show;
1149 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1152 $intended = $user->mBlock
->mAddress
;
1154 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1155 $blockid, $blockExpiry, $intended, $blockTimestamp );
1158 // Remove the errors being ignored.
1160 foreach( $errors as $index => $error ) {
1161 $error_key = is_array($error) ?
$error[0] : $error;
1163 if (in_array( $error_key, $ignoreErrors )) {
1164 unset($errors[$index]);
1172 * Can $user perform $action on this page? This is an internal function,
1173 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1174 * checks on wfReadOnly() and blocks)
1176 * @param string $action action that permission needs to be checked for
1177 * @param User $user user to check
1178 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1179 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1181 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1182 wfProfileIn( __METHOD__
);
1186 // Use getUserPermissionsErrors instead
1187 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1188 wfProfileOut( __METHOD__
);
1189 return $result ?
array() : array( array( 'badaccess-group0' ) );
1192 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1193 if ($result != array() && is_array($result) && !is_array($result[0]))
1194 $errors[] = $result; # A single array representing an error
1195 else if (is_array($result) && is_array($result[0]))
1196 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1197 else if ($result != '' && $result != null && $result !== true && $result !== false)
1198 $errors[] = array($result); # A string representing a message-id
1199 else if ($result === false )
1200 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1202 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1203 if ($result != array() && is_array($result) && !is_array($result[0]))
1204 $errors[] = $result; # A single array representing an error
1205 else if (is_array($result) && is_array($result[0]))
1206 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1207 else if ($result != '' && $result != null && $result !== true && $result !== false)
1208 $errors[] = array($result); # A string representing a message-id
1209 else if ($result === false )
1210 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1213 $specialOKActions = array( 'createaccount', 'execute' );
1214 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1215 $errors[] = array('ns-specialprotected');
1218 if ( $this->isNamespaceProtected() ) {
1219 $ns = $this->getNamespace() == NS_MAIN
1220 ?
wfMsg( 'nstab-main' )
1221 : $this->getNsText();
1222 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1223 ?
array('protectedinterface')
1224 : array( 'namespaceprotected', $ns ) );
1227 if( $this->mDbkeyform
== '_' ) {
1228 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1229 $errors[] = array('badaccess-group0');
1232 # protect css/js subpages of user pages
1233 # XXX: this might be better using restrictions
1234 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1235 if( $this->isCssJsSubpage()
1236 && !$user->isAllowed('editusercssjs')
1237 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1238 $errors[] = array('customcssjsprotected');
1241 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1242 # We /could/ use the protection level on the source page, but it's fairly ugly
1243 # as we have to establish a precedence hierarchy for pages included by multiple
1244 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1245 # as they could remove the protection anyway.
1246 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1247 # Cascading protection depends on more than this page...
1248 # Several cascading protected pages may include this page...
1249 # Check each cascading level
1250 # This is only for protection restrictions, not for all actions
1251 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1252 foreach( $restrictions[$action] as $right ) {
1253 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1254 if( '' != $right && !$user->isAllowed( $right ) ) {
1256 foreach( $cascadingSources as $page )
1257 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1258 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1264 foreach( $this->getRestrictions($action) as $right ) {
1265 // Backwards compatibility, rewrite sysop -> protect
1266 if ( $right == 'sysop' ) {
1269 if( '' != $right && !$user->isAllowed( $right ) ) {
1270 //Users with 'editprotected' permission can edit protected pages
1271 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1272 //Users with 'editprotected' permission cannot edit protected pages
1273 //with cascading option turned on.
1274 if($this->mCascadeRestriction
) {
1275 $errors[] = array( 'protectedpagetext', $right );
1277 //Nothing, user can edit!
1280 $errors[] = array( 'protectedpagetext', $right );
1285 if ($action == 'protect') {
1286 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1287 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1291 if ($action == 'create') {
1292 $title_protection = $this->getTitleProtection();
1294 if (is_array($title_protection)) {
1295 extract($title_protection);
1297 if ($pt_create_perm == 'sysop')
1298 $pt_create_perm = 'protect';
1300 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1301 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1305 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1306 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1307 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1309 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1310 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1311 } elseif ( !$user->isAllowed( $action ) ) {
1313 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1314 User
::getGroupsWithPermission( $action ) );
1316 $return = array( 'badaccess-groups',
1318 implode( ', ', $groups ),
1319 count( $groups ) ) );
1322 $return = array( "badaccess-group0" );
1324 $errors[] = $return;
1327 wfProfileOut( __METHOD__
);
1332 * Is this title subject to title protection?
1333 * @return mixed An associative array representing any existent title
1334 * protection, or false if there's none.
1336 private function getTitleProtection() {
1337 // Can't protect pages in special namespaces
1338 if ( $this->getNamespace() < 0 ) {
1342 $dbr = wfGetDB( DB_SLAVE
);
1343 $res = $dbr->select( 'protected_titles', '*',
1344 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1346 if ($row = $dbr->fetchRow( $res )) {
1353 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1354 global $wgUser,$wgContLang;
1356 if ($create_perm == implode(',',$this->getRestrictions('create'))
1357 && $expiry == $this->mRestrictionsExpiry
) {
1362 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1364 $dbw = wfGetDB( DB_MASTER
);
1366 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1368 $expiry_description = '';
1369 if ( $encodedExpiry != 'infinity' ) {
1370 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1373 # Update protection table
1374 if ($create_perm != '' ) {
1375 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1376 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1377 , 'pt_create_perm' => $create_perm
1378 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1379 , 'pt_expiry' => $encodedExpiry
1380 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1382 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1383 'pt_title' => $title ), __METHOD__
);
1385 # Update the protection log
1386 $log = new LogPage( 'protect' );
1388 if( $create_perm ) {
1389 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1391 $log->addEntry( 'unprotect', $this, $reason );
1398 * Remove any title protection (due to page existing
1400 public function deleteTitleProtection() {
1401 $dbw = wfGetDB( DB_MASTER
);
1403 $dbw->delete( 'protected_titles',
1404 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1408 * Can $wgUser edit this page?
1410 * @deprecated use userCan('edit')
1412 public function userCanEdit( $doExpensiveQueries = true ) {
1413 return $this->userCan( 'edit', $doExpensiveQueries );
1417 * Can $wgUser create this page?
1419 * @deprecated use userCan('create')
1421 public function userCanCreate( $doExpensiveQueries = true ) {
1422 return $this->userCan( 'create', $doExpensiveQueries );
1426 * Can $wgUser move this page?
1428 * @deprecated use userCan('move')
1430 public function userCanMove( $doExpensiveQueries = true ) {
1431 return $this->userCan( 'move', $doExpensiveQueries );
1435 * Would anybody with sufficient privileges be able to move this page?
1436 * Some pages just aren't movable.
1440 public function isMovable() {
1441 return MWNamespace
::isMovable( $this->getNamespace() )
1442 && $this->getInterwiki() == '';
1446 * Can $wgUser read this page?
1448 * @todo fold these checks into userCan()
1450 public function userCanRead() {
1451 global $wgUser, $wgGroupPermissions;
1454 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1455 if ( $result !== null ) {
1459 # Shortcut for public wikis, allows skipping quite a bit of code
1460 if ($wgGroupPermissions['*']['read'])
1463 if( $wgUser->isAllowed( 'read' ) ) {
1466 global $wgWhitelistRead;
1469 * Always grant access to the login page.
1470 * Even anons need to be able to log in.
1472 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1477 * Bail out if there isn't whitelist
1479 if( !is_array($wgWhitelistRead) ) {
1484 * Check for explicit whitelisting
1486 $name = $this->getPrefixedText();
1487 $dbName = $this->getPrefixedDBKey();
1488 // Check with and without underscores
1489 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1493 * Old settings might have the title prefixed with
1494 * a colon for main-namespace pages
1496 if( $this->getNamespace() == NS_MAIN
) {
1497 if( in_array( ':' . $name, $wgWhitelistRead ) )
1502 * If it's a special page, ditch the subpage bit
1505 if( $this->getNamespace() == NS_SPECIAL
) {
1506 $name = $this->getDBkey();
1507 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1508 if ( $name === false ) {
1509 # Invalid special page, but we show standard login required message
1513 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1514 if( in_array( $pure, $wgWhitelistRead, true ) )
1523 * Is this a talk page of some sort?
1526 public function isTalkPage() {
1527 return MWNamespace
::isTalk( $this->getNamespace() );
1531 * Is this a subpage?
1534 public function isSubpage() {
1535 return MWNamespace
::hasSubpages( $this->mNamespace
)
1536 ?
strpos( $this->getText(), '/' ) !== false
1541 * Does this have subpages? (Warning, usually requires an extra DB query.)
1544 public function hasSubpages() {
1545 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1550 # We dynamically add a member variable for the purpose of this method
1551 # alone to cache the result. There's no point in having it hanging
1552 # around uninitialized in every Title object; therefore we only add it
1553 # if needed and don't declare it statically.
1554 if( isset( $this->mHasSubpages
) ) {
1555 return $this->mHasSubpages
;
1558 $db = wfGetDB( DB_SLAVE
);
1559 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1560 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1561 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1567 * Could this page contain custom CSS or JavaScript, based
1572 public function isCssOrJsPage() {
1573 return $this->mNamespace
== NS_MEDIAWIKI
1574 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1578 * Is this a .css or .js subpage of a user page?
1581 public function isCssJsSubpage() {
1582 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1585 * Is this a *valid* .css or .js subpage of a user page?
1586 * Check that the corresponding skin exists
1588 public function isValidCssJsSubpage() {
1589 if ( $this->isCssJsSubpage() ) {
1590 $skinNames = Skin
::getSkinNames();
1591 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1597 * Trim down a .css or .js subpage title to get the corresponding skin name
1599 public function getSkinFromCssJsSubpage() {
1600 $subpage = explode( '/', $this->mTextform
);
1601 $subpage = $subpage[ count( $subpage ) - 1 ];
1602 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1605 * Is this a .css subpage of a user page?
1608 public function isCssSubpage() {
1609 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1612 * Is this a .js subpage of a user page?
1615 public function isJsSubpage() {
1616 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1619 * Protect css/js subpages of user pages: can $wgUser edit
1623 * @todo XXX: this might be better using restrictions
1625 public function userCanEditCssJsSubpage() {
1627 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1631 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1633 * @return bool If the page is subject to cascading restrictions.
1635 public function isCascadeProtected() {
1636 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1637 return ( $sources > 0 );
1641 * Cascading protection: Get the source of any cascading restrictions on this page.
1643 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1644 * @return array( mixed title array, restriction array)
1645 * 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.
1646 * The restriction array is an array of each type, each of which contains an array of unique groups
1648 public function getCascadeProtectionSources( $get_pages = true ) {
1649 global $wgRestrictionTypes;
1651 # Define our dimension of restrictions types
1652 $pagerestrictions = array();
1653 foreach( $wgRestrictionTypes as $action )
1654 $pagerestrictions[$action] = array();
1656 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1657 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1658 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1659 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1662 wfProfileIn( __METHOD__
);
1664 $dbr = wfGetDb( DB_SLAVE
);
1666 if ( $this->getNamespace() == NS_IMAGE
) {
1667 $tables = array ('imagelinks', 'page_restrictions');
1668 $where_clauses = array(
1669 'il_to' => $this->getDBkey(),
1671 'pr_cascade' => 1 );
1673 $tables = array ('templatelinks', 'page_restrictions');
1674 $where_clauses = array(
1675 'tl_namespace' => $this->getNamespace(),
1676 'tl_title' => $this->getDBkey(),
1678 'pr_cascade' => 1 );
1682 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1683 $where_clauses[] = 'page_id=pr_page';
1686 $cols = array( 'pr_expiry' );
1689 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1691 $sources = $get_pages ?
array() : false;
1692 $now = wfTimestampNow();
1693 $purgeExpired = false;
1695 foreach( $res as $row ) {
1696 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1697 if( $expiry > $now ) {
1699 $page_id = $row->pr_page
;
1700 $page_ns = $row->page_namespace
;
1701 $page_title = $row->page_title
;
1702 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1703 # Add groups needed for each restriction type if its not already there
1704 # Make sure this restriction type still exists
1705 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1706 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1712 // Trigger lazy purge of expired restrictions from the db
1713 $purgeExpired = true;
1716 if( $purgeExpired ) {
1717 Title
::purgeExpiredRestrictions();
1720 wfProfileOut( __METHOD__
);
1723 $this->mCascadeSources
= $sources;
1724 $this->mCascadingRestrictions
= $pagerestrictions;
1726 $this->mHasCascadingRestrictions
= $sources;
1729 return array( $sources, $pagerestrictions );
1732 function areRestrictionsCascading() {
1733 if (!$this->mRestrictionsLoaded
) {
1734 $this->loadRestrictions();
1737 return $this->mCascadeRestriction
;
1741 * Loads a string into mRestrictions array
1742 * @param resource $res restrictions as an SQL result.
1744 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1745 global $wgRestrictionTypes;
1746 $dbr = wfGetDB( DB_SLAVE
);
1748 foreach( $wgRestrictionTypes as $type ){
1749 $this->mRestrictions
[$type] = array();
1752 $this->mCascadeRestriction
= false;
1753 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1755 # Backwards-compatibility: also load the restrictions from the page record (old format).
1757 if ( $oldFashionedRestrictions === NULL ) {
1758 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1759 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1762 if ($oldFashionedRestrictions != '') {
1764 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1765 $temp = explode( '=', trim( $restrict ) );
1766 if(count($temp) == 1) {
1767 // old old format should be treated as edit/move restriction
1768 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1769 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1771 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1775 $this->mOldRestrictions
= true;
1779 if( $dbr->numRows( $res ) ) {
1780 # Current system - load second to make them override.
1781 $now = wfTimestampNow();
1782 $purgeExpired = false;
1784 foreach( $res as $row ) {
1785 # Cycle through all the restrictions.
1787 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1788 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1791 // This code should be refactored, now that it's being used more generally,
1792 // But I don't really see any harm in leaving it in Block for now -werdna
1793 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1795 // Only apply the restrictions if they haven't expired!
1796 if ( !$expiry ||
$expiry > $now ) {
1797 $this->mRestrictionsExpiry
= $expiry;
1798 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1800 $this->mCascadeRestriction |
= $row->pr_cascade
;
1802 // Trigger a lazy purge of expired restrictions
1803 $purgeExpired = true;
1807 if( $purgeExpired ) {
1808 Title
::purgeExpiredRestrictions();
1812 $this->mRestrictionsLoaded
= true;
1815 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1816 if( !$this->mRestrictionsLoaded
) {
1817 if ($this->exists()) {
1818 $dbr = wfGetDB( DB_SLAVE
);
1820 $res = $dbr->select( 'page_restrictions', '*',
1821 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1823 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1825 $title_protection = $this->getTitleProtection();
1827 if (is_array($title_protection)) {
1828 extract($title_protection);
1830 $now = wfTimestampNow();
1831 $expiry = Block
::decodeExpiry($pt_expiry);
1833 if (!$expiry ||
$expiry > $now) {
1834 // Apply the restrictions
1835 $this->mRestrictionsExpiry
= $expiry;
1836 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1837 } else { // Get rid of the old restrictions
1838 Title
::purgeExpiredRestrictions();
1841 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1843 $this->mRestrictionsLoaded
= true;
1849 * Purge expired restrictions from the page_restrictions table
1851 static function purgeExpiredRestrictions() {
1852 $dbw = wfGetDB( DB_MASTER
);
1853 $dbw->delete( 'page_restrictions',
1854 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1857 $dbw->delete( 'protected_titles',
1858 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1863 * Accessor/initialisation for mRestrictions
1865 * @param string $action action that permission needs to be checked for
1866 * @return array the array of groups allowed to edit this article
1868 public function getRestrictions( $action ) {
1869 if( !$this->mRestrictionsLoaded
) {
1870 $this->loadRestrictions();
1872 return isset( $this->mRestrictions
[$action] )
1873 ?
$this->mRestrictions
[$action]
1878 * Is there a version of this page in the deletion archive?
1879 * @return int the number of archived revisions
1881 public function isDeleted() {
1882 $fname = 'Title::isDeleted';
1883 if ( $this->getNamespace() < 0 ) {
1886 $dbr = wfGetDB( DB_SLAVE
);
1887 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1888 'ar_title' => $this->getDBkey() ), $fname );
1889 if( $this->getNamespace() == NS_IMAGE
) {
1890 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1891 array( 'fa_name' => $this->getDBkey() ), $fname );
1898 * Get the article ID for this Title from the link cache,
1899 * adding it if necessary
1900 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1902 * @return int the ID
1904 public function getArticleID( $flags = 0 ) {
1905 $linkCache = LinkCache
::singleton();
1906 if ( $flags & GAID_FOR_UPDATE
) {
1907 $oldUpdate = $linkCache->forUpdate( true );
1908 $this->mArticleID
= $linkCache->addLinkObj( $this );
1909 $linkCache->forUpdate( $oldUpdate );
1911 if ( -1 == $this->mArticleID
) {
1912 $this->mArticleID
= $linkCache->addLinkObj( $this );
1915 return $this->mArticleID
;
1919 * Is this an article that is a redirect page?
1920 * Uses link cache, adding it if necessary
1921 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1924 public function isRedirect( $flags = 0 ) {
1925 if( !is_null($this->mRedirect
) )
1926 return $this->mRedirect
;
1927 # Zero for special pages.
1928 # Also, calling getArticleID() loads the field from cache!
1929 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1932 $linkCache = LinkCache
::singleton();
1933 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1935 return $this->mRedirect
;
1939 * What is the length of this page?
1940 * Uses link cache, adding it if necessary
1941 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1944 public function getLength( $flags = 0 ) {
1945 if( $this->mLength
!= -1 )
1946 return $this->mLength
;
1947 # Zero for special pages.
1948 # Also, calling getArticleID() loads the field from cache!
1949 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1952 $linkCache = LinkCache
::singleton();
1953 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1955 return $this->mLength
;
1959 * What is the page_latest field for this page?
1960 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1963 public function getLatestRevID( $flags = 0 ) {
1964 if ($this->mLatestID
!== false)
1965 return $this->mLatestID
;
1967 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1968 return $this->mLatestID
= $db->selectField( 'revision',
1970 array('rev_page' => $this->getArticleID($flags)),
1971 'Title::getLatestRevID' );
1975 * This clears some fields in this object, and clears any associated
1976 * keys in the "bad links" section of the link cache.
1978 * - This is called from Article::insertNewArticle() to allow
1979 * loading of the new page_id. It's also called from
1980 * Article::doDeleteArticle()
1982 * @param int $newid the new Article ID
1984 public function resetArticleID( $newid ) {
1985 $linkCache = LinkCache
::singleton();
1986 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1988 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1989 else { $this->mArticleID
= $newid; }
1990 $this->mRestrictionsLoaded
= false;
1991 $this->mRestrictions
= array();
1995 * Updates page_touched for this page; called from LinksUpdate.php
1996 * @return bool true if the update succeded
1998 public function invalidateCache() {
1999 global $wgUseFileCache;
2001 if ( wfReadOnly() ) {
2005 $dbw = wfGetDB( DB_MASTER
);
2006 $success = $dbw->update( 'page',
2008 'page_touched' => $dbw->timestamp()
2009 ), array( /* WHERE */
2010 'page_namespace' => $this->getNamespace() ,
2011 'page_title' => $this->getDBkey()
2012 ), 'Title::invalidateCache'
2015 if ($wgUseFileCache) {
2016 $cache = new HTMLFileCache($this);
2017 @unlink
($cache->fileCacheName());
2024 * Prefix some arbitrary text with the namespace or interwiki prefix
2027 * @param string $name the text
2028 * @return string the prefixed text
2031 /* private */ function prefix( $name ) {
2033 if ( '' != $this->mInterwiki
) {
2034 $p = $this->mInterwiki
. ':';
2036 if ( 0 != $this->mNamespace
) {
2037 $p .= $this->getNsText() . ':';
2043 * Secure and split - main initialisation function for this object
2045 * Assumes that mDbkeyform has been set, and is urldecoded
2046 * and uses underscores, but not otherwise munged. This function
2047 * removes illegal characters, splits off the interwiki and
2048 * namespace prefixes, sets the other forms, and canonicalizes
2050 * @return bool true on success
2052 private function secureAndSplit() {
2053 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2056 static $rxTc = false;
2058 # Matching titles will be held as illegal.
2060 # Any character not allowed is forbidden...
2061 '[^' . Title
::legalChars() . ']' .
2062 # URL percent encoding sequences interfere with the ability
2063 # to round-trip titles -- you can't link to them consistently.
2064 '|%[0-9A-Fa-f]{2}' .
2065 # XML/HTML character references produce similar issues.
2066 '|&[A-Za-z0-9\x80-\xff]+;' .
2068 '|&#x[0-9A-Fa-f]+;' .
2072 $this->mInterwiki
= $this->mFragment
= '';
2073 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2075 $dbkey = $this->mDbkeyform
;
2077 # Strip Unicode bidi override characters.
2078 # Sometimes they slip into cut-n-pasted page titles, where the
2079 # override chars get included in list displays.
2080 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2081 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2083 # Clean up whitespace
2085 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2086 $dbkey = trim( $dbkey, '_' );
2088 if ( '' == $dbkey ) {
2092 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2093 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2097 $this->mDbkeyform
= $dbkey;
2099 # Initial colon indicates main namespace rather than specified default
2100 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2101 if ( ':' == $dbkey{0} ) {
2102 $this->mNamespace
= NS_MAIN
;
2103 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2104 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2107 # Namespace or interwiki prefix
2111 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2113 if ( $ns = $wgContLang->getNsIndex( $p )) {
2114 # Ordinary namespace
2116 $this->mNamespace
= $ns;
2117 } elseif( $this->getInterwikiLink( $p ) ) {
2119 # Can't make a local interwiki link to an interwiki link.
2120 # That's just crazy!
2126 $this->mInterwiki
= $wgContLang->lc( $p );
2128 # Redundant interwiki prefix to the local wiki
2129 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2130 if( $dbkey == '' ) {
2131 # Can't have an empty self-link
2134 $this->mInterwiki
= '';
2136 # Do another namespace split...
2140 # If there's an initial colon after the interwiki, that also
2141 # resets the default namespace
2142 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2143 $this->mNamespace
= NS_MAIN
;
2144 $dbkey = substr( $dbkey, 1 );
2147 # If there's no recognized interwiki or namespace,
2148 # then let the colon expression be part of the title.
2153 # We already know that some pages won't be in the database!
2155 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2156 $this->mArticleID
= 0;
2158 $fragment = strstr( $dbkey, '#' );
2159 if ( false !== $fragment ) {
2160 $this->setFragment( $fragment );
2161 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2162 # remove whitespace again: prevents "Foo_bar_#"
2163 # becoming "Foo_bar_"
2164 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2167 # Reject illegal characters.
2169 if( preg_match( $rxTc, $dbkey ) ) {
2174 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2175 * reachable due to the way web browsers deal with 'relative' URLs.
2176 * Also, they conflict with subpage syntax. Forbid them explicitly.
2178 if ( strpos( $dbkey, '.' ) !== false &&
2179 ( $dbkey === '.' ||
$dbkey === '..' ||
2180 strpos( $dbkey, './' ) === 0 ||
2181 strpos( $dbkey, '../' ) === 0 ||
2182 strpos( $dbkey, '/./' ) !== false ||
2183 strpos( $dbkey, '/../' ) !== false ||
2184 substr( $dbkey, -2 ) == '/.' ||
2185 substr( $dbkey, -3 ) == '/..' ) )
2191 * Magic tilde sequences? Nu-uh!
2193 if( strpos( $dbkey, '~~~' ) !== false ) {
2198 * Limit the size of titles to 255 bytes.
2199 * This is typically the size of the underlying database field.
2200 * We make an exception for special pages, which don't need to be stored
2201 * in the database, and may edge over 255 bytes due to subpage syntax
2202 * for long titles, e.g. [[Special:Block/Long name]]
2204 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2205 strlen( $dbkey ) > 512 )
2211 * Normally, all wiki links are forced to have
2212 * an initial capital letter so [[foo]] and [[Foo]]
2213 * point to the same place.
2215 * Don't force it for interwikis, since the other
2216 * site might be case-sensitive.
2218 $this->mUserCaseDBKey
= $dbkey;
2219 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2220 $dbkey = $wgContLang->ucfirst( $dbkey );
2224 * Can't make a link to a namespace alone...
2225 * "empty" local links can only be self-links
2226 * with a fragment identifier.
2229 $this->mInterwiki
== '' &&
2230 $this->mNamespace
!= NS_MAIN
) {
2233 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2234 // IP names are not allowed for accounts, and can only be referring to
2235 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2236 // there are numerous ways to present the same IP. Having sp:contribs scan
2237 // them all is silly and having some show the edits and others not is
2238 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2239 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2240 IP
::sanitizeIP( $dbkey ) : $dbkey;
2241 // Any remaining initial :s are illegal.
2242 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2247 $this->mDbkeyform
= $dbkey;
2248 $this->mUrlform
= wfUrlencode( $dbkey );
2250 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2256 * Set the fragment for this title
2257 * This is kind of bad, since except for this rarely-used function, Title objects
2258 * are immutable. The reason this is here is because it's better than setting the
2259 * members directly, which is what Linker::formatComment was doing previously.
2261 * @param string $fragment text
2262 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2264 public function setFragment( $fragment ) {
2265 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2269 * Get a Title object associated with the talk page of this article
2270 * @return Title the object for the talk page
2272 public function getTalkPage() {
2273 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2277 * Get a title object associated with the subject page of this
2280 * @return Title the object for the subject page
2282 public function getSubjectPage() {
2283 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2287 * Get an array of Title objects linking to this Title
2288 * Also stores the IDs in the link cache.
2290 * WARNING: do not use this function on arbitrary user-supplied titles!
2291 * On heavily-used templates it will max out the memory.
2293 * @param string $options may be FOR UPDATE
2294 * @return array the Title objects linking here
2296 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2297 $linkCache = LinkCache
::singleton();
2300 $db = wfGetDB( DB_MASTER
);
2302 $db = wfGetDB( DB_SLAVE
);
2305 $res = $db->select( array( 'page', $table ),
2306 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2308 "{$prefix}_from=page_id",
2309 "{$prefix}_namespace" => $this->getNamespace(),
2310 "{$prefix}_title" => $this->getDBkey() ),
2315 if ( $db->numRows( $res ) ) {
2316 foreach( $res as $row ) {
2317 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2318 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2319 $retVal[] = $titleObj;
2323 $db->freeResult( $res );
2328 * Get an array of Title objects using this Title as a template
2329 * Also stores the IDs in the link cache.
2331 * WARNING: do not use this function on arbitrary user-supplied titles!
2332 * On heavily-used templates it will max out the memory.
2334 * @param string $options may be FOR UPDATE
2335 * @return array the Title objects linking here
2337 public function getTemplateLinksTo( $options = '' ) {
2338 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2342 * Get an array of Title objects referring to non-existent articles linked from this page
2344 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2345 * @param string $options may be FOR UPDATE
2346 * @return array the Title objects
2348 public function getBrokenLinksFrom( $options = '' ) {
2349 if ( $this->getArticleId() == 0 ) {
2350 # All links from article ID 0 are false positives
2355 $db = wfGetDB( DB_MASTER
);
2357 $db = wfGetDB( DB_SLAVE
);
2360 $res = $db->safeQuery(
2361 "SELECT pl_namespace, pl_title
2364 ON pl_namespace=page_namespace
2365 AND pl_title=page_title
2367 AND page_namespace IS NULL
2369 $db->tableName( 'pagelinks' ),
2370 $db->tableName( 'page' ),
2371 $this->getArticleId(),
2375 if ( $db->numRows( $res ) ) {
2376 foreach( $res as $row ) {
2377 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2380 $db->freeResult( $res );
2386 * Get a list of URLs to purge from the Squid cache when this
2389 * @return array the URLs
2391 public function getSquidURLs() {
2395 $this->getInternalURL(),
2396 $this->getInternalURL( 'action=history' )
2399 // purge variant urls as well
2400 if($wgContLang->hasVariants()){
2401 $variants = $wgContLang->getVariants();
2402 foreach($variants as $vCode){
2403 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2404 $urls[] = $this->getInternalURL('',$vCode);
2411 public function purgeSquid() {
2413 if ( $wgUseSquid ) {
2414 $urls = $this->getSquidURLs();
2415 $u = new SquidUpdate( $urls );
2421 * Move this page without authentication
2422 * @param Title &$nt the new page Title
2424 public function moveNoAuth( &$nt ) {
2425 return $this->moveTo( $nt, false );
2429 * Check whether a given move operation would be valid.
2430 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2431 * @param Title &$nt the new title
2432 * @param bool $auth indicates whether $wgUser's permissions
2434 * @param string $reason is the log summary of the move, used for spam checking
2435 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2437 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2440 // Normally we'd add this to $errors, but we'll get
2441 // lots of syntax errors if $nt is not an object
2442 return array(array('badtitletext'));
2444 if( $this->equals( $nt ) ) {
2445 $errors[] = array('selfmove');
2447 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2448 $errors[] = array('immobile_namespace');
2451 $oldid = $this->getArticleID();
2452 $newid = $nt->getArticleID();
2454 if ( strlen( $nt->getDBkey() ) < 1 ) {
2455 $errors[] = array('articleexists');
2457 if ( ( '' == $this->getDBkey() ) ||
2459 ( '' == $nt->getDBkey() ) ) {
2460 $errors[] = array('badarticleerror');
2463 // Image-specific checks
2464 if( $this->getNamespace() == NS_IMAGE
) {
2465 $file = wfLocalFile( $this );
2466 if( $file->exists() ) {
2467 if( $nt->getNamespace() != NS_IMAGE
) {
2468 $errors[] = array('imagenocrossnamespace');
2470 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2471 $errors[] = array('imageinvalidfilename');
2473 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2474 $errors[] = array('imagetypemismatch');
2481 $errors = array_merge($errors,
2482 $this->getUserPermissionsErrors('move', $wgUser),
2483 $this->getUserPermissionsErrors('edit', $wgUser),
2484 $nt->getUserPermissionsErrors('move', $wgUser),
2485 $nt->getUserPermissionsErrors('edit', $wgUser));
2490 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2491 $errors[] = array('hookaborted', $err);
2494 # The move is allowed only if (1) the target doesn't exist, or
2495 # (2) the target is a redirect to the source, and has no history
2496 # (so we can undo bad moves right after they're done).
2498 if ( 0 != $newid ) { # Target exists; check for validity
2499 if ( ! $this->isValidMoveTarget( $nt ) ) {
2500 $errors[] = array('articleexists');
2503 $tp = $nt->getTitleProtection();
2504 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2505 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2506 $errors[] = array('cantmove-titleprotected');
2515 * Move a title to a new location
2516 * @param Title &$nt the new title
2517 * @param bool $auth indicates whether $wgUser's permissions
2519 * @param string $reason The reason for the move
2520 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2521 * Ignored if the user doesn't have the suppressredirect right.
2522 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2524 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2525 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2526 if( is_array( $err ) ) {
2530 $pageid = $this->getArticleID();
2531 if( $nt->exists() ) {
2532 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2533 $pageCountChange = ($createRedirect ?
0 : -1);
2534 } else { # Target didn't exist, do normal move.
2535 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2536 $pageCountChange = ($createRedirect ?
1 : 0);
2539 if( is_array( $err ) ) {
2542 $redirid = $this->getArticleID();
2544 // Category memberships include a sort key which may be customized.
2545 // If it's left as the default (the page title), we need to update
2546 // the sort key to match the new title.
2548 // Be careful to avoid resetting cl_timestamp, which may disturb
2549 // time-based lists on some sites.
2551 // Warning -- if the sort key is *explicitly* set to the old title,
2552 // we can't actually distinguish it from a default here, and it'll
2553 // be set to the new title even though it really shouldn't.
2554 // It'll get corrected on the next edit, but resetting cl_timestamp.
2555 $dbw = wfGetDB( DB_MASTER
);
2556 $dbw->update( 'categorylinks',
2558 'cl_sortkey' => $nt->getPrefixedText(),
2559 'cl_timestamp=cl_timestamp' ),
2561 'cl_from' => $pageid,
2562 'cl_sortkey' => $this->getPrefixedText() ),
2567 $oldnamespace = $this->getNamespace() & ~
1;
2568 $newnamespace = $nt->getNamespace() & ~
1;
2569 $oldtitle = $this->getDBkey();
2570 $newtitle = $nt->getDBkey();
2572 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2573 WatchedItem
::duplicateEntries( $this, $nt );
2576 # Update search engine
2577 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2579 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2583 if( $this->isContentPage() && !$nt->isContentPage() ) {
2584 # No longer a content page
2585 # Not viewed, edited, removing
2586 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2587 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2588 # Now a content page
2589 # Not viewed, edited, adding
2590 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2591 } elseif( $pageCountChange ) {
2593 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2600 # Update message cache for interface messages
2601 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2602 global $wgMessageCache;
2603 $oldarticle = new Article( $this );
2604 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2605 $newarticle = new Article( $nt );
2606 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2610 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2615 * Move page to a title which is at present a redirect to the
2618 * @param Title &$nt the page to move to, which should currently
2620 * @param string $reason The reason for the move
2621 * @param bool $createRedirect Whether to leave a redirect at the old title.
2622 * Ignored if the user doesn't have the suppressredirect right
2624 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2625 global $wgUseSquid, $wgUser;
2626 $fname = 'Title::moveOverExistingRedirect';
2627 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2630 $comment .= ": $reason";
2633 $now = wfTimestampNow();
2634 $newid = $nt->getArticleID();
2635 $oldid = $this->getArticleID();
2636 $latest = $this->getLatestRevID();
2638 $dbw = wfGetDB( DB_MASTER
);
2641 # Delete the old redirect. We don't save it to history since
2642 # by definition if we've got here it's rather uninteresting.
2643 # We have to remove it so that the next step doesn't trigger
2644 # a conflict on the unique namespace+title index...
2645 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2646 if ( !$dbw->cascadingDeletes() ) {
2647 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2648 global $wgUseTrackbacks;
2649 if ($wgUseTrackbacks)
2650 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2651 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2652 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2653 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2654 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2655 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2656 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2657 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2660 # Save a null revision in the page's history notifying of the move
2661 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2662 $nullRevId = $nullRevision->insertOn( $dbw );
2664 $article = new Article( $this );
2665 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2667 # Change the name of the target page:
2668 $dbw->update( 'page',
2670 'page_touched' => $dbw->timestamp($now),
2671 'page_namespace' => $nt->getNamespace(),
2672 'page_title' => $nt->getDBkey(),
2673 'page_latest' => $nullRevId,
2675 /* WHERE */ array( 'page_id' => $oldid ),
2678 $nt->resetArticleID( $oldid );
2680 # Recreate the redirect, this time in the other direction.
2681 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2682 $mwRedir = MagicWord
::get( 'redirect' );
2683 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2684 $redirectArticle = new Article( $this );
2685 $newid = $redirectArticle->insertOn( $dbw );
2686 $redirectRevision = new Revision( array(
2688 'comment' => $comment,
2689 'text' => $redirectText ) );
2690 $redirectRevision->insertOn( $dbw );
2691 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2693 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2695 # Now, we record the link from the redirect to the new title.
2696 # It should have no other outgoing links...
2697 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2698 $dbw->insert( 'pagelinks',
2700 'pl_from' => $newid,
2701 'pl_namespace' => $nt->getNamespace(),
2702 'pl_title' => $nt->getDBkey() ),
2705 $this->resetArticleID( 0 );
2708 # Move an image if this is a file
2709 if( $this->getNamespace() == NS_IMAGE
) {
2710 $file = wfLocalFile( $this );
2711 if( $file->exists() ) {
2712 $status = $file->move( $nt );
2713 if( !$status->isOk() ) {
2715 return $status->getErrorsArray();
2722 $log = new LogPage( 'move' );
2723 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2726 if ( $wgUseSquid ) {
2727 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2728 $u = new SquidUpdate( $urls );
2735 * Move page to non-existing title.
2736 * @param Title &$nt the new Title
2737 * @param string $reason The reason for the move
2738 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2739 * Ignored if the user doesn't have the suppressredirect right
2741 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2742 global $wgUseSquid, $wgUser;
2743 $fname = 'MovePageForm::moveToNewTitle';
2744 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2746 $comment .= ": $reason";
2749 $newid = $nt->getArticleID();
2750 $oldid = $this->getArticleID();
2751 $latest = $this->getLatestRevId();
2753 $dbw = wfGetDB( DB_MASTER
);
2755 $now = $dbw->timestamp();
2757 # Save a null revision in the page's history notifying of the move
2758 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2759 $nullRevId = $nullRevision->insertOn( $dbw );
2761 $article = new Article( $this );
2762 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2765 $dbw->update( 'page',
2767 'page_touched' => $now,
2768 'page_namespace' => $nt->getNamespace(),
2769 'page_title' => $nt->getDBkey(),
2770 'page_latest' => $nullRevId,
2772 /* WHERE */ array( 'page_id' => $oldid ),
2775 $nt->resetArticleID( $oldid );
2777 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2779 $mwRedir = MagicWord
::get( 'redirect' );
2780 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2781 $redirectArticle = new Article( $this );
2782 $newid = $redirectArticle->insertOn( $dbw );
2783 $redirectRevision = new Revision( array(
2785 'comment' => $comment,
2786 'text' => $redirectText ) );
2787 $redirectRevision->insertOn( $dbw );
2788 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2790 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2792 # Record the just-created redirect's linking to the page
2793 $dbw->insert( 'pagelinks',
2795 'pl_from' => $newid,
2796 'pl_namespace' => $nt->getNamespace(),
2797 'pl_title' => $nt->getDBkey() ),
2800 $this->resetArticleID( 0 );
2803 # Move an image if this is a file
2804 if( $this->getNamespace() == NS_IMAGE
) {
2805 $file = wfLocalFile( $this );
2806 if( $file->exists() ) {
2807 $status = $file->move( $nt );
2808 if( !$status->isOk() ) {
2810 return $status->getErrorsArray();
2817 $log = new LogPage( 'move' );
2818 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2820 # Purge caches as per article creation
2821 Article
::onArticleCreate( $nt );
2823 # Purge old title from squid
2824 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2825 $this->purgeSquid();
2830 * Checks if $this can be moved to a given Title
2831 * - Selects for update, so don't call it unless you mean business
2833 * @param Title &$nt the new title to check
2835 public function isValidMoveTarget( $nt ) {
2837 $fname = 'Title::isValidMoveTarget';
2838 $dbw = wfGetDB( DB_MASTER
);
2840 # Is it an existsing file?
2841 if( $nt->getNamespace() == NS_IMAGE
) {
2842 $file = wfLocalFile( $nt );
2843 if( $file->exists() ) {
2844 wfDebug( __METHOD__
. ": file exists\n" );
2850 $id = $nt->getArticleID();
2851 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2852 array( 'page_is_redirect','old_text','old_flags' ),
2853 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2854 $fname, 'FOR UPDATE' );
2856 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2858 wfDebug( __METHOD__
. ": not a redirect\n" );
2861 $text = Revision
::getRevisionText( $obj );
2863 # Does the redirect point to the source?
2864 # Or is it a broken self-redirect, usually caused by namespace collisions?
2866 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2867 $redirTitle = Title
::newFromText( $m[1] );
2868 if( !is_object( $redirTitle ) ||
2869 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2870 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2871 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2876 wfDebug( __METHOD__
. ": failsafe\n" );
2880 # Does the article have a history?
2881 $row = $dbw->selectRow( array( 'page', 'revision'),
2883 array( 'page_namespace' => $nt->getNamespace(),
2884 'page_title' => $nt->getDBkey(),
2885 'page_id=rev_page AND page_latest != rev_id'
2886 ), $fname, 'FOR UPDATE'
2889 # Return true if there was no history
2890 return $row === false;
2894 * Can this title be added to a user's watchlist?
2898 public function isWatchable() {
2899 return !$this->isExternal()
2900 && MWNamespace
::isWatchable( $this->getNamespace() );
2904 * Get categories to which this Title belongs and return an array of
2905 * categories' names.
2907 * @return array an array of parents in the form:
2908 * $parent => $currentarticle
2910 public function getParentCategories() {
2913 $titlekey = $this->getArticleId();
2914 $dbr = wfGetDB( DB_SLAVE
);
2915 $categorylinks = $dbr->tableName( 'categorylinks' );
2918 $sql = "SELECT * FROM $categorylinks"
2919 ." WHERE cl_from='$titlekey'"
2920 ." AND cl_from <> '0'"
2921 ." ORDER BY cl_sortkey";
2923 $res = $dbr->query( $sql );
2925 if( $dbr->numRows( $res ) > 0 ) {
2926 foreach( $res as $row )
2927 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2928 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2929 $dbr->freeResult( $res );
2937 * Get a tree of parent categories
2938 * @param array $children an array with the children in the keys, to check for circular refs
2941 public function getParentCategoryTree( $children = array() ) {
2943 $parents = $this->getParentCategories();
2946 foreach( $parents as $parent => $current ) {
2947 if ( array_key_exists( $parent, $children ) ) {
2948 # Circular reference
2949 $stack[$parent] = array();
2951 $nt = Title
::newFromText($parent);
2953 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2965 * Get an associative array for selecting this title from
2970 public function pageCond() {
2971 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2975 * Get the revision ID of the previous revision
2977 * @param integer $revId Revision ID. Get the revision that was before this one.
2978 * @param integer $flags, GAID_FOR_UPDATE
2979 * @return integer $oldrevision|false
2981 public function getPreviousRevisionID( $revId, $flags=0 ) {
2982 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2983 return $db->selectField( 'revision', 'rev_id',
2985 'rev_page' => $this->getArticleId($flags),
2986 'rev_id < ' . intval( $revId )
2989 array( 'ORDER BY' => 'rev_id DESC' )
2994 * Get the revision ID of the next revision
2996 * @param integer $revId Revision ID. Get the revision that was after this one.
2997 * @param integer $flags, GAID_FOR_UPDATE
2998 * @return integer $oldrevision|false
3000 public function getNextRevisionID( $revId, $flags=0 ) {
3001 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3002 return $db->selectField( 'revision', 'rev_id',
3004 'rev_page' => $this->getArticleId($flags),
3005 'rev_id > ' . intval( $revId )
3008 array( 'ORDER BY' => 'rev_id' )
3013 * Get the number of revisions between the given revision IDs.
3014 * Used for diffs and other things that really need it.
3016 * @param integer $old Revision ID.
3017 * @param integer $new Revision ID.
3018 * @return integer Number of revisions between these IDs.
3020 public function countRevisionsBetween( $old, $new ) {
3021 $dbr = wfGetDB( DB_SLAVE
);
3022 return $dbr->selectField( 'revision', 'count(*)',
3023 'rev_page = ' . intval( $this->getArticleId() ) .
3024 ' AND rev_id > ' . intval( $old ) .
3025 ' AND rev_id < ' . intval( $new ),
3027 array( 'USE INDEX' => 'PRIMARY' ) );
3031 * Compare with another title.
3033 * @param Title $title
3036 public function equals( Title
$title ) {
3037 // Note: === is necessary for proper matching of number-like titles.
3038 return $this->getInterwiki() === $title->getInterwiki()
3039 && $this->getNamespace() == $title->getNamespace()
3040 && $this->getDBkey() === $title->getDBkey();
3044 * Callback for usort() to do title sorts by (namespace, title)
3046 static function compare( $a, $b ) {
3047 if( $a->getNamespace() == $b->getNamespace() ) {
3048 return strcmp( $a->getText(), $b->getText() );
3050 return $a->getNamespace() - $b->getNamespace();
3055 * Return a string representation of this title
3059 public function __toString() {
3060 return $this->getPrefixedText();
3064 * Check if page exists
3067 public function exists() {
3068 return $this->getArticleId() != 0;
3072 * Do we know that this title definitely exists, or should we otherwise
3073 * consider that it exists?
3077 public function isAlwaysKnown() {
3078 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3079 // the full l10n of that language to be loaded. That takes much memory and
3080 // isn't needed. So we strip the language part away.
3081 // Also, extension messages which are not loaded, are shown as red, because
3082 // we don't call MessageCache::loadAllMessages.
3083 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3084 return $this->isExternal()
3085 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3086 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3090 * Update page_touched timestamps and send squid purge messages for
3091 * pages linking to this title. May be sent to the job queue depending
3092 * on the number of links. Typically called on create and delete.
3094 public function touchLinks() {
3095 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3098 if ( $this->getNamespace() == NS_CATEGORY
) {
3099 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3105 * Get the last touched timestamp
3107 public function getTouched() {
3108 $dbr = wfGetDB( DB_SLAVE
);
3109 $touched = $dbr->selectField( 'page', 'page_touched',
3111 'page_namespace' => $this->getNamespace(),
3112 'page_title' => $this->getDBkey()
3118 public function trackbackURL() {
3119 global $wgTitle, $wgScriptPath, $wgServer;
3121 return "$wgServer$wgScriptPath/trackback.php?article="
3122 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3125 public function trackbackRDF() {
3126 $url = htmlspecialchars($this->getFullURL());
3127 $title = htmlspecialchars($this->getText());
3128 $tburl = $this->trackbackURL();
3130 // Autodiscovery RDF is placed in comments so HTML validator
3131 // won't barf. This is a rather icky workaround, but seems
3132 // frequently used by this kind of RDF thingy.
3134 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3136 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3137 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3138 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3141 dc:identifier=\"$url\"
3143 trackback:ping=\"$tburl\" />
3149 * Generate strings used for xml 'id' names in monobook tabs
3152 public function getNamespaceKey() {
3154 switch ($this->getNamespace()) {
3157 return 'nstab-main';
3160 return 'nstab-user';
3162 return 'nstab-media';
3164 return 'nstab-special';
3166 case NS_PROJECT_TALK
:
3167 return 'nstab-project';
3170 return 'nstab-image';
3172 case NS_MEDIAWIKI_TALK
:
3173 return 'nstab-mediawiki';
3175 case NS_TEMPLATE_TALK
:
3176 return 'nstab-template';
3179 return 'nstab-help';
3181 case NS_CATEGORY_TALK
:
3182 return 'nstab-category';
3184 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3189 * Returns true if this title resolves to the named special page
3190 * @param string $name The special page name
3192 public function isSpecial( $name ) {
3193 if ( $this->getNamespace() == NS_SPECIAL
) {
3194 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3195 if ( $name == $thisName ) {
3203 * If the Title refers to a special page alias which is not the local default,
3204 * returns a new Title which points to the local default. Otherwise, returns $this.
3206 public function fixSpecialName() {
3207 if ( $this->getNamespace() == NS_SPECIAL
) {
3208 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3209 if ( $canonicalName ) {
3210 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3211 if ( $localName != $this->mDbkeyform
) {
3212 return Title
::makeTitle( NS_SPECIAL
, $localName );
3220 * Is this Title in a namespace which contains content?
3221 * In other words, is this a content page, for the purposes of calculating
3226 public function isContentPage() {
3227 return MWNamespace
::isContent( $this->getNamespace() );
3230 public function getRedirectsHere( $ns = null ) {
3233 $dbr = wfGetDB( DB_SLAVE
);
3235 'rd_namespace' => $this->getNamespace(),
3236 'rd_title' => $this->getDBkey(),
3239 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3241 $res = $dbr->select(
3242 array( 'redirect', 'page' ),
3243 array( 'page_namespace', 'page_title' ),
3249 foreach( $res as $row ) {
3250 $redirs[] = self
::newFromRow( $row );