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
66 # Don't change the following default, NS_MAIN is hardcoded in several
67 # places. See bug 696.
68 var $mDefaultNamespace = NS_MAIN
; # Namespace index when there is no namespace
69 # Zero except in {{transclusion}} tags
70 var $mWatched = null; # Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
71 var $mLength = -1; # The page length, 0 for special pages
72 var $mRedirect = null; # Is the article at this title a redirect?
80 /* private */ function __construct() {}
83 * Create a new Title from a prefixed DB key
84 * @param string $key The database key, which has underscores
85 * instead of spaces, possibly including namespace and
87 * @return Title the new object, or NULL on an error
89 public static function newFromDBkey( $key ) {
91 $t->mDbkeyform
= $key;
92 if( $t->secureAndSplit() )
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
109 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
110 if( is_object( $text ) ) {
111 throw new MWException( 'Title::newFromText given an object' );
115 * Wiki pages often contain multiple links to the same page.
116 * Title normalization and parsing can become expensive on
117 * pages with many links, so we can save a little time by
120 * In theory these are value objects and won't get changed...
122 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
123 return Title
::$titleCache[$text];
127 * Convert things like é ā or 〗 into real text...
129 $filteredText = Sanitizer
::decodeCharReferences( $text );
132 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
133 $t->mDefaultNamespace
= $defaultNamespace;
135 static $cachedcount = 0 ;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( $cachedcount >= MW_TITLECACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 Title
::$titleCache = array();
144 Title
::$titleCache[$text] =& $t;
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
159 public static function newFromURL( $url ) {
160 global $wgLegalTitleChars;
163 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
164 # but some URLs used it as a space replacement and they still come
165 # from some external search tools.
166 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
167 $url = str_replace( '+', ' ', $url );
170 $t->mDbkeyform
= str_replace( ' ', '_', $url );
171 if( $t->secureAndSplit() ) {
179 * Create a new Title from an article ID
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
184 * @param int $id the page_id corresponding to the Title to create
185 * @param int $flags, use GAID_FOR_UPDATE to use master
186 * @return Title the new object, or NULL on an error
188 public static function newFromID( $id, $flags = 0 ) {
189 $fname = 'Title::newFromID';
190 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
191 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
192 array( 'page_id' => $id ), $fname );
193 if ( $row !== false ) {
194 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
202 * Make an array of titles from an array of IDs
204 public static function newFromIDs( $ids ) {
205 if ( !count( $ids ) ) {
208 $dbr = wfGetDB( DB_SLAVE
);
209 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
210 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
213 foreach( $res as $row ) {
214 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
220 * Make a Title object from a DB row
221 * @param Row $row (needs at least page_title,page_namespace)
223 public static function newFromRow( $row ) {
224 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
226 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
227 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
228 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
229 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
235 * Create a new Title from a namespace index and a DB key.
236 * It's assumed that $ns and $title are *valid*, for instance when
237 * they came directly from the database or a special page name.
238 * For convenience, spaces are converted to underscores so that
239 * eg user_text fields can be used directly.
241 * @param int $ns the namespace of the article
242 * @param string $title the unprefixed database key form
243 * @param string $fragment The link fragment (after the "#")
244 * @return Title the new object
246 public static function &makeTitle( $ns, $title, $fragment = '' ) {
249 $t->mFragment
= $fragment;
250 $t->mNamespace
= $ns = intval( $ns );
251 $t->mDbkeyform
= str_replace( ' ', '_', $title );
252 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
253 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
254 $t->mTextform
= str_replace( '_', ' ', $title );
259 * Create a new Title from a namespace index and a DB key.
260 * The parameters will be checked for validity, which is a bit slower
261 * than makeTitle() but safer for user-provided data.
263 * @param int $ns the namespace of the article
264 * @param string $title the database key form
265 * @param string $fragment The link fragment (after the "#")
266 * @return Title the new object, or NULL on an error
268 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
270 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
271 if( $t->secureAndSplit() ) {
279 * Create a new Title for the Main Page
280 * @return Title the new object
282 public static function newMainPage() {
283 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
284 // Don't give fatal errors if the message is broken
286 $title = Title
::newFromText( 'Main Page' );
292 * Extract a redirect destination from a string and return the
293 * Title, or null if the text doesn't contain a valid redirect
295 * @param string $text Text with possible redirect
298 public static function newFromRedirect( $text ) {
299 $redir = MagicWord
::get( 'redirect' );
301 if( $redir->matchStartAndRemove( $text ) ) {
302 // Extract the first link and see if it's usable
303 // Ensure that it really does come directly after #REDIRECT
304 // Some older redirects included a colon, so don't freak about that!
306 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
307 // Strip preceding colon used to "escape" categories, etc.
308 // and URL-decode links
309 if( strpos( $m[1], '%' ) !== false ) {
310 // Match behavior of inline link parsing here;
311 // don't interpret + as " " most of the time!
312 // It might be safe to just use rawurldecode instead, though.
313 $m[1] = urldecode( ltrim( $m[1], ':' ) );
315 $title = Title
::newFromText( $m[1] );
316 // Redirects to Special:Userlogout are not permitted
317 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
324 #----------------------------------------------------------------------------
326 #----------------------------------------------------------------------------
329 * Get the prefixed DB key associated with an ID
330 * @param int $id the page_id of the article
331 * @return Title an object representing the article, or NULL
332 * if no such article was found
334 public static function nameOf( $id ) {
335 $dbr = wfGetDB( DB_SLAVE
);
337 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
338 if ( $s === false ) { return NULL; }
340 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
345 * Get a regex character class describing the legal characters in a link
346 * @return string the list of characters, not delimited
348 public static function legalChars() {
349 global $wgLegalTitleChars;
350 return $wgLegalTitleChars;
354 * Get a string representation of a title suitable for
355 * including in a search index
357 * @param int $ns a namespace index
358 * @param string $title text-form main part
359 * @return string a stripped-down title string ready for the
362 public static function indexTitle( $ns, $title ) {
365 $lc = SearchEngine
::legalSearchChars() . '&#;';
366 $t = $wgContLang->stripForSearch( $title );
367 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
368 $t = $wgContLang->lc( $t );
371 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
372 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
374 $t = preg_replace( "/\\s+/", ' ', $t );
376 if ( $ns == NS_IMAGE
) {
377 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
383 * Make a prefixed DB key from a DB key and a namespace index
384 * @param int $ns numerical representation of the namespace
385 * @param string $title the DB key form the title
386 * @param string $fragment The link fragment (after the "#")
387 * @return string the prefixed form of the title
389 public static function makeName( $ns, $title, $fragment = '' ) {
392 $namespace = $wgContLang->getNsText( $ns );
393 $name = $namespace == '' ?
$title : "$namespace:$title";
394 if ( strval( $fragment ) != '' ) {
395 $name .= '#' . $fragment;
401 * Returns the URL associated with an interwiki prefix
402 * @param string $key the interwiki prefix (e.g. "MeatBall")
403 * @return the associated URL, containing "$1", which should be
404 * replaced by an article title
407 public function getInterwikiLink( $key ) {
408 global $wgMemc, $wgInterwikiExpiry;
409 global $wgInterwikiCache, $wgContLang;
410 $fname = 'Title::getInterwikiLink';
412 $key = $wgContLang->lc( $key );
414 $k = wfMemcKey( 'interwiki', $key );
415 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
416 return Title
::$interwikiCache[$k]->iw_url
;
419 if ($wgInterwikiCache) {
420 return Title
::getInterwikiCached( $key );
423 $s = $wgMemc->get( $k );
424 # Ignore old keys with no iw_local
425 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
426 Title
::$interwikiCache[$k] = $s;
430 $dbr = wfGetDB( DB_SLAVE
);
431 $res = $dbr->select( 'interwiki',
432 array( 'iw_url', 'iw_local', 'iw_trans' ),
433 array( 'iw_prefix' => $key ), $fname );
438 $s = $dbr->fetchObject( $res );
440 # Cache non-existence: create a blank object and save it to memcached
446 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
447 Title
::$interwikiCache[$k] = $s;
453 * Fetch interwiki prefix data from local cache in constant database
455 * More logic is explained in DefaultSettings
457 * @return string URL of interwiki site
459 public static function getInterwikiCached( $key ) {
460 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
464 $db=dba_open($wgInterwikiCache,'r','cdb');
465 /* Resolve site name */
466 if ($wgInterwikiScopes>=3 and !$site) {
467 $site = dba_fetch('__sites:' . wfWikiID(), $db);
469 $site = $wgInterwikiFallbackSite;
471 $value = dba_fetch( wfMemcKey( $key ), $db);
472 if ($value=='' and $wgInterwikiScopes>=3) {
474 $value = dba_fetch("_{$site}:{$key}", $db);
476 if ($value=='' and $wgInterwikiScopes>=2) {
478 $value = dba_fetch("__global:{$key}", $db);
487 list($local,$url)=explode(' ',$value,2);
489 $s->iw_local
=(int)$local;
491 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
495 * Determine whether the object refers to a page within
498 * @return bool TRUE if this is an in-project interwiki link
499 * or a wikilink, FALSE otherwise
501 public function isLocal() {
502 if ( $this->mInterwiki
!= '' ) {
503 # Make sure key is loaded into cache
504 $this->getInterwikiLink( $this->mInterwiki
);
505 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
506 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
513 * Determine whether the object refers to a page within
514 * this project and is transcludable.
516 * @return bool TRUE if this is transcludable
518 public function isTrans() {
519 if ($this->mInterwiki
== '')
521 # Make sure key is loaded into cache
522 $this->getInterwikiLink( $this->mInterwiki
);
523 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
524 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
528 * Escape a text fragment, say from a link, for a URL
530 static function escapeFragmentForURL( $fragment ) {
531 $fragment = str_replace( ' ', '_', $fragment );
532 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
533 $replaceArray = array(
537 return strtr( $fragment, $replaceArray );
540 #----------------------------------------------------------------------------
542 #----------------------------------------------------------------------------
544 /** Simple accessors */
546 * Get the text form (spaces not underscores) of the main part
549 public function getText() { return $this->mTextform
; }
551 * Get the URL-encoded form of the main part
554 public function getPartialURL() { return $this->mUrlform
; }
556 * Get the main part with underscores
559 public function getDBkey() { return $this->mDbkeyform
; }
561 * Get the namespace index, i.e. one of the NS_xxxx constants
564 public function getNamespace() { return $this->mNamespace
; }
566 * Get the namespace text
569 public function getNsText() {
570 global $wgContLang, $wgCanonicalNamespaceNames;
572 if ( '' != $this->mInterwiki
) {
573 // This probably shouldn't even happen. ohh man, oh yuck.
574 // But for interwiki transclusion it sometimes does.
575 // Shit. Shit shit shit.
577 // Use the canonical namespaces if possible to try to
578 // resolve a foreign namespace.
579 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
580 return $wgCanonicalNamespaceNames[$this->mNamespace
];
583 return $wgContLang->getNsText( $this->mNamespace
);
586 * Get the DB key with the initial letter case as specified by the user
588 function getUserCaseDBKey() {
589 return $this->mUserCaseDBKey
;
592 * Get the namespace text of the subject (rather than talk) page
595 public function getSubjectNsText() {
597 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
601 * Get the namespace text of the talk page
604 public function getTalkNsText() {
606 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
610 * Could this title have a corresponding talk page?
613 public function canTalk() {
614 return( MWNamespace
::canTalk( $this->mNamespace
) );
618 * Get the interwiki prefix (or null string)
621 public function getInterwiki() { return $this->mInterwiki
; }
623 * Get the Title fragment (i.e. the bit after the #) in text form
626 public function getFragment() { return $this->mFragment
; }
628 * Get the fragment in URL form, including the "#" character if there is one
631 public function getFragmentForURL() {
632 if ( $this->mFragment
== '' ) {
635 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
639 * Get the default namespace index, for when there is no namespace
642 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
645 * Get title for search index
646 * @return string a stripped-down title string ready for the
649 public function getIndexTitle() {
650 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
654 * Get the prefixed database key form
655 * @return string the prefixed title, with underscores and
656 * any interwiki and namespace prefixes
658 public function getPrefixedDBkey() {
659 $s = $this->prefix( $this->mDbkeyform
);
660 $s = str_replace( ' ', '_', $s );
665 * Get the prefixed title with spaces.
666 * This is the form usually used for display
667 * @return string the prefixed title, with spaces
669 public function getPrefixedText() {
670 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
671 $s = $this->prefix( $this->mTextform
);
672 $s = str_replace( '_', ' ', $s );
673 $this->mPrefixedText
= $s;
675 return $this->mPrefixedText
;
679 * Get the prefixed title with spaces, plus any fragment
680 * (part beginning with '#')
681 * @return string the prefixed title, with spaces and
682 * the fragment, including '#'
684 public function getFullText() {
685 $text = $this->getPrefixedText();
686 if( '' != $this->mFragment
) {
687 $text .= '#' . $this->mFragment
;
693 * Get the base name, i.e. the leftmost parts before the /
694 * @return string Base name
696 public function getBaseText() {
697 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
698 return $this->getText();
701 $parts = explode( '/', $this->getText() );
702 # Don't discard the real title if there's no subpage involved
703 if( count( $parts ) > 1 )
704 unset( $parts[ count( $parts ) - 1 ] );
705 return implode( '/', $parts );
709 * Get the lowest-level subpage name, i.e. the rightmost part after /
710 * @return string Subpage name
712 public function getSubpageText() {
713 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
714 return( $this->mTextform
);
716 $parts = explode( '/', $this->mTextform
);
717 return( $parts[ count( $parts ) - 1 ] );
721 * Get a URL-encoded form of the subpage text
722 * @return string URL-encoded subpage name
724 public function getSubpageUrlForm() {
725 $text = $this->getSubpageText();
726 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
727 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
732 * Get a URL-encoded title (not an actual URL) including interwiki
733 * @return string the URL-encoded form
735 public function getPrefixedURL() {
736 $s = $this->prefix( $this->mDbkeyform
);
737 $s = str_replace( ' ', '_', $s );
739 $s = wfUrlencode ( $s ) ;
741 # Cleaning up URL to make it look nice -- is this safe?
742 $s = str_replace( '%28', '(', $s );
743 $s = str_replace( '%29', ')', $s );
749 * Get a real URL referring to this title, with interwiki link and
752 * @param array $query an optional query string, not used for interwiki
753 * links. Can be specified as an associative array as well, e.g.,
754 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
755 * @param string $variant language variant of url (for sr, zh..)
756 * @return string the URL
758 public function getFullURL( $query = '', $variant = false ) {
759 global $wgContLang, $wgServer, $wgRequest;
761 if( is_array( $query ) ) {
762 $query = wfArrayToCGI( $query );
765 if ( '' == $this->mInterwiki
) {
766 $url = $this->getLocalUrl( $query, $variant );
768 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
769 // Correct fix would be to move the prepending elsewhere.
770 if ($wgRequest->getVal('action') != 'render') {
771 $url = $wgServer . $url;
774 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
776 $namespace = wfUrlencode( $this->getNsText() );
777 if ( '' != $namespace ) {
778 # Can this actually happen? Interwikis shouldn't be parsed.
779 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
782 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
783 $url = wfAppendQuery( $url, $query );
786 # Finally, add the fragment.
787 $url .= $this->getFragmentForURL();
789 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
794 * Get a URL with no fragment or server name. If this page is generated
795 * with action=render, $wgServer is prepended.
796 * @param mixed $query an optional query string; if not specified,
797 * $wgArticlePath will be used. Can be specified as an associative array
798 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
800 * @param string $variant language variant of url (for sr, zh..)
801 * @return string the URL
803 public function getLocalURL( $query = '', $variant = false ) {
804 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
805 global $wgVariantArticlePath, $wgContLang, $wgUser;
807 if( is_array( $query ) ) {
808 $query = wfArrayToCGI( $query );
811 // internal links should point to same variant as current page (only anonymous users)
812 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
813 $pref = $wgContLang->getPreferredVariant(false);
814 if($pref != $wgContLang->getCode())
818 if ( $this->isExternal() ) {
819 $url = $this->getFullURL();
821 // This is currently only used for edit section links in the
822 // context of interwiki transclusion. In theory we should
823 // append the query to the end of any existing query string,
824 // but interwiki transclusion is already broken in that case.
828 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
829 if ( $query == '' ) {
830 if( $variant != false && $wgContLang->hasVariants() ) {
831 if( $wgVariantArticlePath == false ) {
832 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
834 $variantArticlePath = $wgVariantArticlePath;
836 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
837 $url = str_replace( '$1', $dbkey, $url );
839 $url = str_replace( '$1', $dbkey, $wgArticlePath );
842 global $wgActionPaths;
845 if( !empty( $wgActionPaths ) &&
846 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
848 $action = urldecode( $matches[2] );
849 if( isset( $wgActionPaths[$action] ) ) {
850 $query = $matches[1];
851 if( isset( $matches[4] ) ) $query .= $matches[4];
852 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
853 if( $query != '' ) $url .= '?' . $query;
856 if ( $url === false ) {
857 if ( $query == '-' ) {
860 $url = "{$wgScript}?title={$dbkey}&{$query}";
864 // FIXME: this causes breakage in various places when we
865 // actually expected a local URL and end up with dupe prefixes.
866 if ($wgRequest->getVal('action') == 'render') {
867 $url = $wgServer . $url;
870 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
875 * Get a URL that's the simplest URL that will be valid to link, locally,
876 * to the current Title. It includes the fragment, but does not include
877 * the server unless action=render is used (or the link is external). If
878 * there's a fragment but the prefixed text is empty, we just return a link
881 * @param array $query An associative array of key => value pairs for the
882 * query string. Keys and values will be escaped.
883 * @param string $variant Language variant of URL (for sr, zh..). Ignored
884 * for external links. Default is "false" (same variant as current page,
885 * for anonymous users).
886 * @return string the URL
888 public function getLinkUrl( $query = array(), $variant = false ) {
889 if( !is_array( $query ) ) {
890 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
893 if( $this->isExternal() ) {
894 return $this->getFullURL( $query );
895 } elseif( $this->getPrefixedText() === ''
896 and $this->getFragment() !== '' ) {
897 return $this->getFragmentForURL();
899 return $this->getLocalURL( $query, $variant )
900 . $this->getFragmentForURL();
905 * Get an HTML-escaped version of the URL form, suitable for
906 * using in a link, without a server name or fragment
907 * @param string $query an optional query string
908 * @return string the URL
910 public function escapeLocalURL( $query = '' ) {
911 return htmlspecialchars( $this->getLocalURL( $query ) );
915 * Get an HTML-escaped version of the URL form, suitable for
916 * using in a link, including the server name and fragment
918 * @return string the URL
919 * @param string $query an optional query string
921 public function escapeFullURL( $query = '' ) {
922 return htmlspecialchars( $this->getFullURL( $query ) );
926 * Get the URL form for an internal link.
927 * - Used in various Squid-related code, in case we have a different
928 * internal hostname for the server from the exposed one.
930 * @param string $query an optional query string
931 * @param string $variant language variant of url (for sr, zh..)
932 * @return string the URL
934 public function getInternalURL( $query = '', $variant = false ) {
935 global $wgInternalServer;
936 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
937 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
942 * Get the edit URL for this Title
943 * @return string the URL, or a null string if this is an
946 public function getEditURL() {
947 if ( '' != $this->mInterwiki
) { return ''; }
948 $s = $this->getLocalURL( 'action=edit' );
954 * Get the HTML-escaped displayable text form.
955 * Used for the title field in <a> tags.
956 * @return string the text, including any prefixes
958 public function getEscapedText() {
959 return htmlspecialchars( $this->getPrefixedText() );
963 * Is this Title interwiki?
966 public function isExternal() { return ( '' != $this->mInterwiki
); }
969 * Is this page "semi-protected" - the *only* protection is autoconfirm?
971 * @param string Action to check (default: edit)
974 public function isSemiProtected( $action = 'edit' ) {
975 if( $this->exists() ) {
976 $restrictions = $this->getRestrictions( $action );
977 if( count( $restrictions ) > 0 ) {
978 foreach( $restrictions as $restriction ) {
979 if( strtolower( $restriction ) != 'autoconfirmed' )
988 # If it doesn't exist, it can't be protected
994 * Does the title correspond to a protected article?
995 * @param string $what the action the page is protected from,
996 * by default checks move and edit
999 public function isProtected( $action = '' ) {
1000 global $wgRestrictionLevels, $wgRestrictionTypes;
1002 # Special pages have inherent protection
1003 if( $this->getNamespace() == NS_SPECIAL
)
1006 # Check regular protection levels
1007 foreach( $wgRestrictionTypes as $type ){
1008 if( $action == $type ||
$action == '' ) {
1009 $r = $this->getRestrictions( $type );
1010 foreach( $wgRestrictionLevels as $level ) {
1011 if( in_array( $level, $r ) && $level != '' ) {
1022 * Is $wgUser watching this page?
1025 public function userIsWatching() {
1028 if ( is_null( $this->mWatched
) ) {
1029 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1030 $this->mWatched
= false;
1032 $this->mWatched
= $wgUser->isWatched( $this );
1035 return $this->mWatched
;
1039 * Can $wgUser perform $action on this page?
1040 * This skips potentially expensive cascading permission checks.
1042 * Suitable for use for nonessential UI controls in common cases, but
1043 * _not_ for functional access control.
1045 * May provide false positives, but should never provide a false negative.
1047 * @param string $action action that permission needs to be checked for
1050 public function quickUserCan( $action ) {
1051 return $this->userCan( $action, false );
1055 * Determines if $wgUser is unable to edit this page because it has been protected
1056 * by $wgNamespaceProtection.
1060 public function isNamespaceProtected() {
1061 global $wgNamespaceProtection, $wgUser;
1062 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1063 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1064 if( $right != '' && !$wgUser->isAllowed( $right ) )
1072 * Can $wgUser perform $action on this page?
1073 * @param string $action action that permission needs to be checked for
1074 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1077 public function userCan( $action, $doExpensiveQueries = true ) {
1079 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1083 * Can $user perform $action on this page?
1085 * FIXME: This *does not* check throttles (User::pingLimiter()).
1087 * @param string $action action that permission needs to be checked for
1088 * @param User $user user to check
1089 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1090 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1091 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1093 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1094 if( !StubObject
::isRealObject( $user ) ) {
1095 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1097 $wgUser->_unstub( '', 5 );
1100 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1104 global $wgEmailConfirmToEdit;
1106 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1107 $errors[] = array( 'confirmedittext' );
1110 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1111 $block = $user->mBlock
;
1113 // This is from OutputPage::blockedPage
1114 // Copied at r23888 by werdna
1116 $id = $user->blockedBy();
1117 $reason = $user->blockedFor();
1118 if( $reason == '' ) {
1119 $reason = wfMsg( 'blockednoreason' );
1123 if ( is_numeric( $id ) ) {
1124 $name = User
::whoIs( $id );
1129 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1130 $blockid = $block->mId
;
1131 $blockExpiry = $user->mBlock
->mExpiry
;
1132 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1134 if ( $blockExpiry == 'infinity' ) {
1135 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1136 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1138 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1139 if ( strpos( $option, ':' ) == false )
1142 list ($show, $value) = explode( ":", $option );
1144 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1145 $blockExpiry = $show;
1150 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1153 $intended = $user->mBlock
->mAddress
;
1155 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1156 $blockid, $blockExpiry, $intended, $blockTimestamp );
1159 // Remove the errors being ignored.
1161 foreach( $errors as $index => $error ) {
1162 $error_key = is_array($error) ?
$error[0] : $error;
1164 if (in_array( $error_key, $ignoreErrors )) {
1165 unset($errors[$index]);
1173 * Can $user perform $action on this page? This is an internal function,
1174 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1175 * checks on wfReadOnly() and blocks)
1177 * @param string $action action that permission needs to be checked for
1178 * @param User $user user to check
1179 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1180 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1182 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1183 wfProfileIn( __METHOD__
);
1187 // Use getUserPermissionsErrors instead
1188 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1189 wfProfileOut( __METHOD__
);
1190 return $result ?
array() : array( array( 'badaccess-group0' ) );
1193 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1194 if ($result != array() && is_array($result) && !is_array($result[0]))
1195 $errors[] = $result; # A single array representing an error
1196 else if (is_array($result) && is_array($result[0]))
1197 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1198 else if ($result != '' && $result != null && $result !== true && $result !== false)
1199 $errors[] = array($result); # A string representing a message-id
1200 else if ($result === false )
1201 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1203 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1204 if ($result != array() && is_array($result) && !is_array($result[0]))
1205 $errors[] = $result; # A single array representing an error
1206 else if (is_array($result) && is_array($result[0]))
1207 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1208 else if ($result != '' && $result != null && $result !== true && $result !== false)
1209 $errors[] = array($result); # A string representing a message-id
1210 else if ($result === false )
1211 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1214 $specialOKActions = array( 'createaccount', 'execute' );
1215 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1216 $errors[] = array('ns-specialprotected');
1219 if ( $this->isNamespaceProtected() ) {
1220 $ns = $this->getNamespace() == NS_MAIN
1221 ?
wfMsg( 'nstab-main' )
1222 : $this->getNsText();
1223 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1224 ?
array('protectedinterface')
1225 : array( 'namespaceprotected', $ns ) );
1228 if( $this->mDbkeyform
== '_' ) {
1229 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1230 $errors[] = array('badaccess-group0');
1233 # protect css/js subpages of user pages
1234 # XXX: this might be better using restrictions
1235 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1236 if( $this->isCssJsSubpage()
1237 && !$user->isAllowed('editusercssjs')
1238 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1239 $errors[] = array('customcssjsprotected');
1242 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1243 # We /could/ use the protection level on the source page, but it's fairly ugly
1244 # as we have to establish a precedence hierarchy for pages included by multiple
1245 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1246 # as they could remove the protection anyway.
1247 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1248 # Cascading protection depends on more than this page...
1249 # Several cascading protected pages may include this page...
1250 # Check each cascading level
1251 # This is only for protection restrictions, not for all actions
1252 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1253 foreach( $restrictions[$action] as $right ) {
1254 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1255 if( '' != $right && !$user->isAllowed( $right ) ) {
1257 foreach( $cascadingSources as $page )
1258 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1259 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1265 foreach( $this->getRestrictions($action) as $right ) {
1266 // Backwards compatibility, rewrite sysop -> protect
1267 if ( $right == 'sysop' ) {
1270 if( '' != $right && !$user->isAllowed( $right ) ) {
1271 //Users with 'editprotected' permission can edit protected pages
1272 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1273 //Users with 'editprotected' permission cannot edit protected pages
1274 //with cascading option turned on.
1275 if($this->mCascadeRestriction
) {
1276 $errors[] = array( 'protectedpagetext', $right );
1278 //Nothing, user can edit!
1281 $errors[] = array( 'protectedpagetext', $right );
1286 if ($action == 'protect') {
1287 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1288 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1292 if ($action == 'create') {
1293 $title_protection = $this->getTitleProtection();
1295 if (is_array($title_protection)) {
1296 extract($title_protection);
1298 if ($pt_create_perm == 'sysop')
1299 $pt_create_perm = 'protect';
1301 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1302 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1306 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1307 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1308 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1310 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1311 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1312 } elseif ( !$user->isAllowed( $action ) ) {
1314 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1315 User
::getGroupsWithPermission( $action ) );
1317 $return = array( 'badaccess-groups',
1319 implode( ', ', $groups ),
1320 count( $groups ) ) );
1323 $return = array( "badaccess-group0" );
1325 $errors[] = $return;
1328 wfProfileOut( __METHOD__
);
1333 * Is this title subject to title protection?
1334 * @return mixed An associative array representing any existent title
1335 * protection, or false if there's none.
1337 private function getTitleProtection() {
1338 // Can't protect pages in special namespaces
1339 if ( $this->getNamespace() < 0 ) {
1343 // Cache to avoid multiple database queries for the same title
1344 if ( isset($this->mProtections
) ) {
1345 return $this->mProtections
;
1349 'pt_namespace' => $this->getNamespace(),
1350 'pt_title' => $this->getDBkey()
1353 $dbr = wfGetDB( DB_SLAVE
);
1354 $res = $dbr->select( 'protected_titles', '*', $conds, __METHOD__
);
1356 if ($row = $dbr->fetchRow( $res )) {
1357 $this->mProtections
= $row;
1359 $this->mProtections
= false;
1362 return $this->mProtections
;
1365 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1366 global $wgUser,$wgContLang;
1368 if ($create_perm == implode(',',$this->getRestrictions('create'))
1369 && $expiry == $this->mRestrictionsExpiry
) {
1374 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1376 $dbw = wfGetDB( DB_MASTER
);
1378 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1380 $expiry_description = '';
1381 if ( $encodedExpiry != 'infinity' ) {
1382 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1385 # Update protection table
1386 if ($create_perm != '' ) {
1387 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1388 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1389 , 'pt_create_perm' => $create_perm
1390 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1391 , 'pt_expiry' => $encodedExpiry
1392 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1394 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1395 'pt_title' => $title ), __METHOD__
);
1397 # Update the protection log
1398 $log = new LogPage( 'protect' );
1400 if( $create_perm ) {
1401 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1403 $log->addEntry( 'unprotect', $this, $reason );
1410 * Remove any title protection (due to page existing
1412 public function deleteTitleProtection() {
1413 $dbw = wfGetDB( DB_MASTER
);
1415 $dbw->delete( 'protected_titles',
1416 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1420 * Can $wgUser edit this page?
1422 * @deprecated use userCan('edit')
1424 public function userCanEdit( $doExpensiveQueries = true ) {
1425 return $this->userCan( 'edit', $doExpensiveQueries );
1429 * Can $wgUser create this page?
1431 * @deprecated use userCan('create')
1433 public function userCanCreate( $doExpensiveQueries = true ) {
1434 return $this->userCan( 'create', $doExpensiveQueries );
1438 * Can $wgUser move this page?
1440 * @deprecated use userCan('move')
1442 public function userCanMove( $doExpensiveQueries = true ) {
1443 return $this->userCan( 'move', $doExpensiveQueries );
1447 * Would anybody with sufficient privileges be able to move this page?
1448 * Some pages just aren't movable.
1452 public function isMovable() {
1453 return MWNamespace
::isMovable( $this->getNamespace() )
1454 && $this->getInterwiki() == '';
1458 * Can $wgUser read this page?
1460 * @todo fold these checks into userCan()
1462 public function userCanRead() {
1463 global $wgUser, $wgGroupPermissions;
1466 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1467 if ( $result !== null ) {
1471 # Shortcut for public wikis, allows skipping quite a bit of code
1472 if ($wgGroupPermissions['*']['read'])
1475 if( $wgUser->isAllowed( 'read' ) ) {
1478 global $wgWhitelistRead;
1481 * Always grant access to the login page.
1482 * Even anons need to be able to log in.
1484 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1489 * Bail out if there isn't whitelist
1491 if( !is_array($wgWhitelistRead) ) {
1496 * Check for explicit whitelisting
1498 $name = $this->getPrefixedText();
1499 $dbName = $this->getPrefixedDBKey();
1500 // Check with and without underscores
1501 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1505 * Old settings might have the title prefixed with
1506 * a colon for main-namespace pages
1508 if( $this->getNamespace() == NS_MAIN
) {
1509 if( in_array( ':' . $name, $wgWhitelistRead ) )
1514 * If it's a special page, ditch the subpage bit
1517 if( $this->getNamespace() == NS_SPECIAL
) {
1518 $name = $this->getDBkey();
1519 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1520 if ( $name === false ) {
1521 # Invalid special page, but we show standard login required message
1525 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1526 if( in_array( $pure, $wgWhitelistRead, true ) )
1535 * Is this a talk page of some sort?
1538 public function isTalkPage() {
1539 return MWNamespace
::isTalk( $this->getNamespace() );
1543 * Is this a subpage?
1546 public function isSubpage() {
1547 return MWNamespace
::hasSubpages( $this->mNamespace
)
1548 ?
strpos( $this->getText(), '/' ) !== false
1553 * Does this have subpages? (Warning, usually requires an extra DB query.)
1556 public function hasSubpages() {
1557 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1562 # We dynamically add a member variable for the purpose of this method
1563 # alone to cache the result. There's no point in having it hanging
1564 # around uninitialized in every Title object; therefore we only add it
1565 # if needed and don't declare it statically.
1566 if( isset( $this->mHasSubpages
) ) {
1567 return $this->mHasSubpages
;
1570 $db = wfGetDB( DB_SLAVE
);
1571 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1572 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1573 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1579 * Could this page contain custom CSS or JavaScript, based
1584 public function isCssOrJsPage() {
1585 return $this->mNamespace
== NS_MEDIAWIKI
1586 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1590 * Is this a .css or .js subpage of a user page?
1593 public function isCssJsSubpage() {
1594 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1597 * Is this a *valid* .css or .js subpage of a user page?
1598 * Check that the corresponding skin exists
1600 public function isValidCssJsSubpage() {
1601 if ( $this->isCssJsSubpage() ) {
1602 $skinNames = Skin
::getSkinNames();
1603 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1609 * Trim down a .css or .js subpage title to get the corresponding skin name
1611 public function getSkinFromCssJsSubpage() {
1612 $subpage = explode( '/', $this->mTextform
);
1613 $subpage = $subpage[ count( $subpage ) - 1 ];
1614 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1617 * Is this a .css subpage of a user page?
1620 public function isCssSubpage() {
1621 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1624 * Is this a .js subpage of a user page?
1627 public function isJsSubpage() {
1628 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1631 * Protect css/js subpages of user pages: can $wgUser edit
1635 * @todo XXX: this might be better using restrictions
1637 public function userCanEditCssJsSubpage() {
1639 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1643 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1645 * @return bool If the page is subject to cascading restrictions.
1647 public function isCascadeProtected() {
1648 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1649 return ( $sources > 0 );
1653 * Cascading protection: Get the source of any cascading restrictions on this page.
1655 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1656 * @return array( mixed title array, restriction array)
1657 * 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.
1658 * The restriction array is an array of each type, each of which contains an array of unique groups
1660 public function getCascadeProtectionSources( $get_pages = true ) {
1661 global $wgRestrictionTypes;
1663 # Define our dimension of restrictions types
1664 $pagerestrictions = array();
1665 foreach( $wgRestrictionTypes as $action )
1666 $pagerestrictions[$action] = array();
1668 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1669 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1670 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1671 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1674 wfProfileIn( __METHOD__
);
1676 $dbr = wfGetDb( DB_SLAVE
);
1678 if ( $this->getNamespace() == NS_IMAGE
) {
1679 $tables = array ('imagelinks', 'page_restrictions');
1680 $where_clauses = array(
1681 'il_to' => $this->getDBkey(),
1683 'pr_cascade' => 1 );
1685 $tables = array ('templatelinks', 'page_restrictions');
1686 $where_clauses = array(
1687 'tl_namespace' => $this->getNamespace(),
1688 'tl_title' => $this->getDBkey(),
1690 'pr_cascade' => 1 );
1694 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1695 $where_clauses[] = 'page_id=pr_page';
1698 $cols = array( 'pr_expiry' );
1701 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1703 $sources = $get_pages ?
array() : false;
1704 $now = wfTimestampNow();
1705 $purgeExpired = false;
1707 foreach( $res as $row ) {
1708 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1709 if( $expiry > $now ) {
1711 $page_id = $row->pr_page
;
1712 $page_ns = $row->page_namespace
;
1713 $page_title = $row->page_title
;
1714 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1715 # Add groups needed for each restriction type if its not already there
1716 # Make sure this restriction type still exists
1717 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1718 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1724 // Trigger lazy purge of expired restrictions from the db
1725 $purgeExpired = true;
1728 if( $purgeExpired ) {
1729 Title
::purgeExpiredRestrictions();
1732 wfProfileOut( __METHOD__
);
1735 $this->mCascadeSources
= $sources;
1736 $this->mCascadingRestrictions
= $pagerestrictions;
1738 $this->mHasCascadingRestrictions
= $sources;
1741 return array( $sources, $pagerestrictions );
1744 function areRestrictionsCascading() {
1745 if (!$this->mRestrictionsLoaded
) {
1746 $this->loadRestrictions();
1749 return $this->mCascadeRestriction
;
1753 * Loads a string into mRestrictions array
1754 * @param resource $res restrictions as an SQL result.
1756 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1757 global $wgRestrictionTypes;
1758 $dbr = wfGetDB( DB_SLAVE
);
1760 foreach( $wgRestrictionTypes as $type ){
1761 $this->mRestrictions
[$type] = array();
1764 $this->mCascadeRestriction
= false;
1765 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1767 # Backwards-compatibility: also load the restrictions from the page record (old format).
1769 if ( $oldFashionedRestrictions === NULL ) {
1770 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1771 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1774 if ($oldFashionedRestrictions != '') {
1776 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1777 $temp = explode( '=', trim( $restrict ) );
1778 if(count($temp) == 1) {
1779 // old old format should be treated as edit/move restriction
1780 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1781 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1783 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1787 $this->mOldRestrictions
= true;
1791 if( $dbr->numRows( $res ) ) {
1792 # Current system - load second to make them override.
1793 $now = wfTimestampNow();
1794 $purgeExpired = false;
1796 foreach( $res as $row ) {
1797 # Cycle through all the restrictions.
1799 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1800 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1803 // This code should be refactored, now that it's being used more generally,
1804 // But I don't really see any harm in leaving it in Block for now -werdna
1805 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1807 // Only apply the restrictions if they haven't expired!
1808 if ( !$expiry ||
$expiry > $now ) {
1809 $this->mRestrictionsExpiry
= $expiry;
1810 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1812 $this->mCascadeRestriction |
= $row->pr_cascade
;
1814 // Trigger a lazy purge of expired restrictions
1815 $purgeExpired = true;
1819 if( $purgeExpired ) {
1820 Title
::purgeExpiredRestrictions();
1824 $this->mRestrictionsLoaded
= true;
1827 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1828 if( !$this->mRestrictionsLoaded
) {
1829 if ($this->exists()) {
1830 $dbr = wfGetDB( DB_SLAVE
);
1832 $res = $dbr->select( 'page_restrictions', '*',
1833 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1835 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1837 $title_protection = $this->getTitleProtection();
1839 if (is_array($title_protection)) {
1840 extract($title_protection);
1842 $now = wfTimestampNow();
1843 $expiry = Block
::decodeExpiry($pt_expiry);
1845 if (!$expiry ||
$expiry > $now) {
1846 // Apply the restrictions
1847 $this->mRestrictionsExpiry
= $expiry;
1848 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1849 } else { // Get rid of the old restrictions
1850 Title
::purgeExpiredRestrictions();
1853 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1855 $this->mRestrictionsLoaded
= true;
1861 * Purge expired restrictions from the page_restrictions table
1863 static function purgeExpiredRestrictions() {
1864 $dbw = wfGetDB( DB_MASTER
);
1865 $dbw->delete( 'page_restrictions',
1866 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1869 $dbw->delete( 'protected_titles',
1870 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1875 * Accessor/initialisation for mRestrictions
1877 * @param string $action action that permission needs to be checked for
1878 * @return array the array of groups allowed to edit this article
1880 public function getRestrictions( $action ) {
1881 if( !$this->mRestrictionsLoaded
) {
1882 $this->loadRestrictions();
1884 return isset( $this->mRestrictions
[$action] )
1885 ?
$this->mRestrictions
[$action]
1890 * Is there a version of this page in the deletion archive?
1891 * @return int the number of archived revisions
1893 public function isDeleted() {
1894 if ( $this->getNamespace() < 0 ) {
1898 // Cache to avoid multiple queries for the same title
1899 if ( isset($this->mIsDeleted
) ) {
1900 return $this->mIsDeleted
;
1903 $dbr = wfGetDB( DB_SLAVE
);
1905 'ar_namespace' => $this->getNamespace(),
1906 'ar_title' => $this->getDBkey()
1908 $n = $dbr->selectField( 'archive', 'COUNT(*)', $aConds, __METHOD__
);
1910 if ( $this->getNamespace() == NS_IMAGE
) {
1911 $faConds = array( 'fa_name' => $this->getDBkey() );
1912 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)', $faConds , __METHOD__
);
1915 $this->mIsDeleted
= (int) $n;
1917 return $this->mIsDeleted
;
1921 * Get the article ID for this Title from the link cache,
1922 * adding it if necessary
1923 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1925 * @return int the ID
1927 public function getArticleID( $flags = 0 ) {
1928 $linkCache = LinkCache
::singleton();
1929 if ( $flags & GAID_FOR_UPDATE
) {
1930 $oldUpdate = $linkCache->forUpdate( true );
1931 $this->mArticleID
= $linkCache->addLinkObj( $this );
1932 $linkCache->forUpdate( $oldUpdate );
1934 if ( -1 == $this->mArticleID
) {
1935 $this->mArticleID
= $linkCache->addLinkObj( $this );
1938 return $this->mArticleID
;
1942 * Is this an article that is a redirect page?
1943 * Uses link cache, adding it if necessary
1944 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1947 public function isRedirect( $flags = 0 ) {
1948 if( !is_null($this->mRedirect
) )
1949 return $this->mRedirect
;
1950 # Zero for special pages.
1951 # Also, calling getArticleID() loads the field from cache!
1952 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1955 $linkCache = LinkCache
::singleton();
1956 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1958 return $this->mRedirect
;
1962 * What is the length of this page?
1963 * Uses link cache, adding it if necessary
1964 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1967 public function getLength( $flags = 0 ) {
1968 if( $this->mLength
!= -1 )
1969 return $this->mLength
;
1970 # Zero for special pages.
1971 # Also, calling getArticleID() loads the field from cache!
1972 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1975 $linkCache = LinkCache
::singleton();
1976 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1978 return $this->mLength
;
1982 * What is the page_latest field for this page?
1983 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1986 public function getLatestRevID( $flags = 0 ) {
1987 if ($this->mLatestID
!== false)
1988 return $this->mLatestID
;
1990 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1991 return $this->mLatestID
= $db->selectField( 'revision',
1993 array('rev_page' => $this->getArticleID($flags)),
1994 'Title::getLatestRevID' );
1998 * This clears some fields in this object, and clears any associated
1999 * keys in the "bad links" section of the link cache.
2001 * - This is called from Article::insertNewArticle() to allow
2002 * loading of the new page_id. It's also called from
2003 * Article::doDeleteArticle()
2005 * @param int $newid the new Article ID
2007 public function resetArticleID( $newid ) {
2008 $linkCache = LinkCache
::singleton();
2009 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2011 if ( 0 == $newid ) { $this->mArticleID
= -1; }
2012 else { $this->mArticleID
= $newid; }
2013 $this->mRestrictionsLoaded
= false;
2014 $this->mRestrictions
= array();
2018 * Updates page_touched for this page; called from LinksUpdate.php
2019 * @return bool true if the update succeded
2021 public function invalidateCache() {
2022 global $wgUseFileCache;
2024 if ( wfReadOnly() ) {
2028 $dbw = wfGetDB( DB_MASTER
);
2029 $success = $dbw->update( 'page',
2031 'page_touched' => $dbw->timestamp()
2032 ), array( /* WHERE */
2033 'page_namespace' => $this->getNamespace() ,
2034 'page_title' => $this->getDBkey()
2035 ), 'Title::invalidateCache'
2038 if ($wgUseFileCache) {
2039 $cache = new HTMLFileCache($this);
2040 @unlink
($cache->fileCacheName());
2047 * Prefix some arbitrary text with the namespace or interwiki prefix
2050 * @param string $name the text
2051 * @return string the prefixed text
2054 /* private */ function prefix( $name ) {
2056 if ( '' != $this->mInterwiki
) {
2057 $p = $this->mInterwiki
. ':';
2059 if ( 0 != $this->mNamespace
) {
2060 $p .= $this->getNsText() . ':';
2066 * Secure and split - main initialisation function for this object
2068 * Assumes that mDbkeyform has been set, and is urldecoded
2069 * and uses underscores, but not otherwise munged. This function
2070 * removes illegal characters, splits off the interwiki and
2071 * namespace prefixes, sets the other forms, and canonicalizes
2073 * @return bool true on success
2075 private function secureAndSplit() {
2076 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2079 static $rxTc = false;
2081 # Matching titles will be held as illegal.
2083 # Any character not allowed is forbidden...
2084 '[^' . Title
::legalChars() . ']' .
2085 # URL percent encoding sequences interfere with the ability
2086 # to round-trip titles -- you can't link to them consistently.
2087 '|%[0-9A-Fa-f]{2}' .
2088 # XML/HTML character references produce similar issues.
2089 '|&[A-Za-z0-9\x80-\xff]+;' .
2091 '|&#x[0-9A-Fa-f]+;' .
2095 $this->mInterwiki
= $this->mFragment
= '';
2096 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2098 $dbkey = $this->mDbkeyform
;
2100 # Strip Unicode bidi override characters.
2101 # Sometimes they slip into cut-n-pasted page titles, where the
2102 # override chars get included in list displays.
2103 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2104 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2106 # Clean up whitespace
2108 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2109 $dbkey = trim( $dbkey, '_' );
2111 if ( '' == $dbkey ) {
2115 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2116 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2120 $this->mDbkeyform
= $dbkey;
2122 # Initial colon indicates main namespace rather than specified default
2123 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2124 if ( ':' == $dbkey{0} ) {
2125 $this->mNamespace
= NS_MAIN
;
2126 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2127 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2130 # Namespace or interwiki prefix
2134 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2136 if ( $ns = $wgContLang->getNsIndex( $p )) {
2137 # Ordinary namespace
2139 $this->mNamespace
= $ns;
2140 } elseif( $this->getInterwikiLink( $p ) ) {
2142 # Can't make a local interwiki link to an interwiki link.
2143 # That's just crazy!
2149 $this->mInterwiki
= $wgContLang->lc( $p );
2151 # Redundant interwiki prefix to the local wiki
2152 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2153 if( $dbkey == '' ) {
2154 # Can't have an empty self-link
2157 $this->mInterwiki
= '';
2159 # Do another namespace split...
2163 # If there's an initial colon after the interwiki, that also
2164 # resets the default namespace
2165 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2166 $this->mNamespace
= NS_MAIN
;
2167 $dbkey = substr( $dbkey, 1 );
2170 # If there's no recognized interwiki or namespace,
2171 # then let the colon expression be part of the title.
2176 # We already know that some pages won't be in the database!
2178 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2179 $this->mArticleID
= 0;
2181 $fragment = strstr( $dbkey, '#' );
2182 if ( false !== $fragment ) {
2183 $this->setFragment( $fragment );
2184 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2185 # remove whitespace again: prevents "Foo_bar_#"
2186 # becoming "Foo_bar_"
2187 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2190 # Reject illegal characters.
2192 if( preg_match( $rxTc, $dbkey ) ) {
2197 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2198 * reachable due to the way web browsers deal with 'relative' URLs.
2199 * Also, they conflict with subpage syntax. Forbid them explicitly.
2201 if ( strpos( $dbkey, '.' ) !== false &&
2202 ( $dbkey === '.' ||
$dbkey === '..' ||
2203 strpos( $dbkey, './' ) === 0 ||
2204 strpos( $dbkey, '../' ) === 0 ||
2205 strpos( $dbkey, '/./' ) !== false ||
2206 strpos( $dbkey, '/../' ) !== false ||
2207 substr( $dbkey, -2 ) == '/.' ||
2208 substr( $dbkey, -3 ) == '/..' ) )
2214 * Magic tilde sequences? Nu-uh!
2216 if( strpos( $dbkey, '~~~' ) !== false ) {
2221 * Limit the size of titles to 255 bytes.
2222 * This is typically the size of the underlying database field.
2223 * We make an exception for special pages, which don't need to be stored
2224 * in the database, and may edge over 255 bytes due to subpage syntax
2225 * for long titles, e.g. [[Special:Block/Long name]]
2227 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2228 strlen( $dbkey ) > 512 )
2234 * Normally, all wiki links are forced to have
2235 * an initial capital letter so [[foo]] and [[Foo]]
2236 * point to the same place.
2238 * Don't force it for interwikis, since the other
2239 * site might be case-sensitive.
2241 $this->mUserCaseDBKey
= $dbkey;
2242 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2243 $dbkey = $wgContLang->ucfirst( $dbkey );
2247 * Can't make a link to a namespace alone...
2248 * "empty" local links can only be self-links
2249 * with a fragment identifier.
2252 $this->mInterwiki
== '' &&
2253 $this->mNamespace
!= NS_MAIN
) {
2256 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2257 // IP names are not allowed for accounts, and can only be referring to
2258 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2259 // there are numerous ways to present the same IP. Having sp:contribs scan
2260 // them all is silly and having some show the edits and others not is
2261 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2262 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2263 IP
::sanitizeIP( $dbkey ) : $dbkey;
2264 // Any remaining initial :s are illegal.
2265 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2270 $this->mDbkeyform
= $dbkey;
2271 $this->mUrlform
= wfUrlencode( $dbkey );
2273 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2279 * Set the fragment for this title
2280 * This is kind of bad, since except for this rarely-used function, Title objects
2281 * are immutable. The reason this is here is because it's better than setting the
2282 * members directly, which is what Linker::formatComment was doing previously.
2284 * @param string $fragment text
2285 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2287 public function setFragment( $fragment ) {
2288 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2292 * Get a Title object associated with the talk page of this article
2293 * @return Title the object for the talk page
2295 public function getTalkPage() {
2296 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2300 * Get a title object associated with the subject page of this
2303 * @return Title the object for the subject page
2305 public function getSubjectPage() {
2306 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2310 * Get an array of Title objects linking to this Title
2311 * Also stores the IDs in the link cache.
2313 * WARNING: do not use this function on arbitrary user-supplied titles!
2314 * On heavily-used templates it will max out the memory.
2316 * @param string $options may be FOR UPDATE
2317 * @return array the Title objects linking here
2319 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2320 $linkCache = LinkCache
::singleton();
2323 $db = wfGetDB( DB_MASTER
);
2325 $db = wfGetDB( DB_SLAVE
);
2328 $res = $db->select( array( 'page', $table ),
2329 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2331 "{$prefix}_from=page_id",
2332 "{$prefix}_namespace" => $this->getNamespace(),
2333 "{$prefix}_title" => $this->getDBkey() ),
2338 if ( $db->numRows( $res ) ) {
2339 foreach( $res as $row ) {
2340 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2341 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2342 $retVal[] = $titleObj;
2346 $db->freeResult( $res );
2351 * Get an array of Title objects using this Title as a template
2352 * Also stores the IDs in the link cache.
2354 * WARNING: do not use this function on arbitrary user-supplied titles!
2355 * On heavily-used templates it will max out the memory.
2357 * @param string $options may be FOR UPDATE
2358 * @return array the Title objects linking here
2360 public function getTemplateLinksTo( $options = '' ) {
2361 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2365 * Get an array of Title objects referring to non-existent articles linked from this page
2367 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2368 * @param string $options may be FOR UPDATE
2369 * @return array the Title objects
2371 public function getBrokenLinksFrom( $options = '' ) {
2372 if ( $this->getArticleId() == 0 ) {
2373 # All links from article ID 0 are false positives
2378 $db = wfGetDB( DB_MASTER
);
2380 $db = wfGetDB( DB_SLAVE
);
2383 $res = $db->safeQuery(
2384 "SELECT pl_namespace, pl_title
2387 ON pl_namespace=page_namespace
2388 AND pl_title=page_title
2390 AND page_namespace IS NULL
2392 $db->tableName( 'pagelinks' ),
2393 $db->tableName( 'page' ),
2394 $this->getArticleId(),
2398 if ( $db->numRows( $res ) ) {
2399 foreach( $res as $row ) {
2400 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2403 $db->freeResult( $res );
2409 * Get a list of URLs to purge from the Squid cache when this
2412 * @return array the URLs
2414 public function getSquidURLs() {
2418 $this->getInternalURL(),
2419 $this->getInternalURL( 'action=history' )
2422 // purge variant urls as well
2423 if($wgContLang->hasVariants()){
2424 $variants = $wgContLang->getVariants();
2425 foreach($variants as $vCode){
2426 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2427 $urls[] = $this->getInternalURL('',$vCode);
2434 public function purgeSquid() {
2436 if ( $wgUseSquid ) {
2437 $urls = $this->getSquidURLs();
2438 $u = new SquidUpdate( $urls );
2444 * Move this page without authentication
2445 * @param Title &$nt the new page Title
2447 public function moveNoAuth( &$nt ) {
2448 return $this->moveTo( $nt, false );
2452 * Check whether a given move operation would be valid.
2453 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2454 * @param Title &$nt the new title
2455 * @param bool $auth indicates whether $wgUser's permissions
2457 * @param string $reason is the log summary of the move, used for spam checking
2458 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2460 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2463 // Normally we'd add this to $errors, but we'll get
2464 // lots of syntax errors if $nt is not an object
2465 return array(array('badtitletext'));
2467 if( $this->equals( $nt ) ) {
2468 $errors[] = array('selfmove');
2470 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2471 $errors[] = array('immobile_namespace');
2474 $oldid = $this->getArticleID();
2475 $newid = $nt->getArticleID();
2477 if ( strlen( $nt->getDBkey() ) < 1 ) {
2478 $errors[] = array('articleexists');
2480 if ( ( '' == $this->getDBkey() ) ||
2482 ( '' == $nt->getDBkey() ) ) {
2483 $errors[] = array('badarticleerror');
2486 // Image-specific checks
2487 if( $this->getNamespace() == NS_IMAGE
) {
2488 $file = wfLocalFile( $this );
2489 if( $file->exists() ) {
2490 if( $nt->getNamespace() != NS_IMAGE
) {
2491 $errors[] = array('imagenocrossnamespace');
2493 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2494 $errors[] = array('imageinvalidfilename');
2496 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2497 $errors[] = array('imagetypemismatch');
2504 $errors = array_merge($errors,
2505 $this->getUserPermissionsErrors('move', $wgUser),
2506 $this->getUserPermissionsErrors('edit', $wgUser),
2507 $nt->getUserPermissionsErrors('move', $wgUser),
2508 $nt->getUserPermissionsErrors('edit', $wgUser));
2513 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2514 $errors[] = array('hookaborted', $err);
2517 # The move is allowed only if (1) the target doesn't exist, or
2518 # (2) the target is a redirect to the source, and has no history
2519 # (so we can undo bad moves right after they're done).
2521 if ( 0 != $newid ) { # Target exists; check for validity
2522 if ( ! $this->isValidMoveTarget( $nt ) ) {
2523 $errors[] = array('articleexists');
2526 $tp = $nt->getTitleProtection();
2527 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2528 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2529 $errors[] = array('cantmove-titleprotected');
2538 * Move a title to a new location
2539 * @param Title &$nt the new title
2540 * @param bool $auth indicates whether $wgUser's permissions
2542 * @param string $reason The reason for the move
2543 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2544 * Ignored if the user doesn't have the suppressredirect right.
2545 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2547 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2548 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2549 if( is_array( $err ) ) {
2553 $pageid = $this->getArticleID();
2554 if( $nt->exists() ) {
2555 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2556 $pageCountChange = ($createRedirect ?
0 : -1);
2557 } else { # Target didn't exist, do normal move.
2558 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2559 $pageCountChange = ($createRedirect ?
1 : 0);
2562 if( is_array( $err ) ) {
2565 $redirid = $this->getArticleID();
2567 // Category memberships include a sort key which may be customized.
2568 // If it's left as the default (the page title), we need to update
2569 // the sort key to match the new title.
2571 // Be careful to avoid resetting cl_timestamp, which may disturb
2572 // time-based lists on some sites.
2574 // Warning -- if the sort key is *explicitly* set to the old title,
2575 // we can't actually distinguish it from a default here, and it'll
2576 // be set to the new title even though it really shouldn't.
2577 // It'll get corrected on the next edit, but resetting cl_timestamp.
2578 $dbw = wfGetDB( DB_MASTER
);
2579 $dbw->update( 'categorylinks',
2581 'cl_sortkey' => $nt->getPrefixedText(),
2582 'cl_timestamp=cl_timestamp' ),
2584 'cl_from' => $pageid,
2585 'cl_sortkey' => $this->getPrefixedText() ),
2590 $oldnamespace = $this->getNamespace() & ~
1;
2591 $newnamespace = $nt->getNamespace() & ~
1;
2592 $oldtitle = $this->getDBkey();
2593 $newtitle = $nt->getDBkey();
2595 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2596 WatchedItem
::duplicateEntries( $this, $nt );
2599 # Update search engine
2600 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2602 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2606 if( $this->isContentPage() && !$nt->isContentPage() ) {
2607 # No longer a content page
2608 # Not viewed, edited, removing
2609 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2610 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2611 # Now a content page
2612 # Not viewed, edited, adding
2613 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2614 } elseif( $pageCountChange ) {
2616 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2623 # Update message cache for interface messages
2624 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2625 global $wgMessageCache;
2626 $oldarticle = new Article( $this );
2627 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2628 $newarticle = new Article( $nt );
2629 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2633 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2638 * Move page to a title which is at present a redirect to the
2641 * @param Title &$nt the page to move to, which should currently
2643 * @param string $reason The reason for the move
2644 * @param bool $createRedirect Whether to leave a redirect at the old title.
2645 * Ignored if the user doesn't have the suppressredirect right
2647 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2648 global $wgUseSquid, $wgUser;
2649 $fname = 'Title::moveOverExistingRedirect';
2650 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2653 $comment .= ": $reason";
2656 $now = wfTimestampNow();
2657 $newid = $nt->getArticleID();
2658 $oldid = $this->getArticleID();
2659 $latest = $this->getLatestRevID();
2661 $dbw = wfGetDB( DB_MASTER
);
2664 # Delete the old redirect. We don't save it to history since
2665 # by definition if we've got here it's rather uninteresting.
2666 # We have to remove it so that the next step doesn't trigger
2667 # a conflict on the unique namespace+title index...
2668 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2669 if ( !$dbw->cascadingDeletes() ) {
2670 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2671 global $wgUseTrackbacks;
2672 if ($wgUseTrackbacks)
2673 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2674 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2675 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2676 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2677 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2678 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2679 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2680 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2683 # Save a null revision in the page's history notifying of the move
2684 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2685 $nullRevId = $nullRevision->insertOn( $dbw );
2687 $article = new Article( $this );
2688 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2690 # Change the name of the target page:
2691 $dbw->update( 'page',
2693 'page_touched' => $dbw->timestamp($now),
2694 'page_namespace' => $nt->getNamespace(),
2695 'page_title' => $nt->getDBkey(),
2696 'page_latest' => $nullRevId,
2698 /* WHERE */ array( 'page_id' => $oldid ),
2701 $nt->resetArticleID( $oldid );
2703 # Recreate the redirect, this time in the other direction.
2704 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2705 $mwRedir = MagicWord
::get( 'redirect' );
2706 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2707 $redirectArticle = new Article( $this );
2708 $newid = $redirectArticle->insertOn( $dbw );
2709 $redirectRevision = new Revision( array(
2711 'comment' => $comment,
2712 'text' => $redirectText ) );
2713 $redirectRevision->insertOn( $dbw );
2714 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2716 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2718 # Now, we record the link from the redirect to the new title.
2719 # It should have no other outgoing links...
2720 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2721 $dbw->insert( 'pagelinks',
2723 'pl_from' => $newid,
2724 'pl_namespace' => $nt->getNamespace(),
2725 'pl_title' => $nt->getDBkey() ),
2728 $this->resetArticleID( 0 );
2731 # Move an image if this is a file
2732 if( $this->getNamespace() == NS_IMAGE
) {
2733 $file = wfLocalFile( $this );
2734 if( $file->exists() ) {
2735 $status = $file->move( $nt );
2736 if( !$status->isOk() ) {
2738 return $status->getErrorsArray();
2745 $log = new LogPage( 'move' );
2746 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2749 if ( $wgUseSquid ) {
2750 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2751 $u = new SquidUpdate( $urls );
2758 * Move page to non-existing title.
2759 * @param Title &$nt the new Title
2760 * @param string $reason The reason for the move
2761 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2762 * Ignored if the user doesn't have the suppressredirect right
2764 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2765 global $wgUseSquid, $wgUser;
2766 $fname = 'MovePageForm::moveToNewTitle';
2767 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2769 $comment .= ": $reason";
2772 $newid = $nt->getArticleID();
2773 $oldid = $this->getArticleID();
2774 $latest = $this->getLatestRevId();
2776 $dbw = wfGetDB( DB_MASTER
);
2778 $now = $dbw->timestamp();
2780 # Save a null revision in the page's history notifying of the move
2781 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2782 $nullRevId = $nullRevision->insertOn( $dbw );
2784 $article = new Article( $this );
2785 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2788 $dbw->update( 'page',
2790 'page_touched' => $now,
2791 'page_namespace' => $nt->getNamespace(),
2792 'page_title' => $nt->getDBkey(),
2793 'page_latest' => $nullRevId,
2795 /* WHERE */ array( 'page_id' => $oldid ),
2798 $nt->resetArticleID( $oldid );
2800 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2802 $mwRedir = MagicWord
::get( 'redirect' );
2803 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2804 $redirectArticle = new Article( $this );
2805 $newid = $redirectArticle->insertOn( $dbw );
2806 $redirectRevision = new Revision( array(
2808 'comment' => $comment,
2809 'text' => $redirectText ) );
2810 $redirectRevision->insertOn( $dbw );
2811 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2813 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2815 # Record the just-created redirect's linking to the page
2816 $dbw->insert( 'pagelinks',
2818 'pl_from' => $newid,
2819 'pl_namespace' => $nt->getNamespace(),
2820 'pl_title' => $nt->getDBkey() ),
2823 $this->resetArticleID( 0 );
2826 # Move an image if this is a file
2827 if( $this->getNamespace() == NS_IMAGE
) {
2828 $file = wfLocalFile( $this );
2829 if( $file->exists() ) {
2830 $status = $file->move( $nt );
2831 if( !$status->isOk() ) {
2833 return $status->getErrorsArray();
2840 $log = new LogPage( 'move' );
2841 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2843 # Purge caches as per article creation
2844 Article
::onArticleCreate( $nt );
2846 # Purge old title from squid
2847 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2848 $this->purgeSquid();
2853 * Checks if $this can be moved to a given Title
2854 * - Selects for update, so don't call it unless you mean business
2856 * @param Title &$nt the new title to check
2858 public function isValidMoveTarget( $nt ) {
2860 $fname = 'Title::isValidMoveTarget';
2861 $dbw = wfGetDB( DB_MASTER
);
2863 # Is it an existsing file?
2864 if( $nt->getNamespace() == NS_IMAGE
) {
2865 $file = wfLocalFile( $nt );
2866 if( $file->exists() ) {
2867 wfDebug( __METHOD__
. ": file exists\n" );
2873 $id = $nt->getArticleID();
2874 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2875 array( 'page_is_redirect','old_text','old_flags' ),
2876 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2877 $fname, 'FOR UPDATE' );
2879 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2881 wfDebug( __METHOD__
. ": not a redirect\n" );
2884 $text = Revision
::getRevisionText( $obj );
2886 # Does the redirect point to the source?
2887 # Or is it a broken self-redirect, usually caused by namespace collisions?
2889 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2890 $redirTitle = Title
::newFromText( $m[1] );
2891 if( !is_object( $redirTitle ) ||
2892 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2893 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2894 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2899 wfDebug( __METHOD__
. ": failsafe\n" );
2903 # Does the article have a history?
2904 $row = $dbw->selectRow( array( 'page', 'revision'),
2906 array( 'page_namespace' => $nt->getNamespace(),
2907 'page_title' => $nt->getDBkey(),
2908 'page_id=rev_page AND page_latest != rev_id'
2909 ), $fname, 'FOR UPDATE'
2912 # Return true if there was no history
2913 return $row === false;
2917 * Can this title be added to a user's watchlist?
2921 public function isWatchable() {
2922 return !$this->isExternal()
2923 && MWNamespace
::isWatchable( $this->getNamespace() );
2927 * Get categories to which this Title belongs and return an array of
2928 * categories' names.
2930 * @return array an array of parents in the form:
2931 * $parent => $currentarticle
2933 public function getParentCategories() {
2936 $titlekey = $this->getArticleId();
2937 $dbr = wfGetDB( DB_SLAVE
);
2938 $categorylinks = $dbr->tableName( 'categorylinks' );
2941 $sql = "SELECT * FROM $categorylinks"
2942 ." WHERE cl_from='$titlekey'"
2943 ." AND cl_from <> '0'"
2944 ." ORDER BY cl_sortkey";
2946 $res = $dbr->query( $sql );
2948 if( $dbr->numRows( $res ) > 0 ) {
2949 foreach( $res as $row )
2950 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2951 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2952 $dbr->freeResult( $res );
2960 * Get a tree of parent categories
2961 * @param array $children an array with the children in the keys, to check for circular refs
2964 public function getParentCategoryTree( $children = array() ) {
2966 $parents = $this->getParentCategories();
2969 foreach( $parents as $parent => $current ) {
2970 if ( array_key_exists( $parent, $children ) ) {
2971 # Circular reference
2972 $stack[$parent] = array();
2974 $nt = Title
::newFromText($parent);
2976 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2988 * Get an associative array for selecting this title from
2993 public function pageCond() {
2994 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2998 * Get the revision ID of the previous revision
3000 * @param integer $revId Revision ID. Get the revision that was before this one.
3001 * @param integer $flags, GAID_FOR_UPDATE
3002 * @return integer $oldrevision|false
3004 public function getPreviousRevisionID( $revId, $flags=0 ) {
3005 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3006 return $db->selectField( 'revision', 'rev_id',
3008 'rev_page' => $this->getArticleId($flags),
3009 'rev_id < ' . intval( $revId )
3012 array( 'ORDER BY' => 'rev_id DESC' )
3017 * Get the revision ID of the next revision
3019 * @param integer $revId Revision ID. Get the revision that was after this one.
3020 * @param integer $flags, GAID_FOR_UPDATE
3021 * @return integer $oldrevision|false
3023 public function getNextRevisionID( $revId, $flags=0 ) {
3024 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3025 return $db->selectField( 'revision', 'rev_id',
3027 'rev_page' => $this->getArticleId($flags),
3028 'rev_id > ' . intval( $revId )
3031 array( 'ORDER BY' => 'rev_id' )
3036 * Get the number of revisions between the given revision IDs.
3037 * Used for diffs and other things that really need it.
3039 * @param integer $old Revision ID.
3040 * @param integer $new Revision ID.
3041 * @return integer Number of revisions between these IDs.
3043 public function countRevisionsBetween( $old, $new ) {
3044 $dbr = wfGetDB( DB_SLAVE
);
3045 return $dbr->selectField( 'revision', 'count(*)',
3046 'rev_page = ' . intval( $this->getArticleId() ) .
3047 ' AND rev_id > ' . intval( $old ) .
3048 ' AND rev_id < ' . intval( $new ),
3050 array( 'USE INDEX' => 'PRIMARY' ) );
3054 * Compare with another title.
3056 * @param Title $title
3059 public function equals( Title
$title ) {
3060 // Note: === is necessary for proper matching of number-like titles.
3061 return $this->getInterwiki() === $title->getInterwiki()
3062 && $this->getNamespace() == $title->getNamespace()
3063 && $this->getDBkey() === $title->getDBkey();
3067 * Callback for usort() to do title sorts by (namespace, title)
3069 static function compare( $a, $b ) {
3070 if( $a->getNamespace() == $b->getNamespace() ) {
3071 return strcmp( $a->getText(), $b->getText() );
3073 return $a->getNamespace() - $b->getNamespace();
3078 * Return a string representation of this title
3082 public function __toString() {
3083 return $this->getPrefixedText();
3087 * Check if page exists
3090 public function exists() {
3091 return $this->getArticleId() != 0;
3095 * Do we know that this title definitely exists, or should we otherwise
3096 * consider that it exists?
3100 public function isAlwaysKnown() {
3101 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3102 // the full l10n of that language to be loaded. That takes much memory and
3103 // isn't needed. So we strip the language part away.
3104 // Also, extension messages which are not loaded, are shown as red, because
3105 // we don't call MessageCache::loadAllMessages.
3106 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3107 return $this->isExternal()
3108 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3109 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3113 * Update page_touched timestamps and send squid purge messages for
3114 * pages linking to this title. May be sent to the job queue depending
3115 * on the number of links. Typically called on create and delete.
3117 public function touchLinks() {
3118 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3121 if ( $this->getNamespace() == NS_CATEGORY
) {
3122 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3128 * Get the last touched timestamp
3130 public function getTouched() {
3131 $dbr = wfGetDB( DB_SLAVE
);
3132 $touched = $dbr->selectField( 'page', 'page_touched',
3134 'page_namespace' => $this->getNamespace(),
3135 'page_title' => $this->getDBkey()
3141 public function trackbackURL() {
3142 global $wgTitle, $wgScriptPath, $wgServer;
3144 return "$wgServer$wgScriptPath/trackback.php?article="
3145 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3148 public function trackbackRDF() {
3149 $url = htmlspecialchars($this->getFullURL());
3150 $title = htmlspecialchars($this->getText());
3151 $tburl = $this->trackbackURL();
3153 // Autodiscovery RDF is placed in comments so HTML validator
3154 // won't barf. This is a rather icky workaround, but seems
3155 // frequently used by this kind of RDF thingy.
3157 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3159 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3160 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3161 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3164 dc:identifier=\"$url\"
3166 trackback:ping=\"$tburl\" />
3172 * Generate strings used for xml 'id' names in monobook tabs
3175 public function getNamespaceKey() {
3177 switch ($this->getNamespace()) {
3180 return 'nstab-main';
3183 return 'nstab-user';
3185 return 'nstab-media';
3187 return 'nstab-special';
3189 case NS_PROJECT_TALK
:
3190 return 'nstab-project';
3193 return 'nstab-image';
3195 case NS_MEDIAWIKI_TALK
:
3196 return 'nstab-mediawiki';
3198 case NS_TEMPLATE_TALK
:
3199 return 'nstab-template';
3202 return 'nstab-help';
3204 case NS_CATEGORY_TALK
:
3205 return 'nstab-category';
3207 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3212 * Returns true if this title resolves to the named special page
3213 * @param string $name The special page name
3215 public function isSpecial( $name ) {
3216 if ( $this->getNamespace() == NS_SPECIAL
) {
3217 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3218 if ( $name == $thisName ) {
3226 * If the Title refers to a special page alias which is not the local default,
3227 * returns a new Title which points to the local default. Otherwise, returns $this.
3229 public function fixSpecialName() {
3230 if ( $this->getNamespace() == NS_SPECIAL
) {
3231 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3232 if ( $canonicalName ) {
3233 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3234 if ( $localName != $this->mDbkeyform
) {
3235 return Title
::makeTitle( NS_SPECIAL
, $localName );
3243 * Is this Title in a namespace which contains content?
3244 * In other words, is this a content page, for the purposes of calculating
3249 public function isContentPage() {
3250 return MWNamespace
::isContent( $this->getNamespace() );
3253 public function getRedirectsHere( $ns = null ) {
3256 $dbr = wfGetDB( DB_SLAVE
);
3258 'rd_namespace' => $this->getNamespace(),
3259 'rd_title' => $this->getDBkey(),
3262 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3264 $res = $dbr->select(
3265 array( 'redirect', 'page' ),
3266 array( 'page_namespace', 'page_title' ),
3272 foreach( $res as $row ) {
3273 $redirs[] = self
::newFromRow( $row );