9 require_once( 'normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * Static cache variables
31 static private $titleCache=array();
32 static private $interwikiCache=array();
36 * All member variables should be considered private
37 * Please use the accessor functions
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
66 /* private */ function Title() {
67 $this->mInterwiki
= $this->mUrlform
=
68 $this->mTextform
= $this->mDbkeyform
= '';
69 $this->mArticleID
= -1;
70 $this->mNamespace
= NS_MAIN
;
71 $this->mRestrictionsLoaded
= false;
72 $this->mRestrictions
= array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
75 $this->mDefaultNamespace
= NS_MAIN
;
76 $this->mWatched
= NULL;
77 $this->mLatestID
= false;
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return Title the new object, or NULL on an error
89 /* 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
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
112 if( is_object( $text ) ) {
113 throw new MWException( 'Title::newFromText given an object' );
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
122 * In theory these are value objects and won't get changed...
124 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
125 return Title
::$titleCache[$text];
129 * Convert things like é ā or 〗 into real text...
131 $filteredText = Sanitizer
::decodeCharReferences( $text );
134 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace
= $defaultNamespace;
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN
) {
140 if( $cachedcount >= MW_TITLECACHE_MAX
) {
141 # Avoid memory leaks on mass operations...
142 Title
::$titleCache = array();
146 Title
::$titleCache[$text] =& $t;
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
163 public static function newFromURL( $url ) {
164 global $wgLegalTitleChars;
167 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
168 # but some URLs used it as a space replacement and they still come
169 # from some external search tools.
170 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
171 $url = str_replace( '+', ' ', $url );
174 $t->mDbkeyform
= str_replace( ' ', '_', $url );
175 if( $t->secureAndSplit() ) {
183 * Create a new Title from an article ID
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
193 public static function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE
);
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
207 * Make an array of titles from an array of IDs
209 function newFromIDs( $ids ) {
210 $dbr =& wfGetDB( DB_SLAVE
);
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
234 public static function &makeTitle( $ns, $title ) {
238 $t->mNamespace
= intval( $ns );
239 $t->mDbkeyform
= str_replace( ' ', '_', $title );
240 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
241 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
242 $t->mTextform
= str_replace( '_', ' ', $title );
247 * Create a new Title from a namespace index and a DB key.
248 * The parameters will be checked for validity, which is a bit slower
249 * than makeTitle() but safer for user-provided data.
251 * @param int $ns the namespace of the article
252 * @param string $title the database key form
253 * @return Title the new object, or NULL on an error
257 public static function makeTitleSafe( $ns, $title ) {
259 $t->mDbkeyform
= Title
::makeName( $ns, $title );
260 if( $t->secureAndSplit() ) {
268 * Create a new Title for the Main Page
271 * @return Title the new object
274 public static function newMainPage() {
275 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
279 * Create a new Title for a redirect
280 * @param string $text the redirect title text
281 * @return Title the new object, or NULL if the text is not a
284 public static function newFromRedirect( $text ) {
285 $mwRedir = MagicWord
::get( 'redirect' );
287 if ( $mwRedir->matchStart( $text ) ) {
289 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
290 # categories are escaped using : for example one can enter:
291 # #REDIRECT [[:Category:Music]]. Need to remove it.
292 if ( substr($m[1],0,1) == ':') {
293 # We don't want to keep the ':'
294 $m[1] = substr( $m[1], 1 );
297 $rt = Title
::newFromText( $m[1] );
298 # Disallow redirects to Special:Userlogout
299 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
307 #----------------------------------------------------------------------------
309 #----------------------------------------------------------------------------
312 * Get the prefixed DB key associated with an ID
313 * @param int $id the page_id of the article
314 * @return Title an object representing the article, or NULL
315 * if no such article was found
319 function nameOf( $id ) {
320 $fname = 'Title::nameOf';
321 $dbr =& wfGetDB( DB_SLAVE
);
323 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
324 if ( $s === false ) { return NULL; }
326 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
331 * Get a regex character class describing the legal characters in a link
332 * @return string the list of characters, not delimited
336 public static function legalChars() {
337 global $wgLegalTitleChars;
338 return $wgLegalTitleChars;
342 * Get a string representation of a title suitable for
343 * including in a search index
345 * @param int $ns a namespace index
346 * @param string $title text-form main part
347 * @return string a stripped-down title string ready for the
350 public static function indexTitle( $ns, $title ) {
353 $lc = SearchEngine
::legalSearchChars() . '&#;';
354 $t = $wgContLang->stripForSearch( $title );
355 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
356 $t = $wgContLang->lc( $t );
359 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
360 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
362 $t = preg_replace( "/\\s+/", ' ', $t );
364 if ( $ns == NS_IMAGE
) {
365 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
371 * Make a prefixed DB key from a DB key and a namespace index
372 * @param int $ns numerical representation of the namespace
373 * @param string $title the DB key form the title
374 * @return string the prefixed form of the title
376 public static function makeName( $ns, $title ) {
379 $n = $wgContLang->getNsText( $ns );
380 return $n == '' ?
$title : "$n:$title";
384 * Returns the URL associated with an interwiki prefix
385 * @param string $key the interwiki prefix (e.g. "MeatBall")
386 * @return the associated URL, containing "$1", which should be
387 * replaced by an article title
391 function getInterwikiLink( $key ) {
392 global $wgMemc, $wgInterwikiExpiry;
393 global $wgInterwikiCache, $wgContLang;
394 $fname = 'Title::getInterwikiLink';
396 $key = $wgContLang->lc( $key );
398 $k = wfMemcKey( 'interwiki', $key );
399 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
400 return Title
::$interwikiCache[$k]->iw_url
;
403 if ($wgInterwikiCache) {
404 return Title
::getInterwikiCached( $key );
407 $s = $wgMemc->get( $k );
408 # Ignore old keys with no iw_local
409 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
410 Title
::$interwikiCache[$k] = $s;
414 $dbr =& wfGetDB( DB_SLAVE
);
415 $res = $dbr->select( 'interwiki',
416 array( 'iw_url', 'iw_local', 'iw_trans' ),
417 array( 'iw_prefix' => $key ), $fname );
422 $s = $dbr->fetchObject( $res );
424 # Cache non-existence: create a blank object and save it to memcached
430 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
431 Title
::$interwikiCache[$k] = $s;
437 * Fetch interwiki prefix data from local cache in constant database
439 * More logic is explained in DefaultSettings
441 * @return string URL of interwiki site
444 function getInterwikiCached( $key ) {
445 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
449 $db=dba_open($wgInterwikiCache,'r','cdb');
450 /* Resolve site name */
451 if ($wgInterwikiScopes>=3 and !$site) {
452 $site = dba_fetch('__sites:' . wfWikiID(), $db);
454 $site = $wgInterwikiFallbackSite;
456 $value = dba_fetch( wfMemcKey( $key ), $db);
457 if ($value=='' and $wgInterwikiScopes>=3) {
459 $value = dba_fetch("_{$site}:{$key}", $db);
461 if ($value=='' and $wgInterwikiScopes>=2) {
463 $value = dba_fetch("__global:{$key}", $db);
472 list($local,$url)=explode(' ',$value,2);
474 $s->iw_local
=(int)$local;
476 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
480 * Determine whether the object refers to a page within
483 * @return bool TRUE if this is an in-project interwiki link
484 * or a wikilink, FALSE otherwise
488 if ( $this->mInterwiki
!= '' ) {
489 # Make sure key is loaded into cache
490 $this->getInterwikiLink( $this->mInterwiki
);
491 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
492 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
499 * Determine whether the object refers to a page within
500 * this project and is transcludable.
502 * @return bool TRUE if this is transcludable
506 if ($this->mInterwiki
== '')
508 # Make sure key is loaded into cache
509 $this->getInterwikiLink( $this->mInterwiki
);
510 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
511 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
515 * Update the page_touched field for an array of title objects
516 * @todo Inefficient unless the IDs are already loaded into the
518 * @param array $titles an array of Title objects to be touched
519 * @param string $timestamp the timestamp to use instead of the
520 * default current time
524 function touchArray( $titles, $timestamp = '' ) {
526 if ( count( $titles ) == 0 ) {
529 $dbw =& wfGetDB( DB_MASTER
);
530 if ( $timestamp == '' ) {
531 $timestamp = $dbw->timestamp();
534 $page = $dbw->tableName( 'page' );
535 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
538 foreach ( $titles as $title ) {
539 if ( $wgUseFileCache ) {
540 $cm = new HTMLFileCache($title);
541 @unlink($cm->fileCacheName());
548 $sql .= $title->getArticleID();
552 $dbw->query( $sql, 'Title::touchArray' );
555 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
556 // do them in small chunks:
557 $fname = 'Title::touchArray';
558 foreach( $titles as $title ) {
559 $dbw->update( 'page',
560 array( 'page_touched' => $timestamp ),
562 'page_namespace' => $title->getNamespace(),
563 'page_title' => $title->getDBkey() ),
569 * Escape a text fragment, say from a link, for a URL
571 static function escapeFragmentForURL( $fragment ) {
572 $fragment = str_replace( ' ', '_', $fragment );
573 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
574 $replaceArray = array(
578 return strtr( $fragment, $replaceArray );
581 #----------------------------------------------------------------------------
583 #----------------------------------------------------------------------------
585 /** Simple accessors */
587 * Get the text form (spaces not underscores) of the main part
591 function getText() { return $this->mTextform
; }
593 * Get the URL-encoded form of the main part
597 function getPartialURL() { return $this->mUrlform
; }
599 * Get the main part with underscores
603 function getDBkey() { return $this->mDbkeyform
; }
605 * Get the namespace index, i.e. one of the NS_xxxx constants
609 function getNamespace() { return $this->mNamespace
; }
611 * Get the namespace text
615 function getNsText() {
616 global $wgContLang, $wgCanonicalNamespaceNames;
618 if ( '' != $this->mInterwiki
) {
619 // This probably shouldn't even happen. ohh man, oh yuck.
620 // But for interwiki transclusion it sometimes does.
621 // Shit. Shit shit shit.
623 // Use the canonical namespaces if possible to try to
624 // resolve a foreign namespace.
625 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
626 return $wgCanonicalNamespaceNames[$this->mNamespace
];
629 return $wgContLang->getNsText( $this->mNamespace
);
632 * Get the namespace text of the subject (rather than talk) page
636 function getSubjectNsText() {
638 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
642 * Get the namespace text of the talk page
645 function getTalkNsText() {
647 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
651 * Could this title have a corresponding talk page?
655 return( Namespace::canTalk( $this->mNamespace
) );
659 * Get the interwiki prefix (or null string)
663 function getInterwiki() { return $this->mInterwiki
; }
665 * Get the Title fragment (i.e. the bit after the #) in text form
669 function getFragment() { return $this->mFragment
; }
671 * Get the fragment in URL form, including the "#" character if there is one
676 function getFragmentForURL() {
677 if ( $this->mFragment
== '' ) {
680 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
684 * Get the default namespace index, for when there is no namespace
688 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
691 * Get title for search index
692 * @return string a stripped-down title string ready for the
695 function getIndexTitle() {
696 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
700 * Get the prefixed database key form
701 * @return string the prefixed title, with underscores and
702 * any interwiki and namespace prefixes
705 function getPrefixedDBkey() {
706 $s = $this->prefix( $this->mDbkeyform
);
707 $s = str_replace( ' ', '_', $s );
712 * Get the prefixed title with spaces.
713 * This is the form usually used for display
714 * @return string the prefixed title, with spaces
717 function getPrefixedText() {
718 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
719 $s = $this->prefix( $this->mTextform
);
720 $s = str_replace( '_', ' ', $s );
721 $this->mPrefixedText
= $s;
723 return $this->mPrefixedText
;
727 * Get the prefixed title with spaces, plus any fragment
728 * (part beginning with '#')
729 * @return string the prefixed title, with spaces and
730 * the fragment, including '#'
733 function getFullText() {
734 $text = $this->getPrefixedText();
735 if( '' != $this->mFragment
) {
736 $text .= '#' . $this->mFragment
;
742 * Get the base name, i.e. the leftmost parts before the /
743 * @return string Base name
745 function getBaseText() {
746 global $wgNamespacesWithSubpages;
747 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
748 $parts = explode( '/', $this->getText() );
749 # Don't discard the real title if there's no subpage involved
750 if( count( $parts ) > 1 )
751 unset( $parts[ count( $parts ) - 1 ] );
752 return implode( '/', $parts );
754 return $this->getText();
759 * Get the lowest-level subpage name, i.e. the rightmost part after /
760 * @return string Subpage name
762 function getSubpageText() {
763 global $wgNamespacesWithSubpages;
764 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
765 $parts = explode( '/', $this->mTextform
);
766 return( $parts[ count( $parts ) - 1 ] );
768 return( $this->mTextform
);
773 * Get a URL-encoded form of the subpage text
774 * @return string URL-encoded subpage name
776 function getSubpageUrlForm() {
777 $text = $this->getSubpageText();
778 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
779 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
784 * Get a URL-encoded title (not an actual URL) including interwiki
785 * @return string the URL-encoded form
788 function getPrefixedURL() {
789 $s = $this->prefix( $this->mDbkeyform
);
790 $s = str_replace( ' ', '_', $s );
792 $s = wfUrlencode ( $s ) ;
794 # Cleaning up URL to make it look nice -- is this safe?
795 $s = str_replace( '%28', '(', $s );
796 $s = str_replace( '%29', ')', $s );
802 * Get a real URL referring to this title, with interwiki link and
805 * @param string $query an optional query string, not used
806 * for interwiki links
807 * @param string $variant language variant of url (for sr, zh..)
808 * @return string the URL
811 function getFullURL( $query = '', $variant = false ) {
812 global $wgContLang, $wgServer, $wgRequest;
814 if ( '' == $this->mInterwiki
) {
815 $url = $this->getLocalUrl( $query, $variant );
817 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
818 // Correct fix would be to move the prepending elsewhere.
819 if ($wgRequest->getVal('action') != 'render') {
820 $url = $wgServer . $url;
823 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
825 $namespace = wfUrlencode( $this->getNsText() );
826 if ( '' != $namespace ) {
827 # Can this actually happen? Interwikis shouldn't be parsed.
828 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
831 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
833 if( false === strpos( $url, '?' ) ) {
842 # Finally, add the fragment.
843 $url .= $this->getFragmentForURL();
845 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
850 * Get a URL with no fragment or server name. If this page is generated
851 * with action=render, $wgServer is prepended.
852 * @param string $query an optional query string; if not specified,
853 * $wgArticlePath will be used.
854 * @param string $variant language variant of url (for sr, zh..)
855 * @return string the URL
858 function getLocalURL( $query = '', $variant = false ) {
859 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
860 global $wgVariantArticlePath, $wgContLang, $wgUser;
862 // internal links should point to same variant as current page (only anonymous users)
863 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
864 $pref = $wgContLang->getPreferredVariant(false);
865 if($pref != $wgContLang->getCode())
869 if ( $this->isExternal() ) {
870 $url = $this->getFullURL();
872 // This is currently only used for edit section links in the
873 // context of interwiki transclusion. In theory we should
874 // append the query to the end of any existing query string,
875 // but interwiki transclusion is already broken in that case.
879 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
880 if ( $query == '' ) {
881 if($variant!=false && $wgContLang->hasVariants()){
882 if($wgVariantArticlePath==false)
883 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
885 $variantArticlePath = $wgVariantArticlePath;
887 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
888 $url = str_replace( '$1', $dbkey, $url );
892 $url = str_replace( '$1', $dbkey, $wgArticlePath );
894 global $wgActionPaths;
897 if( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
900 $action = urldecode( $matches[2] );
901 if( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if( isset( $matches[4] ) ) $query .= $matches[4];
904 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
905 if( $query != '' ) $url .= '?' . $query;
908 if ( $url === false ) {
909 if ( $query == '-' ) {
912 $url = "{$wgScript}?title={$dbkey}&{$query}";
916 // FIXME: this causes breakage in various places when we
917 // actually expected a local URL and end up with dupe prefixes.
918 if ($wgRequest->getVal('action') == 'render') {
919 $url = $wgServer . $url;
922 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
927 * Get an HTML-escaped version of the URL form, suitable for
928 * using in a link, without a server name or fragment
929 * @param string $query an optional query string
930 * @return string the URL
933 function escapeLocalURL( $query = '' ) {
934 return htmlspecialchars( $this->getLocalURL( $query ) );
938 * Get an HTML-escaped version of the URL form, suitable for
939 * using in a link, including the server name and fragment
941 * @return string the URL
942 * @param string $query an optional query string
945 function escapeFullURL( $query = '' ) {
946 return htmlspecialchars( $this->getFullURL( $query ) );
950 * Get the URL form for an internal link.
951 * - Used in various Squid-related code, in case we have a different
952 * internal hostname for the server from the exposed one.
954 * @param string $query an optional query string
955 * @param string $variant language variant of url (for sr, zh..)
956 * @return string the URL
959 function getInternalURL( $query = '', $variant = false ) {
960 global $wgInternalServer;
961 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
962 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
967 * Get the edit URL for this Title
968 * @return string the URL, or a null string if this is an
972 function getEditURL() {
973 if ( '' != $this->mInterwiki
) { return ''; }
974 $s = $this->getLocalURL( 'action=edit' );
980 * Get the HTML-escaped displayable text form.
981 * Used for the title field in <a> tags.
982 * @return string the text, including any prefixes
985 function getEscapedText() {
986 return htmlspecialchars( $this->getPrefixedText() );
990 * Is this Title interwiki?
994 function isExternal() { return ( '' != $this->mInterwiki
); }
997 * Is this page "semi-protected" - the *only* protection is autoconfirm?
999 * @param string Action to check (default: edit)
1002 function isSemiProtected( $action = 'edit' ) {
1003 if( $this->exists() ) {
1004 $restrictions = $this->getRestrictions( $action );
1005 if( count( $restrictions ) > 0 ) {
1006 foreach( $restrictions as $restriction ) {
1007 if( strtolower( $restriction ) != 'autoconfirmed' )
1016 # If it doesn't exist, it can't be protected
1022 * Does the title correspond to a protected article?
1023 * @param string $what the action the page is protected from,
1024 * by default checks move and edit
1028 function isProtected( $action = '' ) {
1029 global $wgRestrictionLevels;
1030 if ( NS_SPECIAL
== $this->mNamespace
) { return true; }
1032 if( $action == 'edit' ||
$action == '' ) {
1033 $r = $this->getRestrictions( 'edit' );
1034 foreach( $wgRestrictionLevels as $level ) {
1035 if( in_array( $level, $r ) && $level != '' ) {
1041 if( $action == 'move' ||
$action == '' ) {
1042 $r = $this->getRestrictions( 'move' );
1043 foreach( $wgRestrictionLevels as $level ) {
1044 if( in_array( $level, $r ) && $level != '' ) {
1054 * Is $wgUser is watching this page?
1058 function userIsWatching() {
1061 if ( is_null( $this->mWatched
) ) {
1062 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1063 $this->mWatched
= false;
1065 $this->mWatched
= $wgUser->isWatched( $this );
1068 return $this->mWatched
;
1072 * Can $wgUser perform $action this page?
1073 * @param string $action action that permission needs to be checked for
1077 function userCan($action) {
1078 $fname = 'Title::userCan';
1079 wfProfileIn( $fname );
1084 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1085 if ( $result !== null ) {
1086 wfProfileOut( $fname );
1090 if( NS_SPECIAL
== $this->mNamespace
) {
1091 wfProfileOut( $fname );
1094 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1095 // from taking effect -ævar
1096 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1097 !$wgUser->isAllowed('editinterface') ) {
1098 wfProfileOut( $fname );
1102 if( $this->mDbkeyform
== '_' ) {
1103 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1104 wfProfileOut( $fname );
1108 # protect css/js subpages of user pages
1109 # XXX: this might be better using restrictions
1110 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1111 if( $this->isCssJsSubpage()
1112 && !$wgUser->isAllowed('editinterface')
1113 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1114 wfProfileOut( $fname );
1118 foreach( $this->getRestrictions($action) as $right ) {
1119 // Backwards compatibility, rewrite sysop -> protect
1120 if ( $right == 'sysop' ) {
1123 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1124 wfProfileOut( $fname );
1129 if( $action == 'move' &&
1130 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1131 wfProfileOut( $fname );
1135 if( $action == 'create' ) {
1136 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1137 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1138 wfProfileOut( $fname );
1143 wfProfileOut( $fname );
1148 * Can $wgUser edit this page?
1152 function userCanEdit() {
1153 return $this->userCan('edit');
1157 * Can $wgUser create this page?
1161 function userCanCreate() {
1162 return $this->userCan('create');
1166 * Can $wgUser move this page?
1170 function userCanMove() {
1171 return $this->userCan('move');
1175 * Would anybody with sufficient privileges be able to move this page?
1176 * Some pages just aren't movable.
1181 function isMovable() {
1182 return Namespace::isMovable( $this->getNamespace() )
1183 && $this->getInterwiki() == '';
1187 * Can $wgUser read this page?
1191 function userCanRead() {
1195 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1196 if ( $result !== null ) {
1200 if( $wgUser->isAllowed('read') ) {
1203 global $wgWhitelistRead;
1206 * Always grant access to the login page.
1207 * Even anons need to be able to log in.
1209 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1213 /** some pages are explicitly allowed */
1214 $name = $this->getPrefixedText();
1215 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1219 # Compatibility with old settings
1220 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1221 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1230 * Is this a talk page of some sort?
1234 function isTalkPage() {
1235 return Namespace::isTalk( $this->getNamespace() );
1239 * Is this a subpage?
1243 function isSubpage() {
1244 global $wgNamespacesWithSubpages;
1246 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1247 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1254 * Is this a .css or .js subpage of a user page?
1258 function isCssJsSubpage() {
1259 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform
) );
1262 * Is this a *valid* .css or .js subpage of a user page?
1263 * Check that the corresponding skin exists
1265 function isValidCssJsSubpage() {
1266 if ( $this->isCssJsSubpage() ) {
1267 $skinNames = Skin
::getSkinNames();
1268 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1274 * Trim down a .css or .js subpage title to get the corresponding skin name
1276 function getSkinFromCssJsSubpage() {
1277 $subpage = explode( '/', $this->mTextform
);
1278 $subpage = $subpage[ count( $subpage ) - 1 ];
1279 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1282 * Is this a .css subpage of a user page?
1286 function isCssSubpage() {
1287 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1290 * Is this a .js subpage of a user page?
1294 function isJsSubpage() {
1295 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1298 * Protect css/js subpages of user pages: can $wgUser edit
1302 * @todo XXX: this might be better using restrictions
1305 function userCanEditCssJsSubpage() {
1307 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1311 * Loads a string into mRestrictions array
1312 * @param string $res restrictions in string format
1315 function loadRestrictions( $res ) {
1316 $this->mRestrictions
['edit'] = array();
1317 $this->mRestrictions
['move'] = array();
1320 # No restrictions (page_restrictions blank)
1321 $this->mRestrictionsLoaded
= true;
1325 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1326 $temp = explode( '=', trim( $restrict ) );
1327 if(count($temp) == 1) {
1328 // old format should be treated as edit/move restriction
1329 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1330 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1332 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1335 $this->mRestrictionsLoaded
= true;
1339 * Accessor/initialisation for mRestrictions
1342 * @param string $action action that permission needs to be checked for
1343 * @return array the array of groups allowed to edit this article
1345 function getRestrictions( $action ) {
1346 if( $this->exists() ) {
1347 if( !$this->mRestrictionsLoaded
) {
1348 $dbr =& wfGetDB( DB_SLAVE
);
1349 $res = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ) );
1350 $this->loadRestrictions( $res );
1352 return isset( $this->mRestrictions
[$action] )
1353 ?
$this->mRestrictions
[$action]
1361 * Is there a version of this page in the deletion archive?
1362 * @return int the number of archived revisions
1365 function isDeleted() {
1366 $fname = 'Title::isDeleted';
1367 if ( $this->getNamespace() < 0 ) {
1370 $dbr =& wfGetDB( DB_SLAVE
);
1371 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1372 'ar_title' => $this->getDBkey() ), $fname );
1373 if( $this->getNamespace() == NS_IMAGE
) {
1374 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1375 array( 'fa_name' => $this->getDBkey() ), $fname );
1382 * Get the article ID for this Title from the link cache,
1383 * adding it if necessary
1384 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1386 * @return int the ID
1388 public function getArticleID( $flags = 0 ) {
1389 $linkCache =& LinkCache
::singleton();
1390 if ( $flags & GAID_FOR_UPDATE
) {
1391 $oldUpdate = $linkCache->forUpdate( true );
1392 $this->mArticleID
= $linkCache->addLinkObj( $this );
1393 $linkCache->forUpdate( $oldUpdate );
1395 if ( -1 == $this->mArticleID
) {
1396 $this->mArticleID
= $linkCache->addLinkObj( $this );
1399 return $this->mArticleID
;
1402 function getLatestRevID() {
1403 if ($this->mLatestID
!== false)
1404 return $this->mLatestID
;
1406 $db =& wfGetDB(DB_SLAVE
);
1407 return $this->mLatestID
= $db->selectField( 'revision',
1409 array('rev_page' => $this->getArticleID()),
1410 'Title::getLatestRevID' );
1414 * This clears some fields in this object, and clears any associated
1415 * keys in the "bad links" section of the link cache.
1417 * - This is called from Article::insertNewArticle() to allow
1418 * loading of the new page_id. It's also called from
1419 * Article::doDeleteArticle()
1421 * @param int $newid the new Article ID
1424 function resetArticleID( $newid ) {
1425 $linkCache =& LinkCache
::singleton();
1426 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1428 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1429 else { $this->mArticleID
= $newid; }
1430 $this->mRestrictionsLoaded
= false;
1431 $this->mRestrictions
= array();
1435 * Updates page_touched for this page; called from LinksUpdate.php
1436 * @return bool true if the update succeded
1439 function invalidateCache() {
1440 global $wgUseFileCache;
1442 if ( wfReadOnly() ) {
1446 $dbw =& wfGetDB( DB_MASTER
);
1447 $success = $dbw->update( 'page',
1449 'page_touched' => $dbw->timestamp()
1450 ), array( /* WHERE */
1451 'page_namespace' => $this->getNamespace() ,
1452 'page_title' => $this->getDBkey()
1453 ), 'Title::invalidateCache'
1456 if ($wgUseFileCache) {
1457 $cache = new HTMLFileCache($this);
1458 @unlink
($cache->fileCacheName());
1465 * Prefix some arbitrary text with the namespace or interwiki prefix
1468 * @param string $name the text
1469 * @return string the prefixed text
1472 /* private */ function prefix( $name ) {
1474 if ( '' != $this->mInterwiki
) {
1475 $p = $this->mInterwiki
. ':';
1477 if ( 0 != $this->mNamespace
) {
1478 $p .= $this->getNsText() . ':';
1484 * Secure and split - main initialisation function for this object
1486 * Assumes that mDbkeyform has been set, and is urldecoded
1487 * and uses underscores, but not otherwise munged. This function
1488 * removes illegal characters, splits off the interwiki and
1489 * namespace prefixes, sets the other forms, and canonicalizes
1491 * @return bool true on success
1494 /* private */ function secureAndSplit() {
1495 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1498 static $rxTc = false;
1500 # % is needed as well
1501 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1504 $this->mInterwiki
= $this->mFragment
= '';
1505 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1507 $dbkey = $this->mDbkeyform
;
1509 # Strip Unicode bidi override characters.
1510 # Sometimes they slip into cut-n-pasted page titles, where the
1511 # override chars get included in list displays.
1512 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1513 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1515 # Clean up whitespace
1517 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1518 $dbkey = trim( $dbkey, '_' );
1520 if ( '' == $dbkey ) {
1524 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1525 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1529 $this->mDbkeyform
= $dbkey;
1531 # Initial colon indicates main namespace rather than specified default
1532 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1533 if ( ':' == $dbkey{0} ) {
1534 $this->mNamespace
= NS_MAIN
;
1535 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1538 # Namespace or interwiki prefix
1542 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1544 $lowerNs = $wgContLang->lc( $p );
1545 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1546 # Canonical namespace
1548 $this->mNamespace
= $ns;
1549 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1550 # Ordinary namespace
1552 $this->mNamespace
= $ns;
1553 } elseif( $this->getInterwikiLink( $p ) ) {
1555 # Can't make a local interwiki link to an interwiki link.
1556 # That's just crazy!
1562 $this->mInterwiki
= $wgContLang->lc( $p );
1564 # Redundant interwiki prefix to the local wiki
1565 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1566 if( $dbkey == '' ) {
1567 # Can't have an empty self-link
1570 $this->mInterwiki
= '';
1572 # Do another namespace split...
1576 # If there's an initial colon after the interwiki, that also
1577 # resets the default namespace
1578 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1579 $this->mNamespace
= NS_MAIN
;
1580 $dbkey = substr( $dbkey, 1 );
1583 # If there's no recognized interwiki or namespace,
1584 # then let the colon expression be part of the title.
1589 # We already know that some pages won't be in the database!
1591 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1592 $this->mArticleID
= 0;
1594 $fragment = strstr( $dbkey, '#' );
1595 if ( false !== $fragment ) {
1596 $this->setFragment( $fragment );
1597 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1598 # remove whitespace again: prevents "Foo_bar_#"
1599 # becoming "Foo_bar_"
1600 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1603 # Reject illegal characters.
1605 if( preg_match( $rxTc, $dbkey ) ) {
1610 * Pages with "/./" or "/../" appearing in the URLs will
1611 * often be unreachable due to the way web browsers deal
1612 * with 'relative' URLs. Forbid them explicitly.
1614 if ( strpos( $dbkey, '.' ) !== false &&
1615 ( $dbkey === '.' ||
$dbkey === '..' ||
1616 strpos( $dbkey, './' ) === 0 ||
1617 strpos( $dbkey, '../' ) === 0 ||
1618 strpos( $dbkey, '/./' ) !== false ||
1619 strpos( $dbkey, '/../' ) !== false ) )
1625 * Limit the size of titles to 255 bytes.
1626 * This is typically the size of the underlying database field.
1627 * We make an exception for special pages, which don't need to be stored
1628 * in the database, and may edge over 255 bytes due to subpage syntax
1629 * for long titles, e.g. [[Special:Block/Long name]]
1631 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1632 strlen( $dbkey ) > 512 )
1638 * Normally, all wiki links are forced to have
1639 * an initial capital letter so [[foo]] and [[Foo]]
1640 * point to the same place.
1642 * Don't force it for interwikis, since the other
1643 * site might be case-sensitive.
1645 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1646 $dbkey = $wgContLang->ucfirst( $dbkey );
1650 * Can't make a link to a namespace alone...
1651 * "empty" local links can only be self-links
1652 * with a fragment identifier.
1655 $this->mInterwiki
== '' &&
1656 $this->mNamespace
!= NS_MAIN
) {
1660 // Any remaining initial :s are illegal.
1661 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1666 $this->mDbkeyform
= $dbkey;
1667 $this->mUrlform
= wfUrlencode( $dbkey );
1669 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1675 * Set the fragment for this title
1676 * This is kind of bad, since except for this rarely-used function, Title objects
1677 * are immutable. The reason this is here is because it's better than setting the
1678 * members directly, which is what Linker::formatComment was doing previously.
1680 * @param string $fragment text
1681 * @access kind of public
1683 function setFragment( $fragment ) {
1684 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1688 * Get a Title object associated with the talk page of this article
1689 * @return Title the object for the talk page
1692 function getTalkPage() {
1693 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1697 * Get a title object associated with the subject page of this
1700 * @return Title the object for the subject page
1703 function getSubjectPage() {
1704 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1708 * Get an array of Title objects linking to this Title
1709 * Also stores the IDs in the link cache.
1711 * WARNING: do not use this function on arbitrary user-supplied titles!
1712 * On heavily-used templates it will max out the memory.
1714 * @param string $options may be FOR UPDATE
1715 * @return array the Title objects linking here
1718 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1719 $linkCache =& LinkCache
::singleton();
1722 $db =& wfGetDB( DB_MASTER
);
1724 $db =& wfGetDB( DB_SLAVE
);
1727 $res = $db->select( array( 'page', $table ),
1728 array( 'page_namespace', 'page_title', 'page_id' ),
1730 "{$prefix}_from=page_id",
1731 "{$prefix}_namespace" => $this->getNamespace(),
1732 "{$prefix}_title" => $this->getDbKey() ),
1733 'Title::getLinksTo',
1737 if ( $db->numRows( $res ) ) {
1738 while ( $row = $db->fetchObject( $res ) ) {
1739 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1740 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1741 $retVal[] = $titleObj;
1745 $db->freeResult( $res );
1750 * Get an array of Title objects using this Title as a template
1751 * Also stores the IDs in the link cache.
1753 * WARNING: do not use this function on arbitrary user-supplied titles!
1754 * On heavily-used templates it will max out the memory.
1756 * @param string $options may be FOR UPDATE
1757 * @return array the Title objects linking here
1760 function getTemplateLinksTo( $options = '' ) {
1761 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1765 * Get an array of Title objects referring to non-existent articles linked from this page
1767 * @param string $options may be FOR UPDATE
1768 * @return array the Title objects
1771 function getBrokenLinksFrom( $options = '' ) {
1773 $db =& wfGetDB( DB_MASTER
);
1775 $db =& wfGetDB( DB_SLAVE
);
1778 $res = $db->safeQuery(
1779 "SELECT pl_namespace, pl_title
1782 ON pl_namespace=page_namespace
1783 AND pl_title=page_title
1785 AND page_namespace IS NULL
1787 $db->tableName( 'pagelinks' ),
1788 $db->tableName( 'page' ),
1789 $this->getArticleId(),
1793 if ( $db->numRows( $res ) ) {
1794 while ( $row = $db->fetchObject( $res ) ) {
1795 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1798 $db->freeResult( $res );
1804 * Get a list of URLs to purge from the Squid cache when this
1807 * @return array the URLs
1810 function getSquidURLs() {
1814 $this->getInternalURL(),
1815 $this->getInternalURL( 'action=history' )
1818 // purge variant urls as well
1819 if($wgContLang->hasVariants()){
1820 $variants = $wgContLang->getVariants();
1821 foreach($variants as $vCode){
1822 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1823 $urls[] = $this->getInternalURL('',$vCode);
1830 function purgeSquid() {
1832 if ( $wgUseSquid ) {
1833 $urls = $this->getSquidURLs();
1834 $u = new SquidUpdate( $urls );
1840 * Move this page without authentication
1841 * @param Title &$nt the new page Title
1844 function moveNoAuth( &$nt ) {
1845 return $this->moveTo( $nt, false );
1849 * Check whether a given move operation would be valid.
1850 * Returns true if ok, or a message key string for an error message
1851 * if invalid. (Scarrrrry ugly interface this.)
1852 * @param Title &$nt the new title
1853 * @param bool $auth indicates whether $wgUser's permissions
1855 * @return mixed true on success, message name on failure
1858 function isValidMoveOperation( &$nt, $auth = true ) {
1859 if( !$this or !$nt ) {
1860 return 'badtitletext';
1862 if( $this->equals( $nt ) ) {
1865 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1866 return 'immobile_namespace';
1869 $oldid = $this->getArticleID();
1870 $newid = $nt->getArticleID();
1872 if ( strlen( $nt->getDBkey() ) < 1 ) {
1873 return 'articleexists';
1875 if ( ( '' == $this->getDBkey() ) ||
1877 ( '' == $nt->getDBkey() ) ) {
1878 return 'badarticleerror';
1882 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1883 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1884 return 'protectedpage';
1887 # The move is allowed only if (1) the target doesn't exist, or
1888 # (2) the target is a redirect to the source, and has no history
1889 # (so we can undo bad moves right after they're done).
1891 if ( 0 != $newid ) { # Target exists; check for validity
1892 if ( ! $this->isValidMoveTarget( $nt ) ) {
1893 return 'articleexists';
1900 * Move a title to a new location
1901 * @param Title &$nt the new title
1902 * @param bool $auth indicates whether $wgUser's permissions
1904 * @return mixed true on success, message name on failure
1907 function moveTo( &$nt, $auth = true, $reason = '' ) {
1908 $err = $this->isValidMoveOperation( $nt, $auth );
1909 if( is_string( $err ) ) {
1913 $pageid = $this->getArticleID();
1914 if( $nt->exists() ) {
1915 $this->moveOverExistingRedirect( $nt, $reason );
1916 $pageCountChange = 0;
1917 } else { # Target didn't exist, do normal move.
1918 $this->moveToNewTitle( $nt, $reason );
1919 $pageCountChange = 1;
1921 $redirid = $this->getArticleID();
1923 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1924 $dbw =& wfGetDB( DB_MASTER
);
1925 $categorylinks = $dbw->tableName( 'categorylinks' );
1926 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1927 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1928 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1929 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1933 $oldnamespace = $this->getNamespace() & ~
1;
1934 $newnamespace = $nt->getNamespace() & ~
1;
1935 $oldtitle = $this->getDBkey();
1936 $newtitle = $nt->getDBkey();
1938 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1939 WatchedItem
::duplicateEntries( $this, $nt );
1942 # Update search engine
1943 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1945 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1949 if( $this->isContentPage() && !$nt->isContentPage() ) {
1950 # No longer a content page
1951 # Not viewed, edited, removing
1952 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
1953 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
1954 # Now a content page
1955 # Not viewed, edited, adding
1956 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1957 } elseif( $pageCountChange ) {
1959 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1968 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1973 * Move page to a title which is at present a redirect to the
1976 * @param Title &$nt the page to move to, which should currently
1980 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1982 $fname = 'Title::moveOverExistingRedirect';
1983 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1986 $comment .= ": $reason";
1989 $now = wfTimestampNow();
1990 $newid = $nt->getArticleID();
1991 $oldid = $this->getArticleID();
1992 $dbw =& wfGetDB( DB_MASTER
);
1993 $linkCache =& LinkCache
::singleton();
1995 # Delete the old redirect. We don't save it to history since
1996 # by definition if we've got here it's rather uninteresting.
1997 # We have to remove it so that the next step doesn't trigger
1998 # a conflict on the unique namespace+title index...
1999 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2001 # Save a null revision in the page's history notifying of the move
2002 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2003 $nullRevId = $nullRevision->insertOn( $dbw );
2005 # Change the name of the target page:
2006 $dbw->update( 'page',
2008 'page_touched' => $dbw->timestamp($now),
2009 'page_namespace' => $nt->getNamespace(),
2010 'page_title' => $nt->getDBkey(),
2011 'page_latest' => $nullRevId,
2013 /* WHERE */ array( 'page_id' => $oldid ),
2016 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2018 # Recreate the redirect, this time in the other direction.
2019 $mwRedir = MagicWord
::get( 'redirect' );
2020 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2021 $redirectArticle = new Article( $this );
2022 $newid = $redirectArticle->insertOn( $dbw );
2023 $redirectRevision = new Revision( array(
2025 'comment' => $comment,
2026 'text' => $redirectText ) );
2027 $redirectRevision->insertOn( $dbw );
2028 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2029 $linkCache->clearLink( $this->getPrefixedDBkey() );
2032 $log = new LogPage( 'move' );
2033 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2035 # Now, we record the link from the redirect to the new title.
2036 # It should have no other outgoing links...
2037 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2038 $dbw->insert( 'pagelinks',
2040 'pl_from' => $newid,
2041 'pl_namespace' => $nt->getNamespace(),
2042 'pl_title' => $nt->getDbKey() ),
2046 if ( $wgUseSquid ) {
2047 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2048 $u = new SquidUpdate( $urls );
2054 * Move page to non-existing title.
2055 * @param Title &$nt the new Title
2058 function moveToNewTitle( &$nt, $reason = '' ) {
2060 $fname = 'MovePageForm::moveToNewTitle';
2061 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2063 $comment .= ": $reason";
2066 $newid = $nt->getArticleID();
2067 $oldid = $this->getArticleID();
2068 $dbw =& wfGetDB( DB_MASTER
);
2069 $now = $dbw->timestamp();
2070 $linkCache =& LinkCache
::singleton();
2072 # Save a null revision in the page's history notifying of the move
2073 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2074 $nullRevId = $nullRevision->insertOn( $dbw );
2077 $dbw->update( 'page',
2079 'page_touched' => $now,
2080 'page_namespace' => $nt->getNamespace(),
2081 'page_title' => $nt->getDBkey(),
2082 'page_latest' => $nullRevId,
2084 /* WHERE */ array( 'page_id' => $oldid ),
2088 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2091 $mwRedir = MagicWord
::get( 'redirect' );
2092 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2093 $redirectArticle = new Article( $this );
2094 $newid = $redirectArticle->insertOn( $dbw );
2095 $redirectRevision = new Revision( array(
2097 'comment' => $comment,
2098 'text' => $redirectText ) );
2099 $redirectRevision->insertOn( $dbw );
2100 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2101 $linkCache->clearLink( $this->getPrefixedDBkey() );
2104 $log = new LogPage( 'move' );
2105 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2107 # Purge caches as per article creation
2108 Article
::onArticleCreate( $nt );
2110 # Record the just-created redirect's linking to the page
2111 $dbw->insert( 'pagelinks',
2113 'pl_from' => $newid,
2114 'pl_namespace' => $nt->getNamespace(),
2115 'pl_title' => $nt->getDBkey() ),
2118 # Purge old title from squid
2119 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2120 $this->purgeSquid();
2124 * Checks if $this can be moved to a given Title
2125 * - Selects for update, so don't call it unless you mean business
2127 * @param Title &$nt the new title to check
2130 function isValidMoveTarget( $nt ) {
2132 $fname = 'Title::isValidMoveTarget';
2133 $dbw =& wfGetDB( DB_MASTER
);
2136 $id = $nt->getArticleID();
2137 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2138 array( 'page_is_redirect','old_text','old_flags' ),
2139 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2140 $fname, 'FOR UPDATE' );
2142 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2144 wfDebug( __METHOD__
. ": not a redirect\n" );
2147 $text = Revision
::getRevisionText( $obj );
2149 # Does the redirect point to the source?
2150 # Or is it a broken self-redirect, usually caused by namespace collisions?
2152 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2153 $redirTitle = Title
::newFromText( $m[1] );
2154 if( !is_object( $redirTitle ) ||
2155 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2156 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2157 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2162 wfDebug( __METHOD__
. ": failsafe\n" );
2166 # Does the article have a history?
2167 $row = $dbw->selectRow( array( 'page', 'revision'),
2169 array( 'page_namespace' => $nt->getNamespace(),
2170 'page_title' => $nt->getDBkey(),
2171 'page_id=rev_page AND page_latest != rev_id'
2172 ), $fname, 'FOR UPDATE'
2175 # Return true if there was no history
2176 return $row === false;
2180 * Create a redirect; fails if the title already exists; does
2183 * @param Title $dest the destination of the redirect
2184 * @param string $comment the comment string describing the move
2185 * @return bool true on success
2188 function createRedirect( $dest, $comment ) {
2189 if ( $this->getArticleID() ) {
2193 $fname = 'Title::createRedirect';
2194 $dbw =& wfGetDB( DB_MASTER
);
2196 $article = new Article( $this );
2197 $newid = $article->insertOn( $dbw );
2198 $revision = new Revision( array(
2200 'comment' => $comment,
2201 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2203 $revision->insertOn( $dbw );
2204 $article->updateRevisionOn( $dbw, $revision, 0 );
2207 $dbw->insert( 'pagelinks',
2209 'pl_from' => $newid,
2210 'pl_namespace' => $dest->getNamespace(),
2211 'pl_title' => $dest->getDbKey()
2215 Article
::onArticleCreate( $this );
2220 * Get categories to which this Title belongs and return an array of
2221 * categories' names.
2223 * @return array an array of parents in the form:
2224 * $parent => $currentarticle
2227 function getParentCategories() {
2230 $titlekey = $this->getArticleId();
2231 $dbr =& wfGetDB( DB_SLAVE
);
2232 $categorylinks = $dbr->tableName( 'categorylinks' );
2235 $sql = "SELECT * FROM $categorylinks"
2236 ." WHERE cl_from='$titlekey'"
2237 ." AND cl_from <> '0'"
2238 ." ORDER BY cl_sortkey";
2240 $res = $dbr->query ( $sql ) ;
2242 if($dbr->numRows($res) > 0) {
2243 while ( $x = $dbr->fetchObject ( $res ) )
2244 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2245 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2246 $dbr->freeResult ( $res ) ;
2254 * Get a tree of parent categories
2255 * @param array $children an array with the children in the keys, to check for circular refs
2259 function getParentCategoryTree( $children = array() ) {
2260 $parents = $this->getParentCategories();
2262 if($parents != '') {
2263 foreach($parents as $parent => $current) {
2264 if ( array_key_exists( $parent, $children ) ) {
2265 # Circular reference
2266 $stack[$parent] = array();
2268 $nt = Title
::newFromText($parent);
2270 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2282 * Get an associative array for selecting this title from
2288 function pageCond() {
2289 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2293 * Get the revision ID of the previous revision
2295 * @param integer $revision Revision ID. Get the revision that was before this one.
2296 * @return integer $oldrevision|false
2298 function getPreviousRevisionID( $revision ) {
2299 $dbr =& wfGetDB( DB_SLAVE
);
2300 return $dbr->selectField( 'revision', 'rev_id',
2301 'rev_page=' . intval( $this->getArticleId() ) .
2302 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2306 * Get the revision ID of the next revision
2308 * @param integer $revision Revision ID. Get the revision that was after this one.
2309 * @return integer $oldrevision|false
2311 function getNextRevisionID( $revision ) {
2312 $dbr =& wfGetDB( DB_SLAVE
);
2313 return $dbr->selectField( 'revision', 'rev_id',
2314 'rev_page=' . intval( $this->getArticleId() ) .
2315 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2319 * Get the number of revisions between the given revision IDs.
2321 * @param integer $old Revision ID.
2322 * @param integer $new Revision ID.
2323 * @return integer Number of revisions between these IDs.
2325 function countRevisionsBetween( $old, $new ) {
2326 $dbr =& wfGetDB( DB_SLAVE
);
2327 return $dbr->selectField( 'revision', 'count(*)',
2328 'rev_page = ' . intval( $this->getArticleId() ) .
2329 ' AND rev_id > ' . intval( $old ) .
2330 ' AND rev_id < ' . intval( $new ) );
2334 * Compare with another title.
2336 * @param Title $title
2339 function equals( $title ) {
2340 // Note: === is necessary for proper matching of number-like titles.
2341 return $this->getInterwiki() === $title->getInterwiki()
2342 && $this->getNamespace() == $title->getNamespace()
2343 && $this->getDbkey() === $title->getDbkey();
2347 * Check if page exists
2351 return $this->getArticleId() != 0;
2355 * Should a link should be displayed as a known link, just based on its title?
2357 * Currently, a self-link with a fragment and special pages are in
2358 * this category. Special pages never exist in the database.
2360 function isAlwaysKnown() {
2361 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2362 || NS_SPECIAL
== $this->mNamespace
;
2366 * Update page_touched timestamps and send squid purge messages for
2367 * pages linking to this title. May be sent to the job queue depending
2368 * on the number of links. Typically called on create and delete.
2370 function touchLinks() {
2371 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2374 if ( $this->getNamespace() == NS_CATEGORY
) {
2375 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2381 * Get the last touched timestamp
2383 function getTouched() {
2384 $dbr =& wfGetDB( DB_SLAVE
);
2385 $touched = $dbr->selectField( 'page', 'page_touched',
2387 'page_namespace' => $this->getNamespace(),
2388 'page_title' => $this->getDBkey()
2395 * Get a cached value from a global cache that is invalidated when this page changes
2396 * @param string $key the key
2397 * @param callback $callback A callback function which generates the value on cache miss
2399 * @deprecated use DependencyWrapper
2401 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2402 return DependencyWrapper
::getValueFromCache( $memc, $key, $expiry, $callback,
2403 $params, new TitleDependency( $this ) );
2406 function trackbackURL() {
2407 global $wgTitle, $wgScriptPath, $wgServer;
2409 return "$wgServer$wgScriptPath/trackback.php?article="
2410 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2413 function trackbackRDF() {
2414 $url = htmlspecialchars($this->getFullURL());
2415 $title = htmlspecialchars($this->getText());
2416 $tburl = $this->trackbackURL();
2419 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2420 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2421 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2424 dc:identifier=\"$url\"
2426 trackback:ping=\"$tburl\" />
2431 * Generate strings used for xml 'id' names in monobook tabs
2434 function getNamespaceKey() {
2436 switch ($this->getNamespace()) {
2439 return 'nstab-main';
2442 return 'nstab-user';
2444 return 'nstab-media';
2446 return 'nstab-special';
2448 case NS_PROJECT_TALK
:
2449 return 'nstab-project';
2452 return 'nstab-image';
2454 case NS_MEDIAWIKI_TALK
:
2455 return 'nstab-mediawiki';
2457 case NS_TEMPLATE_TALK
:
2458 return 'nstab-template';
2461 return 'nstab-help';
2463 case NS_CATEGORY_TALK
:
2464 return 'nstab-category';
2466 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2471 * Returns true if this title resolves to the named special page
2472 * @param string $name The special page name
2475 function isSpecial( $name ) {
2476 if ( $this->getNamespace() == NS_SPECIAL
) {
2477 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2478 if ( $name == $thisName ) {
2486 * If the Title refers to a special page alias which is not the local default,
2487 * returns a new Title which points to the local default. Otherwise, returns $this.
2489 function fixSpecialName() {
2490 if ( $this->getNamespace() == NS_SPECIAL
) {
2491 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2492 if ( $canonicalName ) {
2493 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2494 if ( $localName != $this->mDbkeyform
) {
2495 return Title
::makeTitle( NS_SPECIAL
, $localName );
2503 * Is this Title in a namespace which contains content?
2504 * In other words, is this a content page, for the purposes of calculating
2509 public function isContentPage() {
2510 return Namespace::isContent( $this->getNamespace() );