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
304 if( preg_match( '!^\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
305 // Strip preceding colon used to "escape" categories, etc.
306 // and URL-decode links
307 if( strpos( $m[1], '%' ) !== false ) {
308 // Match behavior of inline link parsing here;
309 // don't interpret + as " " most of the time!
310 // It might be safe to just use rawurldecode instead, though.
311 $m[1] = urldecode( ltrim( $m[1], ':' ) );
313 $title = Title
::newFromText( $m[1] );
314 // Redirects to Special:Userlogout are not permitted
315 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
322 #----------------------------------------------------------------------------
324 #----------------------------------------------------------------------------
327 * Get the prefixed DB key associated with an ID
328 * @param int $id the page_id of the article
329 * @return Title an object representing the article, or NULL
330 * if no such article was found
332 public static function nameOf( $id ) {
333 $dbr = wfGetDB( DB_SLAVE
);
335 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
336 if ( $s === false ) { return NULL; }
338 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
343 * Get a regex character class describing the legal characters in a link
344 * @return string the list of characters, not delimited
346 public static function legalChars() {
347 global $wgLegalTitleChars;
348 return $wgLegalTitleChars;
352 * Get a string representation of a title suitable for
353 * including in a search index
355 * @param int $ns a namespace index
356 * @param string $title text-form main part
357 * @return string a stripped-down title string ready for the
360 public static function indexTitle( $ns, $title ) {
363 $lc = SearchEngine
::legalSearchChars() . '&#;';
364 $t = $wgContLang->stripForSearch( $title );
365 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
366 $t = $wgContLang->lc( $t );
369 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
370 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
372 $t = preg_replace( "/\\s+/", ' ', $t );
374 if ( $ns == NS_IMAGE
) {
375 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
381 * Make a prefixed DB key from a DB key and a namespace index
382 * @param int $ns numerical representation of the namespace
383 * @param string $title the DB key form the title
384 * @param string $fragment The link fragment (after the "#")
385 * @return string the prefixed form of the title
387 public static function makeName( $ns, $title, $fragment = '' ) {
390 $namespace = $wgContLang->getNsText( $ns );
391 $name = $namespace == '' ?
$title : "$namespace:$title";
392 if ( strval( $fragment ) != '' ) {
393 $name .= '#' . $fragment;
399 * Returns the URL associated with an interwiki prefix
400 * @param string $key the interwiki prefix (e.g. "MeatBall")
401 * @return the associated URL, containing "$1", which should be
402 * replaced by an article title
405 public function getInterwikiLink( $key ) {
406 global $wgMemc, $wgInterwikiExpiry;
407 global $wgInterwikiCache, $wgContLang;
408 $fname = 'Title::getInterwikiLink';
410 $key = $wgContLang->lc( $key );
412 $k = wfMemcKey( 'interwiki', $key );
413 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
414 return Title
::$interwikiCache[$k]->iw_url
;
417 if ($wgInterwikiCache) {
418 return Title
::getInterwikiCached( $key );
421 $s = $wgMemc->get( $k );
422 # Ignore old keys with no iw_local
423 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
424 Title
::$interwikiCache[$k] = $s;
428 $dbr = wfGetDB( DB_SLAVE
);
429 $res = $dbr->select( 'interwiki',
430 array( 'iw_url', 'iw_local', 'iw_trans' ),
431 array( 'iw_prefix' => $key ), $fname );
436 $s = $dbr->fetchObject( $res );
438 # Cache non-existence: create a blank object and save it to memcached
444 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
445 Title
::$interwikiCache[$k] = $s;
451 * Fetch interwiki prefix data from local cache in constant database
453 * More logic is explained in DefaultSettings
455 * @return string URL of interwiki site
457 public static function getInterwikiCached( $key ) {
458 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
462 $db=dba_open($wgInterwikiCache,'r','cdb');
463 /* Resolve site name */
464 if ($wgInterwikiScopes>=3 and !$site) {
465 $site = dba_fetch('__sites:' . wfWikiID(), $db);
467 $site = $wgInterwikiFallbackSite;
469 $value = dba_fetch( wfMemcKey( $key ), $db);
470 if ($value=='' and $wgInterwikiScopes>=3) {
472 $value = dba_fetch("_{$site}:{$key}", $db);
474 if ($value=='' and $wgInterwikiScopes>=2) {
476 $value = dba_fetch("__global:{$key}", $db);
485 list($local,$url)=explode(' ',$value,2);
487 $s->iw_local
=(int)$local;
489 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
493 * Determine whether the object refers to a page within
496 * @return bool TRUE if this is an in-project interwiki link
497 * or a wikilink, FALSE otherwise
499 public function isLocal() {
500 if ( $this->mInterwiki
!= '' ) {
501 # Make sure key is loaded into cache
502 $this->getInterwikiLink( $this->mInterwiki
);
503 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
504 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
511 * Determine whether the object refers to a page within
512 * this project and is transcludable.
514 * @return bool TRUE if this is transcludable
516 public function isTrans() {
517 if ($this->mInterwiki
== '')
519 # Make sure key is loaded into cache
520 $this->getInterwikiLink( $this->mInterwiki
);
521 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
522 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
526 * Escape a text fragment, say from a link, for a URL
528 static function escapeFragmentForURL( $fragment ) {
529 $fragment = str_replace( ' ', '_', $fragment );
530 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
531 $replaceArray = array(
535 return strtr( $fragment, $replaceArray );
538 #----------------------------------------------------------------------------
540 #----------------------------------------------------------------------------
542 /** Simple accessors */
544 * Get the text form (spaces not underscores) of the main part
547 public function getText() { return $this->mTextform
; }
549 * Get the URL-encoded form of the main part
552 public function getPartialURL() { return $this->mUrlform
; }
554 * Get the main part with underscores
557 public function getDBkey() { return $this->mDbkeyform
; }
559 * Get the namespace index, i.e. one of the NS_xxxx constants
562 public function getNamespace() { return $this->mNamespace
; }
564 * Get the namespace text
567 public function getNsText() {
568 global $wgContLang, $wgCanonicalNamespaceNames;
570 if ( '' != $this->mInterwiki
) {
571 // This probably shouldn't even happen. ohh man, oh yuck.
572 // But for interwiki transclusion it sometimes does.
573 // Shit. Shit shit shit.
575 // Use the canonical namespaces if possible to try to
576 // resolve a foreign namespace.
577 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
578 return $wgCanonicalNamespaceNames[$this->mNamespace
];
581 return $wgContLang->getNsText( $this->mNamespace
);
584 * Get the DB key with the initial letter case as specified by the user
586 function getUserCaseDBKey() {
587 return $this->mUserCaseDBKey
;
590 * Get the namespace text of the subject (rather than talk) page
593 public function getSubjectNsText() {
595 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
599 * Get the namespace text of the talk page
602 public function getTalkNsText() {
604 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
608 * Could this title have a corresponding talk page?
611 public function canTalk() {
612 return( MWNamespace
::canTalk( $this->mNamespace
) );
616 * Get the interwiki prefix (or null string)
619 public function getInterwiki() { return $this->mInterwiki
; }
621 * Get the Title fragment (i.e. the bit after the #) in text form
624 public function getFragment() { return $this->mFragment
; }
626 * Get the fragment in URL form, including the "#" character if there is one
629 public function getFragmentForURL() {
630 if ( $this->mFragment
== '' ) {
633 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
637 * Get the default namespace index, for when there is no namespace
640 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
643 * Get title for search index
644 * @return string a stripped-down title string ready for the
647 public function getIndexTitle() {
648 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
652 * Get the prefixed database key form
653 * @return string the prefixed title, with underscores and
654 * any interwiki and namespace prefixes
656 public function getPrefixedDBkey() {
657 $s = $this->prefix( $this->mDbkeyform
);
658 $s = str_replace( ' ', '_', $s );
663 * Get the prefixed title with spaces.
664 * This is the form usually used for display
665 * @return string the prefixed title, with spaces
667 public function getPrefixedText() {
668 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
669 $s = $this->prefix( $this->mTextform
);
670 $s = str_replace( '_', ' ', $s );
671 $this->mPrefixedText
= $s;
673 return $this->mPrefixedText
;
677 * Get the prefixed title with spaces, plus any fragment
678 * (part beginning with '#')
679 * @return string the prefixed title, with spaces and
680 * the fragment, including '#'
682 public function getFullText() {
683 $text = $this->getPrefixedText();
684 if( '' != $this->mFragment
) {
685 $text .= '#' . $this->mFragment
;
691 * Get the base name, i.e. the leftmost parts before the /
692 * @return string Base name
694 public function getBaseText() {
695 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
696 return $this->getText();
699 $parts = explode( '/', $this->getText() );
700 # Don't discard the real title if there's no subpage involved
701 if( count( $parts ) > 1 )
702 unset( $parts[ count( $parts ) - 1 ] );
703 return implode( '/', $parts );
707 * Get the lowest-level subpage name, i.e. the rightmost part after /
708 * @return string Subpage name
710 public function getSubpageText() {
711 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
712 return( $this->mTextform
);
714 $parts = explode( '/', $this->mTextform
);
715 return( $parts[ count( $parts ) - 1 ] );
719 * Get a URL-encoded form of the subpage text
720 * @return string URL-encoded subpage name
722 public function getSubpageUrlForm() {
723 $text = $this->getSubpageText();
724 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
725 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
730 * Get a URL-encoded title (not an actual URL) including interwiki
731 * @return string the URL-encoded form
733 public function getPrefixedURL() {
734 $s = $this->prefix( $this->mDbkeyform
);
735 $s = str_replace( ' ', '_', $s );
737 $s = wfUrlencode ( $s ) ;
739 # Cleaning up URL to make it look nice -- is this safe?
740 $s = str_replace( '%28', '(', $s );
741 $s = str_replace( '%29', ')', $s );
747 * Get a real URL referring to this title, with interwiki link and
750 * @param array $query an optional query string, not used for interwiki
751 * links. Can be specified as an associative array as well, e.g.,
752 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
753 * @param string $variant language variant of url (for sr, zh..)
754 * @return string the URL
756 public function getFullURL( $query = '', $variant = false ) {
757 global $wgContLang, $wgServer, $wgRequest;
759 if( is_array( $query ) ) {
760 $query = wfArrayToCGI( $query );
763 if ( '' == $this->mInterwiki
) {
764 $url = $this->getLocalUrl( $query, $variant );
766 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
767 // Correct fix would be to move the prepending elsewhere.
768 if ($wgRequest->getVal('action') != 'render') {
769 $url = $wgServer . $url;
772 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
774 $namespace = wfUrlencode( $this->getNsText() );
775 if ( '' != $namespace ) {
776 # Can this actually happen? Interwikis shouldn't be parsed.
777 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
780 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
781 $url = wfAppendQuery( $url, $query );
784 # Finally, add the fragment.
785 $url .= $this->getFragmentForURL();
787 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
792 * Get a URL with no fragment or server name. If this page is generated
793 * with action=render, $wgServer is prepended.
794 * @param mixed $query an optional query string; if not specified,
795 * $wgArticlePath will be used. Can be specified as an associative array
796 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
798 * @param string $variant language variant of url (for sr, zh..)
799 * @return string the URL
801 public function getLocalURL( $query = '', $variant = false ) {
802 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
803 global $wgVariantArticlePath, $wgContLang, $wgUser;
805 if( is_array( $query ) ) {
806 $query = wfArrayToCGI( $query );
809 // internal links should point to same variant as current page (only anonymous users)
810 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
811 $pref = $wgContLang->getPreferredVariant(false);
812 if($pref != $wgContLang->getCode())
816 if ( $this->isExternal() ) {
817 $url = $this->getFullURL();
819 // This is currently only used for edit section links in the
820 // context of interwiki transclusion. In theory we should
821 // append the query to the end of any existing query string,
822 // but interwiki transclusion is already broken in that case.
826 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
827 if ( $query == '' ) {
828 if( $variant != false && $wgContLang->hasVariants() ) {
829 if( $wgVariantArticlePath == false ) {
830 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
832 $variantArticlePath = $wgVariantArticlePath;
834 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
835 $url = str_replace( '$1', $dbkey, $url );
837 $url = str_replace( '$1', $dbkey, $wgArticlePath );
840 global $wgActionPaths;
843 if( !empty( $wgActionPaths ) &&
844 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
846 $action = urldecode( $matches[2] );
847 if( isset( $wgActionPaths[$action] ) ) {
848 $query = $matches[1];
849 if( isset( $matches[4] ) ) $query .= $matches[4];
850 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
851 if( $query != '' ) $url .= '?' . $query;
854 if ( $url === false ) {
855 if ( $query == '-' ) {
858 $url = "{$wgScript}?title={$dbkey}&{$query}";
862 // FIXME: this causes breakage in various places when we
863 // actually expected a local URL and end up with dupe prefixes.
864 if ($wgRequest->getVal('action') == 'render') {
865 $url = $wgServer . $url;
868 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
873 * Get a URL that's the simplest URL that will be valid to link, locally,
874 * to the current Title. It includes the fragment, but does not include
875 * the server unless action=render is used (or the link is external). If
876 * there's a fragment but the prefixed text is empty, we just return a link
879 * @param array $query An associative array of key => value pairs for the
880 * query string. Keys and values will be escaped.
881 * @param string $variant Language variant of URL (for sr, zh..). Ignored
882 * for external links. Default is "false" (same variant as current page,
883 * for anonymous users).
884 * @return string the URL
886 public function getLinkUrl( $query = array(), $variant = false ) {
887 if( !is_array( $query ) ) {
888 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
891 if( $this->isExternal() ) {
892 return $this->getFullURL( $query );
893 } elseif( $this->getPrefixedText() === ''
894 and $this->getFragment() !== '' ) {
895 return $this->getFragmentForURL();
897 return $this->getLocalURL( $query, $variant )
898 . $this->getFragmentForURL();
903 * Get an HTML-escaped version of the URL form, suitable for
904 * using in a link, without a server name or fragment
905 * @param string $query an optional query string
906 * @return string the URL
908 public function escapeLocalURL( $query = '' ) {
909 return htmlspecialchars( $this->getLocalURL( $query ) );
913 * Get an HTML-escaped version of the URL form, suitable for
914 * using in a link, including the server name and fragment
916 * @return string the URL
917 * @param string $query an optional query string
919 public function escapeFullURL( $query = '' ) {
920 return htmlspecialchars( $this->getFullURL( $query ) );
924 * Get the URL form for an internal link.
925 * - Used in various Squid-related code, in case we have a different
926 * internal hostname for the server from the exposed one.
928 * @param string $query an optional query string
929 * @param string $variant language variant of url (for sr, zh..)
930 * @return string the URL
932 public function getInternalURL( $query = '', $variant = false ) {
933 global $wgInternalServer;
934 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
935 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
940 * Get the edit URL for this Title
941 * @return string the URL, or a null string if this is an
944 public function getEditURL() {
945 if ( '' != $this->mInterwiki
) { return ''; }
946 $s = $this->getLocalURL( 'action=edit' );
952 * Get the HTML-escaped displayable text form.
953 * Used for the title field in <a> tags.
954 * @return string the text, including any prefixes
956 public function getEscapedText() {
957 return htmlspecialchars( $this->getPrefixedText() );
961 * Is this Title interwiki?
964 public function isExternal() { return ( '' != $this->mInterwiki
); }
967 * Is this page "semi-protected" - the *only* protection is autoconfirm?
969 * @param string Action to check (default: edit)
972 public function isSemiProtected( $action = 'edit' ) {
973 if( $this->exists() ) {
974 $restrictions = $this->getRestrictions( $action );
975 if( count( $restrictions ) > 0 ) {
976 foreach( $restrictions as $restriction ) {
977 if( strtolower( $restriction ) != 'autoconfirmed' )
986 # If it doesn't exist, it can't be protected
992 * Does the title correspond to a protected article?
993 * @param string $what the action the page is protected from,
994 * by default checks move and edit
997 public function isProtected( $action = '' ) {
998 global $wgRestrictionLevels, $wgRestrictionTypes;
1000 # Special pages have inherent protection
1001 if( $this->getNamespace() == NS_SPECIAL
)
1004 # Check regular protection levels
1005 foreach( $wgRestrictionTypes as $type ){
1006 if( $action == $type ||
$action == '' ) {
1007 $r = $this->getRestrictions( $type );
1008 foreach( $wgRestrictionLevels as $level ) {
1009 if( in_array( $level, $r ) && $level != '' ) {
1020 * Is $wgUser watching this page?
1023 public function userIsWatching() {
1026 if ( is_null( $this->mWatched
) ) {
1027 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1028 $this->mWatched
= false;
1030 $this->mWatched
= $wgUser->isWatched( $this );
1033 return $this->mWatched
;
1037 * Can $wgUser perform $action on this page?
1038 * This skips potentially expensive cascading permission checks.
1040 * Suitable for use for nonessential UI controls in common cases, but
1041 * _not_ for functional access control.
1043 * May provide false positives, but should never provide a false negative.
1045 * @param string $action action that permission needs to be checked for
1048 public function quickUserCan( $action ) {
1049 return $this->userCan( $action, false );
1053 * Determines if $wgUser is unable to edit this page because it has been protected
1054 * by $wgNamespaceProtection.
1058 public function isNamespaceProtected() {
1059 global $wgNamespaceProtection, $wgUser;
1060 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1061 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1062 if( $right != '' && !$wgUser->isAllowed( $right ) )
1070 * Can $wgUser perform $action on this page?
1071 * @param string $action action that permission needs to be checked for
1072 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1075 public function userCan( $action, $doExpensiveQueries = true ) {
1077 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1081 * Can $user perform $action on this page?
1083 * FIXME: This *does not* check throttles (User::pingLimiter()).
1085 * @param string $action action that permission needs to be checked for
1086 * @param User $user user to check
1087 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1088 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1089 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1091 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1092 if( !StubObject
::isRealObject( $user ) ) {
1093 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1095 $wgUser->_unstub( '', 5 );
1098 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1102 global $wgEmailConfirmToEdit;
1104 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1105 $errors[] = array( 'confirmedittext' );
1108 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1109 $block = $user->mBlock
;
1111 // This is from OutputPage::blockedPage
1112 // Copied at r23888 by werdna
1114 $id = $user->blockedBy();
1115 $reason = $user->blockedFor();
1116 if( $reason == '' ) {
1117 $reason = wfMsg( 'blockednoreason' );
1121 if ( is_numeric( $id ) ) {
1122 $name = User
::whoIs( $id );
1127 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1128 $blockid = $block->mId
;
1129 $blockExpiry = $user->mBlock
->mExpiry
;
1130 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1132 if ( $blockExpiry == 'infinity' ) {
1133 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1134 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1136 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1137 if ( strpos( $option, ':' ) == false )
1140 list ($show, $value) = explode( ":", $option );
1142 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1143 $blockExpiry = $show;
1148 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1151 $intended = $user->mBlock
->mAddress
;
1153 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1154 $blockid, $blockExpiry, $intended, $blockTimestamp );
1157 // Remove the errors being ignored.
1159 foreach( $errors as $index => $error ) {
1160 $error_key = is_array($error) ?
$error[0] : $error;
1162 if (in_array( $error_key, $ignoreErrors )) {
1163 unset($errors[$index]);
1171 * Can $user perform $action on this page? This is an internal function,
1172 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1173 * checks on wfReadOnly() and blocks)
1175 * @param string $action action that permission needs to be checked for
1176 * @param User $user user to check
1177 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1178 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1180 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1181 wfProfileIn( __METHOD__
);
1185 // Use getUserPermissionsErrors instead
1186 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1187 wfProfileOut( __METHOD__
);
1188 return $result ?
array() : array( array( 'badaccess-group0' ) );
1191 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1192 if ($result != array() && is_array($result) && !is_array($result[0]))
1193 $errors[] = $result; # A single array representing an error
1194 else if (is_array($result) && is_array($result[0]))
1195 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1196 else if ($result != '' && $result != null && $result !== true && $result !== false)
1197 $errors[] = array($result); # A string representing a message-id
1198 else if ($result === false )
1199 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1201 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1202 if ($result != array() && is_array($result) && !is_array($result[0]))
1203 $errors[] = $result; # A single array representing an error
1204 else if (is_array($result) && is_array($result[0]))
1205 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1206 else if ($result != '' && $result != null && $result !== true && $result !== false)
1207 $errors[] = array($result); # A string representing a message-id
1208 else if ($result === false )
1209 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1212 $specialOKActions = array( 'createaccount', 'execute' );
1213 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1214 $errors[] = array('ns-specialprotected');
1217 if ( $this->isNamespaceProtected() ) {
1218 $ns = $this->getNamespace() == NS_MAIN
1219 ?
wfMsg( 'nstab-main' )
1220 : $this->getNsText();
1221 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1222 ?
array('protectedinterface')
1223 : array( 'namespaceprotected', $ns ) );
1226 if( $this->mDbkeyform
== '_' ) {
1227 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1228 $errors[] = array('badaccess-group0');
1231 # protect css/js subpages of user pages
1232 # XXX: this might be better using restrictions
1233 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1234 if( $this->isCssJsSubpage()
1235 && !$user->isAllowed('editusercssjs')
1236 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1237 $errors[] = array('customcssjsprotected');
1240 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1241 # We /could/ use the protection level on the source page, but it's fairly ugly
1242 # as we have to establish a precedence hierarchy for pages included by multiple
1243 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1244 # as they could remove the protection anyway.
1245 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1246 # Cascading protection depends on more than this page...
1247 # Several cascading protected pages may include this page...
1248 # Check each cascading level
1249 # This is only for protection restrictions, not for all actions
1250 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1251 foreach( $restrictions[$action] as $right ) {
1252 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1253 if( '' != $right && !$user->isAllowed( $right ) ) {
1255 foreach( $cascadingSources as $page )
1256 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1257 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1263 foreach( $this->getRestrictions($action) as $right ) {
1264 // Backwards compatibility, rewrite sysop -> protect
1265 if ( $right == 'sysop' ) {
1268 if( '' != $right && !$user->isAllowed( $right ) ) {
1269 //Users with 'editprotected' permission can edit protected pages
1270 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1271 //Users with 'editprotected' permission cannot edit protected pages
1272 //with cascading option turned on.
1273 if($this->mCascadeRestriction
) {
1274 $errors[] = array( 'protectedpagetext', $right );
1276 //Nothing, user can edit!
1279 $errors[] = array( 'protectedpagetext', $right );
1284 if ($action == 'protect') {
1285 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1286 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1290 if ($action == 'create') {
1291 $title_protection = $this->getTitleProtection();
1293 if (is_array($title_protection)) {
1294 extract($title_protection);
1296 if ($pt_create_perm == 'sysop')
1297 $pt_create_perm = 'protect';
1299 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1300 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1304 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1305 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1306 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1308 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1309 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1310 } elseif ( !$user->isAllowed( $action ) ) {
1312 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1313 User
::getGroupsWithPermission( $action ) );
1315 $return = array( 'badaccess-groups',
1317 implode( ', ', $groups ),
1318 count( $groups ) ) );
1321 $return = array( "badaccess-group0" );
1323 $errors[] = $return;
1326 wfProfileOut( __METHOD__
);
1331 * Is this title subject to title protection?
1332 * @return mixed An associative array representing any existent title
1333 * protection, or false if there's none.
1335 private function getTitleProtection() {
1336 // Can't protect pages in special namespaces
1337 if ( $this->getNamespace() < 0 ) {
1341 $dbr = wfGetDB( DB_SLAVE
);
1342 $res = $dbr->select( 'protected_titles', '*',
1343 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1345 if ($row = $dbr->fetchRow( $res )) {
1352 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1353 global $wgUser,$wgContLang;
1355 if ($create_perm == implode(',',$this->getRestrictions('create'))
1356 && $expiry == $this->mRestrictionsExpiry
) {
1361 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1363 $dbw = wfGetDB( DB_MASTER
);
1365 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1367 $expiry_description = '';
1368 if ( $encodedExpiry != 'infinity' ) {
1369 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1372 # Update protection table
1373 if ($create_perm != '' ) {
1374 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1375 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1376 , 'pt_create_perm' => $create_perm
1377 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1378 , 'pt_expiry' => $encodedExpiry
1379 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1381 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1382 'pt_title' => $title ), __METHOD__
);
1384 # Update the protection log
1385 $log = new LogPage( 'protect' );
1387 if( $create_perm ) {
1388 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1390 $log->addEntry( 'unprotect', $this, $reason );
1397 * Remove any title protection (due to page existing
1399 public function deleteTitleProtection() {
1400 $dbw = wfGetDB( DB_MASTER
);
1402 $dbw->delete( 'protected_titles',
1403 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1407 * Can $wgUser edit this page?
1409 * @deprecated use userCan('edit')
1411 public function userCanEdit( $doExpensiveQueries = true ) {
1412 return $this->userCan( 'edit', $doExpensiveQueries );
1416 * Can $wgUser create this page?
1418 * @deprecated use userCan('create')
1420 public function userCanCreate( $doExpensiveQueries = true ) {
1421 return $this->userCan( 'create', $doExpensiveQueries );
1425 * Can $wgUser move this page?
1427 * @deprecated use userCan('move')
1429 public function userCanMove( $doExpensiveQueries = true ) {
1430 return $this->userCan( 'move', $doExpensiveQueries );
1434 * Would anybody with sufficient privileges be able to move this page?
1435 * Some pages just aren't movable.
1439 public function isMovable() {
1440 return MWNamespace
::isMovable( $this->getNamespace() )
1441 && $this->getInterwiki() == '';
1445 * Can $wgUser read this page?
1447 * @todo fold these checks into userCan()
1449 public function userCanRead() {
1450 global $wgUser, $wgGroupPermissions;
1453 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1454 if ( $result !== null ) {
1458 # Shortcut for public wikis, allows skipping quite a bit of code
1459 if ($wgGroupPermissions['*']['read'])
1462 if( $wgUser->isAllowed( 'read' ) ) {
1465 global $wgWhitelistRead;
1468 * Always grant access to the login page.
1469 * Even anons need to be able to log in.
1471 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1476 * Bail out if there isn't whitelist
1478 if( !is_array($wgWhitelistRead) ) {
1483 * Check for explicit whitelisting
1485 $name = $this->getPrefixedText();
1486 $dbName = $this->getPrefixedDBKey();
1487 // Check with and without underscores
1488 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1492 * Old settings might have the title prefixed with
1493 * a colon for main-namespace pages
1495 if( $this->getNamespace() == NS_MAIN
) {
1496 if( in_array( ':' . $name, $wgWhitelistRead ) )
1501 * If it's a special page, ditch the subpage bit
1504 if( $this->getNamespace() == NS_SPECIAL
) {
1505 $name = $this->getDBkey();
1506 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1507 if ( $name === false ) {
1508 # Invalid special page, but we show standard login required message
1512 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1513 if( in_array( $pure, $wgWhitelistRead, true ) )
1522 * Is this a talk page of some sort?
1525 public function isTalkPage() {
1526 return MWNamespace
::isTalk( $this->getNamespace() );
1530 * Is this a subpage?
1533 public function isSubpage() {
1534 return MWNamespace
::hasSubpages( $this->mNamespace
)
1535 ?
strpos( $this->getText(), '/' ) !== false
1540 * Does this have subpages? (Warning, usually requires an extra DB query.)
1543 public function hasSubpages() {
1544 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1549 # We dynamically add a member variable for the purpose of this method
1550 # alone to cache the result. There's no point in having it hanging
1551 # around uninitialized in every Title object; therefore we only add it
1552 # if needed and don't declare it statically.
1553 if( isset( $this->mHasSubpages
) ) {
1554 return $this->mHasSubpages
;
1557 $db = wfGetDB( DB_SLAVE
);
1558 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1559 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1560 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1566 * Could this page contain custom CSS or JavaScript, based
1571 public function isCssOrJsPage() {
1572 return $this->mNamespace
== NS_MEDIAWIKI
1573 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1577 * Is this a .css or .js subpage of a user page?
1580 public function isCssJsSubpage() {
1581 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1584 * Is this a *valid* .css or .js subpage of a user page?
1585 * Check that the corresponding skin exists
1587 public function isValidCssJsSubpage() {
1588 if ( $this->isCssJsSubpage() ) {
1589 $skinNames = Skin
::getSkinNames();
1590 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1596 * Trim down a .css or .js subpage title to get the corresponding skin name
1598 public function getSkinFromCssJsSubpage() {
1599 $subpage = explode( '/', $this->mTextform
);
1600 $subpage = $subpage[ count( $subpage ) - 1 ];
1601 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1604 * Is this a .css subpage of a user page?
1607 public function isCssSubpage() {
1608 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1611 * Is this a .js subpage of a user page?
1614 public function isJsSubpage() {
1615 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1618 * Protect css/js subpages of user pages: can $wgUser edit
1622 * @todo XXX: this might be better using restrictions
1624 public function userCanEditCssJsSubpage() {
1626 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1630 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1632 * @return bool If the page is subject to cascading restrictions.
1634 public function isCascadeProtected() {
1635 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1636 return ( $sources > 0 );
1640 * Cascading protection: Get the source of any cascading restrictions on this page.
1642 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1643 * @return array( mixed title array, restriction array)
1644 * 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.
1645 * The restriction array is an array of each type, each of which contains an array of unique groups
1647 public function getCascadeProtectionSources( $get_pages = true ) {
1648 global $wgRestrictionTypes;
1650 # Define our dimension of restrictions types
1651 $pagerestrictions = array();
1652 foreach( $wgRestrictionTypes as $action )
1653 $pagerestrictions[$action] = array();
1655 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1656 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1657 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1658 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1661 wfProfileIn( __METHOD__
);
1663 $dbr = wfGetDb( DB_SLAVE
);
1665 if ( $this->getNamespace() == NS_IMAGE
) {
1666 $tables = array ('imagelinks', 'page_restrictions');
1667 $where_clauses = array(
1668 'il_to' => $this->getDBkey(),
1670 'pr_cascade' => 1 );
1672 $tables = array ('templatelinks', 'page_restrictions');
1673 $where_clauses = array(
1674 'tl_namespace' => $this->getNamespace(),
1675 'tl_title' => $this->getDBkey(),
1677 'pr_cascade' => 1 );
1681 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1682 $where_clauses[] = 'page_id=pr_page';
1685 $cols = array( 'pr_expiry' );
1688 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1690 $sources = $get_pages ?
array() : false;
1691 $now = wfTimestampNow();
1692 $purgeExpired = false;
1694 foreach( $res as $row ) {
1695 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1696 if( $expiry > $now ) {
1698 $page_id = $row->pr_page
;
1699 $page_ns = $row->page_namespace
;
1700 $page_title = $row->page_title
;
1701 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1702 # Add groups needed for each restriction type if its not already there
1703 # Make sure this restriction type still exists
1704 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1705 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1711 // Trigger lazy purge of expired restrictions from the db
1712 $purgeExpired = true;
1715 if( $purgeExpired ) {
1716 Title
::purgeExpiredRestrictions();
1719 wfProfileOut( __METHOD__
);
1722 $this->mCascadeSources
= $sources;
1723 $this->mCascadingRestrictions
= $pagerestrictions;
1725 $this->mHasCascadingRestrictions
= $sources;
1728 return array( $sources, $pagerestrictions );
1731 function areRestrictionsCascading() {
1732 if (!$this->mRestrictionsLoaded
) {
1733 $this->loadRestrictions();
1736 return $this->mCascadeRestriction
;
1740 * Loads a string into mRestrictions array
1741 * @param resource $res restrictions as an SQL result.
1743 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1744 global $wgRestrictionTypes;
1745 $dbr = wfGetDB( DB_SLAVE
);
1747 foreach( $wgRestrictionTypes as $type ){
1748 $this->mRestrictions
[$type] = array();
1751 $this->mCascadeRestriction
= false;
1752 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1754 # Backwards-compatibility: also load the restrictions from the page record (old format).
1756 if ( $oldFashionedRestrictions === NULL ) {
1757 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1758 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1761 if ($oldFashionedRestrictions != '') {
1763 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1764 $temp = explode( '=', trim( $restrict ) );
1765 if(count($temp) == 1) {
1766 // old old format should be treated as edit/move restriction
1767 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1768 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1770 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1774 $this->mOldRestrictions
= true;
1778 if( $dbr->numRows( $res ) ) {
1779 # Current system - load second to make them override.
1780 $now = wfTimestampNow();
1781 $purgeExpired = false;
1783 foreach( $res as $row ) {
1784 # Cycle through all the restrictions.
1786 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1787 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1790 // This code should be refactored, now that it's being used more generally,
1791 // But I don't really see any harm in leaving it in Block for now -werdna
1792 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1794 // Only apply the restrictions if they haven't expired!
1795 if ( !$expiry ||
$expiry > $now ) {
1796 $this->mRestrictionsExpiry
= $expiry;
1797 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1799 $this->mCascadeRestriction |
= $row->pr_cascade
;
1801 // Trigger a lazy purge of expired restrictions
1802 $purgeExpired = true;
1806 if( $purgeExpired ) {
1807 Title
::purgeExpiredRestrictions();
1811 $this->mRestrictionsLoaded
= true;
1814 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1815 if( !$this->mRestrictionsLoaded
) {
1816 if ($this->exists()) {
1817 $dbr = wfGetDB( DB_SLAVE
);
1819 $res = $dbr->select( 'page_restrictions', '*',
1820 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1822 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1824 $title_protection = $this->getTitleProtection();
1826 if (is_array($title_protection)) {
1827 extract($title_protection);
1829 $now = wfTimestampNow();
1830 $expiry = Block
::decodeExpiry($pt_expiry);
1832 if (!$expiry ||
$expiry > $now) {
1833 // Apply the restrictions
1834 $this->mRestrictionsExpiry
= $expiry;
1835 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1836 } else { // Get rid of the old restrictions
1837 Title
::purgeExpiredRestrictions();
1840 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1842 $this->mRestrictionsLoaded
= true;
1848 * Purge expired restrictions from the page_restrictions table
1850 static function purgeExpiredRestrictions() {
1851 $dbw = wfGetDB( DB_MASTER
);
1852 $dbw->delete( 'page_restrictions',
1853 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1856 $dbw->delete( 'protected_titles',
1857 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1862 * Accessor/initialisation for mRestrictions
1864 * @param string $action action that permission needs to be checked for
1865 * @return array the array of groups allowed to edit this article
1867 public function getRestrictions( $action ) {
1868 if( !$this->mRestrictionsLoaded
) {
1869 $this->loadRestrictions();
1871 return isset( $this->mRestrictions
[$action] )
1872 ?
$this->mRestrictions
[$action]
1877 * Is there a version of this page in the deletion archive?
1878 * @return int the number of archived revisions
1880 public function isDeleted() {
1881 $fname = 'Title::isDeleted';
1882 if ( $this->getNamespace() < 0 ) {
1885 $dbr = wfGetDB( DB_SLAVE
);
1886 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1887 'ar_title' => $this->getDBkey() ), $fname );
1888 if( $this->getNamespace() == NS_IMAGE
) {
1889 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1890 array( 'fa_name' => $this->getDBkey() ), $fname );
1897 * Get the article ID for this Title from the link cache,
1898 * adding it if necessary
1899 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1901 * @return int the ID
1903 public function getArticleID( $flags = 0 ) {
1904 $linkCache = LinkCache
::singleton();
1905 if ( $flags & GAID_FOR_UPDATE
) {
1906 $oldUpdate = $linkCache->forUpdate( true );
1907 $this->mArticleID
= $linkCache->addLinkObj( $this );
1908 $linkCache->forUpdate( $oldUpdate );
1910 if ( -1 == $this->mArticleID
) {
1911 $this->mArticleID
= $linkCache->addLinkObj( $this );
1914 return $this->mArticleID
;
1918 * Is this an article that is a redirect page?
1919 * Uses link cache, adding it if necessary
1920 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1923 public function isRedirect( $flags = 0 ) {
1924 if( !is_null($this->mRedirect
) )
1925 return $this->mRedirect
;
1926 # Zero for special pages.
1927 # Also, calling getArticleID() loads the field from cache!
1928 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1931 $linkCache = LinkCache
::singleton();
1932 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1934 return $this->mRedirect
;
1938 * What is the length of this page?
1939 * Uses link cache, adding it if necessary
1940 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1943 public function getLength( $flags = 0 ) {
1944 if( $this->mLength
!= -1 )
1945 return $this->mLength
;
1946 # Zero for special pages.
1947 # Also, calling getArticleID() loads the field from cache!
1948 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1951 $linkCache = LinkCache
::singleton();
1952 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1954 return $this->mLength
;
1958 * What is the page_latest field for this page?
1959 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1962 public function getLatestRevID( $flags = 0 ) {
1963 if ($this->mLatestID
!== false)
1964 return $this->mLatestID
;
1966 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1967 return $this->mLatestID
= $db->selectField( 'revision',
1969 array('rev_page' => $this->getArticleID($flags)),
1970 'Title::getLatestRevID' );
1974 * This clears some fields in this object, and clears any associated
1975 * keys in the "bad links" section of the link cache.
1977 * - This is called from Article::insertNewArticle() to allow
1978 * loading of the new page_id. It's also called from
1979 * Article::doDeleteArticle()
1981 * @param int $newid the new Article ID
1983 public function resetArticleID( $newid ) {
1984 $linkCache = LinkCache
::singleton();
1985 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1987 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1988 else { $this->mArticleID
= $newid; }
1989 $this->mRestrictionsLoaded
= false;
1990 $this->mRestrictions
= array();
1994 * Updates page_touched for this page; called from LinksUpdate.php
1995 * @return bool true if the update succeded
1997 public function invalidateCache() {
1998 global $wgUseFileCache;
2000 if ( wfReadOnly() ) {
2004 $dbw = wfGetDB( DB_MASTER
);
2005 $success = $dbw->update( 'page',
2007 'page_touched' => $dbw->timestamp()
2008 ), array( /* WHERE */
2009 'page_namespace' => $this->getNamespace() ,
2010 'page_title' => $this->getDBkey()
2011 ), 'Title::invalidateCache'
2014 if ($wgUseFileCache) {
2015 $cache = new HTMLFileCache($this);
2016 @unlink
($cache->fileCacheName());
2023 * Prefix some arbitrary text with the namespace or interwiki prefix
2026 * @param string $name the text
2027 * @return string the prefixed text
2030 /* private */ function prefix( $name ) {
2032 if ( '' != $this->mInterwiki
) {
2033 $p = $this->mInterwiki
. ':';
2035 if ( 0 != $this->mNamespace
) {
2036 $p .= $this->getNsText() . ':';
2042 * Secure and split - main initialisation function for this object
2044 * Assumes that mDbkeyform has been set, and is urldecoded
2045 * and uses underscores, but not otherwise munged. This function
2046 * removes illegal characters, splits off the interwiki and
2047 * namespace prefixes, sets the other forms, and canonicalizes
2049 * @return bool true on success
2051 private function secureAndSplit() {
2052 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2055 static $rxTc = false;
2057 # Matching titles will be held as illegal.
2059 # Any character not allowed is forbidden...
2060 '[^' . Title
::legalChars() . ']' .
2061 # URL percent encoding sequences interfere with the ability
2062 # to round-trip titles -- you can't link to them consistently.
2063 '|%[0-9A-Fa-f]{2}' .
2064 # XML/HTML character references produce similar issues.
2065 '|&[A-Za-z0-9\x80-\xff]+;' .
2067 '|&#x[0-9A-Fa-f]+;' .
2071 $this->mInterwiki
= $this->mFragment
= '';
2072 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2074 $dbkey = $this->mDbkeyform
;
2076 # Strip Unicode bidi override characters.
2077 # Sometimes they slip into cut-n-pasted page titles, where the
2078 # override chars get included in list displays.
2079 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2080 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2082 # Clean up whitespace
2084 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2085 $dbkey = trim( $dbkey, '_' );
2087 if ( '' == $dbkey ) {
2091 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2092 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2096 $this->mDbkeyform
= $dbkey;
2098 # Initial colon indicates main namespace rather than specified default
2099 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2100 if ( ':' == $dbkey{0} ) {
2101 $this->mNamespace
= NS_MAIN
;
2102 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2103 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2106 # Namespace or interwiki prefix
2110 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2112 if ( $ns = $wgContLang->getNsIndex( $p )) {
2113 # Ordinary namespace
2115 $this->mNamespace
= $ns;
2116 } elseif( $this->getInterwikiLink( $p ) ) {
2118 # Can't make a local interwiki link to an interwiki link.
2119 # That's just crazy!
2125 $this->mInterwiki
= $wgContLang->lc( $p );
2127 # Redundant interwiki prefix to the local wiki
2128 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2129 if( $dbkey == '' ) {
2130 # Can't have an empty self-link
2133 $this->mInterwiki
= '';
2135 # Do another namespace split...
2139 # If there's an initial colon after the interwiki, that also
2140 # resets the default namespace
2141 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2142 $this->mNamespace
= NS_MAIN
;
2143 $dbkey = substr( $dbkey, 1 );
2146 # If there's no recognized interwiki or namespace,
2147 # then let the colon expression be part of the title.
2152 # We already know that some pages won't be in the database!
2154 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2155 $this->mArticleID
= 0;
2157 $fragment = strstr( $dbkey, '#' );
2158 if ( false !== $fragment ) {
2159 $this->setFragment( $fragment );
2160 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2161 # remove whitespace again: prevents "Foo_bar_#"
2162 # becoming "Foo_bar_"
2163 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2166 # Reject illegal characters.
2168 if( preg_match( $rxTc, $dbkey ) ) {
2173 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2174 * reachable due to the way web browsers deal with 'relative' URLs.
2175 * Also, they conflict with subpage syntax. Forbid them explicitly.
2177 if ( strpos( $dbkey, '.' ) !== false &&
2178 ( $dbkey === '.' ||
$dbkey === '..' ||
2179 strpos( $dbkey, './' ) === 0 ||
2180 strpos( $dbkey, '../' ) === 0 ||
2181 strpos( $dbkey, '/./' ) !== false ||
2182 strpos( $dbkey, '/../' ) !== false ||
2183 substr( $dbkey, -2 ) == '/.' ||
2184 substr( $dbkey, -3 ) == '/..' ) )
2190 * Magic tilde sequences? Nu-uh!
2192 if( strpos( $dbkey, '~~~' ) !== false ) {
2197 * Limit the size of titles to 255 bytes.
2198 * This is typically the size of the underlying database field.
2199 * We make an exception for special pages, which don't need to be stored
2200 * in the database, and may edge over 255 bytes due to subpage syntax
2201 * for long titles, e.g. [[Special:Block/Long name]]
2203 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2204 strlen( $dbkey ) > 512 )
2210 * Normally, all wiki links are forced to have
2211 * an initial capital letter so [[foo]] and [[Foo]]
2212 * point to the same place.
2214 * Don't force it for interwikis, since the other
2215 * site might be case-sensitive.
2217 $this->mUserCaseDBKey
= $dbkey;
2218 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2219 $dbkey = $wgContLang->ucfirst( $dbkey );
2223 * Can't make a link to a namespace alone...
2224 * "empty" local links can only be self-links
2225 * with a fragment identifier.
2228 $this->mInterwiki
== '' &&
2229 $this->mNamespace
!= NS_MAIN
) {
2232 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2233 // IP names are not allowed for accounts, and can only be referring to
2234 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2235 // there are numerous ways to present the same IP. Having sp:contribs scan
2236 // them all is silly and having some show the edits and others not is
2237 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2238 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2239 IP
::sanitizeIP( $dbkey ) : $dbkey;
2240 // Any remaining initial :s are illegal.
2241 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2246 $this->mDbkeyform
= $dbkey;
2247 $this->mUrlform
= wfUrlencode( $dbkey );
2249 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2255 * Set the fragment for this title
2256 * This is kind of bad, since except for this rarely-used function, Title objects
2257 * are immutable. The reason this is here is because it's better than setting the
2258 * members directly, which is what Linker::formatComment was doing previously.
2260 * @param string $fragment text
2261 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2263 public function setFragment( $fragment ) {
2264 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2268 * Get a Title object associated with the talk page of this article
2269 * @return Title the object for the talk page
2271 public function getTalkPage() {
2272 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2276 * Get a title object associated with the subject page of this
2279 * @return Title the object for the subject page
2281 public function getSubjectPage() {
2282 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2286 * Get an array of Title objects linking to this Title
2287 * Also stores the IDs in the link cache.
2289 * WARNING: do not use this function on arbitrary user-supplied titles!
2290 * On heavily-used templates it will max out the memory.
2292 * @param string $options may be FOR UPDATE
2293 * @return array the Title objects linking here
2295 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2296 $linkCache = LinkCache
::singleton();
2299 $db = wfGetDB( DB_MASTER
);
2301 $db = wfGetDB( DB_SLAVE
);
2304 $res = $db->select( array( 'page', $table ),
2305 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2307 "{$prefix}_from=page_id",
2308 "{$prefix}_namespace" => $this->getNamespace(),
2309 "{$prefix}_title" => $this->getDBkey() ),
2314 if ( $db->numRows( $res ) ) {
2315 foreach( $res as $row ) {
2316 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2317 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2318 $retVal[] = $titleObj;
2322 $db->freeResult( $res );
2327 * Get an array of Title objects using this Title as a template
2328 * Also stores the IDs in the link cache.
2330 * WARNING: do not use this function on arbitrary user-supplied titles!
2331 * On heavily-used templates it will max out the memory.
2333 * @param string $options may be FOR UPDATE
2334 * @return array the Title objects linking here
2336 public function getTemplateLinksTo( $options = '' ) {
2337 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2341 * Get an array of Title objects referring to non-existent articles linked from this page
2343 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2344 * @param string $options may be FOR UPDATE
2345 * @return array the Title objects
2347 public function getBrokenLinksFrom( $options = '' ) {
2348 if ( $this->getArticleId() == 0 ) {
2349 # All links from article ID 0 are false positives
2354 $db = wfGetDB( DB_MASTER
);
2356 $db = wfGetDB( DB_SLAVE
);
2359 $res = $db->safeQuery(
2360 "SELECT pl_namespace, pl_title
2363 ON pl_namespace=page_namespace
2364 AND pl_title=page_title
2366 AND page_namespace IS NULL
2368 $db->tableName( 'pagelinks' ),
2369 $db->tableName( 'page' ),
2370 $this->getArticleId(),
2374 if ( $db->numRows( $res ) ) {
2375 foreach( $res as $row ) {
2376 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2379 $db->freeResult( $res );
2385 * Get a list of URLs to purge from the Squid cache when this
2388 * @return array the URLs
2390 public function getSquidURLs() {
2394 $this->getInternalURL(),
2395 $this->getInternalURL( 'action=history' )
2398 // purge variant urls as well
2399 if($wgContLang->hasVariants()){
2400 $variants = $wgContLang->getVariants();
2401 foreach($variants as $vCode){
2402 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2403 $urls[] = $this->getInternalURL('',$vCode);
2410 public function purgeSquid() {
2412 if ( $wgUseSquid ) {
2413 $urls = $this->getSquidURLs();
2414 $u = new SquidUpdate( $urls );
2420 * Move this page without authentication
2421 * @param Title &$nt the new page Title
2423 public function moveNoAuth( &$nt ) {
2424 return $this->moveTo( $nt, false );
2428 * Check whether a given move operation would be valid.
2429 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2430 * @param Title &$nt the new title
2431 * @param bool $auth indicates whether $wgUser's permissions
2433 * @param string $reason is the log summary of the move, used for spam checking
2434 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2436 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2439 // Normally we'd add this to $errors, but we'll get
2440 // lots of syntax errors if $nt is not an object
2441 return array(array('badtitletext'));
2443 if( $this->equals( $nt ) ) {
2444 $errors[] = array('selfmove');
2446 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2447 $errors[] = array('immobile_namespace');
2450 $oldid = $this->getArticleID();
2451 $newid = $nt->getArticleID();
2453 if ( strlen( $nt->getDBkey() ) < 1 ) {
2454 $errors[] = array('articleexists');
2456 if ( ( '' == $this->getDBkey() ) ||
2458 ( '' == $nt->getDBkey() ) ) {
2459 $errors[] = array('badarticleerror');
2462 // Image-specific checks
2463 if( $this->getNamespace() == NS_IMAGE
) {
2464 $file = wfLocalFile( $this );
2465 if( $file->exists() ) {
2466 if( $nt->getNamespace() != NS_IMAGE
) {
2467 $errors[] = array('imagenocrossnamespace');
2469 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2470 $errors[] = array('imageinvalidfilename');
2472 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2473 $errors[] = array('imagetypemismatch');
2480 $errors = array_merge($errors,
2481 $this->getUserPermissionsErrors('move', $wgUser),
2482 $this->getUserPermissionsErrors('edit', $wgUser),
2483 $nt->getUserPermissionsErrors('move', $wgUser),
2484 $nt->getUserPermissionsErrors('edit', $wgUser));
2489 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2490 $errors[] = array('hookaborted', $err);
2493 # The move is allowed only if (1) the target doesn't exist, or
2494 # (2) the target is a redirect to the source, and has no history
2495 # (so we can undo bad moves right after they're done).
2497 if ( 0 != $newid ) { # Target exists; check for validity
2498 if ( ! $this->isValidMoveTarget( $nt ) ) {
2499 $errors[] = array('articleexists');
2502 $tp = $nt->getTitleProtection();
2503 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2504 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2505 $errors[] = array('cantmove-titleprotected');
2514 * Move a title to a new location
2515 * @param Title &$nt the new title
2516 * @param bool $auth indicates whether $wgUser's permissions
2518 * @param string $reason The reason for the move
2519 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2520 * Ignored if the user doesn't have the suppressredirect right.
2521 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2523 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2524 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2525 if( is_array( $err ) ) {
2529 $pageid = $this->getArticleID();
2530 if( $nt->exists() ) {
2531 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2532 $pageCountChange = ($createRedirect ?
0 : -1);
2533 } else { # Target didn't exist, do normal move.
2534 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2535 $pageCountChange = ($createRedirect ?
1 : 0);
2538 if( is_array( $err ) ) {
2541 $redirid = $this->getArticleID();
2543 // Category memberships include a sort key which may be customized.
2544 // If it's left as the default (the page title), we need to update
2545 // the sort key to match the new title.
2547 // Be careful to avoid resetting cl_timestamp, which may disturb
2548 // time-based lists on some sites.
2550 // Warning -- if the sort key is *explicitly* set to the old title,
2551 // we can't actually distinguish it from a default here, and it'll
2552 // be set to the new title even though it really shouldn't.
2553 // It'll get corrected on the next edit, but resetting cl_timestamp.
2554 $dbw = wfGetDB( DB_MASTER
);
2555 $dbw->update( 'categorylinks',
2557 'cl_sortkey' => $nt->getPrefixedText(),
2558 'cl_timestamp=cl_timestamp' ),
2560 'cl_from' => $pageid,
2561 'cl_sortkey' => $this->getPrefixedText() ),
2566 $oldnamespace = $this->getNamespace() & ~
1;
2567 $newnamespace = $nt->getNamespace() & ~
1;
2568 $oldtitle = $this->getDBkey();
2569 $newtitle = $nt->getDBkey();
2571 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2572 WatchedItem
::duplicateEntries( $this, $nt );
2575 # Update search engine
2576 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2578 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2582 if( $this->isContentPage() && !$nt->isContentPage() ) {
2583 # No longer a content page
2584 # Not viewed, edited, removing
2585 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2586 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2587 # Now a content page
2588 # Not viewed, edited, adding
2589 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2590 } elseif( $pageCountChange ) {
2592 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2599 # Update message cache for interface messages
2600 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2601 global $wgMessageCache;
2602 $oldarticle = new Article( $this );
2603 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2604 $newarticle = new Article( $nt );
2605 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2609 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2614 * Move page to a title which is at present a redirect to the
2617 * @param Title &$nt the page to move to, which should currently
2619 * @param string $reason The reason for the move
2620 * @param bool $createRedirect Whether to leave a redirect at the old title.
2621 * Ignored if the user doesn't have the suppressredirect right
2623 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2624 global $wgUseSquid, $wgUser;
2625 $fname = 'Title::moveOverExistingRedirect';
2626 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2629 $comment .= ": $reason";
2632 $now = wfTimestampNow();
2633 $newid = $nt->getArticleID();
2634 $oldid = $this->getArticleID();
2635 $latest = $this->getLatestRevID();
2637 $dbw = wfGetDB( DB_MASTER
);
2640 # Delete the old redirect. We don't save it to history since
2641 # by definition if we've got here it's rather uninteresting.
2642 # We have to remove it so that the next step doesn't trigger
2643 # a conflict on the unique namespace+title index...
2644 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2645 if ( !$dbw->cascadingDeletes() ) {
2646 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2647 global $wgUseTrackbacks;
2648 if ($wgUseTrackbacks)
2649 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2650 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2651 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2652 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2653 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2654 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2655 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2656 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2659 # Save a null revision in the page's history notifying of the move
2660 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2661 $nullRevId = $nullRevision->insertOn( $dbw );
2663 $article = new Article( $this );
2664 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2666 # Change the name of the target page:
2667 $dbw->update( 'page',
2669 'page_touched' => $dbw->timestamp($now),
2670 'page_namespace' => $nt->getNamespace(),
2671 'page_title' => $nt->getDBkey(),
2672 'page_latest' => $nullRevId,
2674 /* WHERE */ array( 'page_id' => $oldid ),
2677 $nt->resetArticleID( $oldid );
2679 # Recreate the redirect, this time in the other direction.
2680 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2681 $mwRedir = MagicWord
::get( 'redirect' );
2682 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2683 $redirectArticle = new Article( $this );
2684 $newid = $redirectArticle->insertOn( $dbw );
2685 $redirectRevision = new Revision( array(
2687 'comment' => $comment,
2688 'text' => $redirectText ) );
2689 $redirectRevision->insertOn( $dbw );
2690 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2692 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2694 # Now, we record the link from the redirect to the new title.
2695 # It should have no other outgoing links...
2696 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2697 $dbw->insert( 'pagelinks',
2699 'pl_from' => $newid,
2700 'pl_namespace' => $nt->getNamespace(),
2701 'pl_title' => $nt->getDBkey() ),
2704 $this->resetArticleID( 0 );
2707 # Move an image if this is a file
2708 if( $this->getNamespace() == NS_IMAGE
) {
2709 $file = wfLocalFile( $this );
2710 if( $file->exists() ) {
2711 $status = $file->move( $nt );
2712 if( !$status->isOk() ) {
2714 return $status->getErrorsArray();
2721 $log = new LogPage( 'move' );
2722 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2725 if ( $wgUseSquid ) {
2726 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2727 $u = new SquidUpdate( $urls );
2734 * Move page to non-existing title.
2735 * @param Title &$nt the new Title
2736 * @param string $reason The reason for the move
2737 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2738 * Ignored if the user doesn't have the suppressredirect right
2740 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2741 global $wgUseSquid, $wgUser;
2742 $fname = 'MovePageForm::moveToNewTitle';
2743 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2745 $comment .= ": $reason";
2748 $newid = $nt->getArticleID();
2749 $oldid = $this->getArticleID();
2750 $latest = $this->getLatestRevId();
2752 $dbw = wfGetDB( DB_MASTER
);
2754 $now = $dbw->timestamp();
2756 # Save a null revision in the page's history notifying of the move
2757 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2758 $nullRevId = $nullRevision->insertOn( $dbw );
2760 $article = new Article( $this );
2761 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2764 $dbw->update( 'page',
2766 'page_touched' => $now,
2767 'page_namespace' => $nt->getNamespace(),
2768 'page_title' => $nt->getDBkey(),
2769 'page_latest' => $nullRevId,
2771 /* WHERE */ array( 'page_id' => $oldid ),
2774 $nt->resetArticleID( $oldid );
2776 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2778 $mwRedir = MagicWord
::get( 'redirect' );
2779 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2780 $redirectArticle = new Article( $this );
2781 $newid = $redirectArticle->insertOn( $dbw );
2782 $redirectRevision = new Revision( array(
2784 'comment' => $comment,
2785 'text' => $redirectText ) );
2786 $redirectRevision->insertOn( $dbw );
2787 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2789 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2791 # Record the just-created redirect's linking to the page
2792 $dbw->insert( 'pagelinks',
2794 'pl_from' => $newid,
2795 'pl_namespace' => $nt->getNamespace(),
2796 'pl_title' => $nt->getDBkey() ),
2799 $this->resetArticleID( 0 );
2802 # Move an image if this is a file
2803 if( $this->getNamespace() == NS_IMAGE
) {
2804 $file = wfLocalFile( $this );
2805 if( $file->exists() ) {
2806 $status = $file->move( $nt );
2807 if( !$status->isOk() ) {
2809 return $status->getErrorsArray();
2816 $log = new LogPage( 'move' );
2817 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2819 # Purge caches as per article creation
2820 Article
::onArticleCreate( $nt );
2822 # Purge old title from squid
2823 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2824 $this->purgeSquid();
2829 * Checks if $this can be moved to a given Title
2830 * - Selects for update, so don't call it unless you mean business
2832 * @param Title &$nt the new title to check
2834 public function isValidMoveTarget( $nt ) {
2836 $fname = 'Title::isValidMoveTarget';
2837 $dbw = wfGetDB( DB_MASTER
);
2839 # Is it an existsing file?
2840 if( $nt->getNamespace() == NS_IMAGE
) {
2841 $file = wfLocalFile( $nt );
2842 if( $file->exists() ) {
2843 wfDebug( __METHOD__
. ": file exists\n" );
2849 $id = $nt->getArticleID();
2850 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2851 array( 'page_is_redirect','old_text','old_flags' ),
2852 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2853 $fname, 'FOR UPDATE' );
2855 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2857 wfDebug( __METHOD__
. ": not a redirect\n" );
2860 $text = Revision
::getRevisionText( $obj );
2862 # Does the redirect point to the source?
2863 # Or is it a broken self-redirect, usually caused by namespace collisions?
2865 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2866 $redirTitle = Title
::newFromText( $m[1] );
2867 if( !is_object( $redirTitle ) ||
2868 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2869 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2870 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2875 wfDebug( __METHOD__
. ": failsafe\n" );
2879 # Does the article have a history?
2880 $row = $dbw->selectRow( array( 'page', 'revision'),
2882 array( 'page_namespace' => $nt->getNamespace(),
2883 'page_title' => $nt->getDBkey(),
2884 'page_id=rev_page AND page_latest != rev_id'
2885 ), $fname, 'FOR UPDATE'
2888 # Return true if there was no history
2889 return $row === false;
2893 * Can this title be added to a user's watchlist?
2897 public function isWatchable() {
2898 return !$this->isExternal()
2899 && MWNamespace
::isWatchable( $this->getNamespace() );
2903 * Get categories to which this Title belongs and return an array of
2904 * categories' names.
2906 * @return array an array of parents in the form:
2907 * $parent => $currentarticle
2909 public function getParentCategories() {
2912 $titlekey = $this->getArticleId();
2913 $dbr = wfGetDB( DB_SLAVE
);
2914 $categorylinks = $dbr->tableName( 'categorylinks' );
2917 $sql = "SELECT * FROM $categorylinks"
2918 ." WHERE cl_from='$titlekey'"
2919 ." AND cl_from <> '0'"
2920 ." ORDER BY cl_sortkey";
2922 $res = $dbr->query( $sql );
2924 if( $dbr->numRows( $res ) > 0 ) {
2925 foreach( $res as $row )
2926 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2927 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2928 $dbr->freeResult( $res );
2936 * Get a tree of parent categories
2937 * @param array $children an array with the children in the keys, to check for circular refs
2940 public function getParentCategoryTree( $children = array() ) {
2942 $parents = $this->getParentCategories();
2945 foreach( $parents as $parent => $current ) {
2946 if ( array_key_exists( $parent, $children ) ) {
2947 # Circular reference
2948 $stack[$parent] = array();
2950 $nt = Title
::newFromText($parent);
2952 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2964 * Get an associative array for selecting this title from
2969 public function pageCond() {
2970 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2974 * Get the revision ID of the previous revision
2976 * @param integer $revId Revision ID. Get the revision that was before this one.
2977 * @param integer $flags, GAID_FOR_UPDATE
2978 * @return integer $oldrevision|false
2980 public function getPreviousRevisionID( $revId, $flags=0 ) {
2981 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2982 return $db->selectField( 'revision', 'rev_id',
2984 'rev_page' => $this->getArticleId($flags),
2985 'rev_id < ' . intval( $revId )
2988 array( 'ORDER BY' => 'rev_id DESC' )
2993 * Get the revision ID of the next revision
2995 * @param integer $revId Revision ID. Get the revision that was after this one.
2996 * @param integer $flags, GAID_FOR_UPDATE
2997 * @return integer $oldrevision|false
2999 public function getNextRevisionID( $revId, $flags=0 ) {
3000 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3001 return $db->selectField( 'revision', 'rev_id',
3003 'rev_page' => $this->getArticleId($flags),
3004 'rev_id > ' . intval( $revId )
3007 array( 'ORDER BY' => 'rev_id' )
3012 * Get the number of revisions between the given revision IDs.
3013 * Used for diffs and other things that really need it.
3015 * @param integer $old Revision ID.
3016 * @param integer $new Revision ID.
3017 * @return integer Number of revisions between these IDs.
3019 public function countRevisionsBetween( $old, $new ) {
3020 $dbr = wfGetDB( DB_SLAVE
);
3021 return $dbr->selectField( 'revision', 'count(*)',
3022 'rev_page = ' . intval( $this->getArticleId() ) .
3023 ' AND rev_id > ' . intval( $old ) .
3024 ' AND rev_id < ' . intval( $new ),
3026 array( 'USE INDEX' => 'PRIMARY' ) );
3030 * Compare with another title.
3032 * @param Title $title
3035 public function equals( Title
$title ) {
3036 // Note: === is necessary for proper matching of number-like titles.
3037 return $this->getInterwiki() === $title->getInterwiki()
3038 && $this->getNamespace() == $title->getNamespace()
3039 && $this->getDBkey() === $title->getDBkey();
3043 * Callback for usort() to do title sorts by (namespace, title)
3045 static function compare( $a, $b ) {
3046 if( $a->getNamespace() == $b->getNamespace() ) {
3047 return strcmp( $a->getText(), $b->getText() );
3049 return $a->getNamespace() - $b->getNamespace();
3054 * Return a string representation of this title
3058 public function __toString() {
3059 return $this->getPrefixedText();
3063 * Check if page exists
3066 public function exists() {
3067 return $this->getArticleId() != 0;
3071 * Do we know that this title definitely exists, or should we otherwise
3072 * consider that it exists?
3076 public function isAlwaysKnown() {
3077 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3078 // the full l10n of that language to be loaded. That takes much memory and
3079 // isn't needed. So we strip the language part away.
3080 // Also, extension messages which are not loaded, are shown as red, because
3081 // we don't call MessageCache::loadAllMessages.
3082 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3083 return $this->isExternal()
3084 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3085 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3089 * Update page_touched timestamps and send squid purge messages for
3090 * pages linking to this title. May be sent to the job queue depending
3091 * on the number of links. Typically called on create and delete.
3093 public function touchLinks() {
3094 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3097 if ( $this->getNamespace() == NS_CATEGORY
) {
3098 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3104 * Get the last touched timestamp
3106 public function getTouched() {
3107 $dbr = wfGetDB( DB_SLAVE
);
3108 $touched = $dbr->selectField( 'page', 'page_touched',
3110 'page_namespace' => $this->getNamespace(),
3111 'page_title' => $this->getDBkey()
3117 public function trackbackURL() {
3118 global $wgTitle, $wgScriptPath, $wgServer;
3120 return "$wgServer$wgScriptPath/trackback.php?article="
3121 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3124 public function trackbackRDF() {
3125 $url = htmlspecialchars($this->getFullURL());
3126 $title = htmlspecialchars($this->getText());
3127 $tburl = $this->trackbackURL();
3129 // Autodiscovery RDF is placed in comments so HTML validator
3130 // won't barf. This is a rather icky workaround, but seems
3131 // frequently used by this kind of RDF thingy.
3133 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3135 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3136 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3137 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3140 dc:identifier=\"$url\"
3142 trackback:ping=\"$tburl\" />
3148 * Generate strings used for xml 'id' names in monobook tabs
3151 public function getNamespaceKey() {
3153 switch ($this->getNamespace()) {
3156 return 'nstab-main';
3159 return 'nstab-user';
3161 return 'nstab-media';
3163 return 'nstab-special';
3165 case NS_PROJECT_TALK
:
3166 return 'nstab-project';
3169 return 'nstab-image';
3171 case NS_MEDIAWIKI_TALK
:
3172 return 'nstab-mediawiki';
3174 case NS_TEMPLATE_TALK
:
3175 return 'nstab-template';
3178 return 'nstab-help';
3180 case NS_CATEGORY_TALK
:
3181 return 'nstab-category';
3183 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3188 * Returns true if this title resolves to the named special page
3189 * @param string $name The special page name
3191 public function isSpecial( $name ) {
3192 if ( $this->getNamespace() == NS_SPECIAL
) {
3193 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3194 if ( $name == $thisName ) {
3202 * If the Title refers to a special page alias which is not the local default,
3203 * returns a new Title which points to the local default. Otherwise, returns $this.
3205 public function fixSpecialName() {
3206 if ( $this->getNamespace() == NS_SPECIAL
) {
3207 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3208 if ( $canonicalName ) {
3209 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3210 if ( $localName != $this->mDbkeyform
) {
3211 return Title
::makeTitle( NS_SPECIAL
, $localName );
3219 * Is this Title in a namespace which contains content?
3220 * In other words, is this a content page, for the purposes of calculating
3225 public function isContentPage() {
3226 return MWNamespace
::isContent( $this->getNamespace() );
3229 public function getRedirectsHere( $ns = null ) {
3232 $dbr = wfGetDB( DB_SLAVE
);
3234 'rd_namespace' => $this->getNamespace(),
3235 'rd_title' => $this->getDBkey(),
3238 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3240 $res = $dbr->select(
3241 array( 'redirect', 'page' ),
3242 array( 'page_namespace', 'page_title' ),
3248 foreach( $res as $row ) {
3249 $redirs[] = self
::newFromRow( $row );