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 * Determine whether a Title is a redirect
519 public function isRedirect() {
520 $article = new Article( $this );
521 return $article->isRedirect();
525 * Update the page_touched field for an array of title objects
526 * @todo Inefficient unless the IDs are already loaded into the
528 * @param array $titles an array of Title objects to be touched
529 * @param string $timestamp the timestamp to use instead of the
530 * default current time
534 function touchArray( $titles, $timestamp = '' ) {
536 if ( count( $titles ) == 0 ) {
539 $dbw =& wfGetDB( DB_MASTER
);
540 if ( $timestamp == '' ) {
541 $timestamp = $dbw->timestamp();
544 $page = $dbw->tableName( 'page' );
545 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
548 foreach ( $titles as $title ) {
549 if ( $wgUseFileCache ) {
550 $cm = new HTMLFileCache($title);
551 @unlink($cm->fileCacheName());
558 $sql .= $title->getArticleID();
562 $dbw->query( $sql, 'Title::touchArray' );
565 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
566 // do them in small chunks:
567 $fname = 'Title::touchArray';
568 foreach( $titles as $title ) {
569 $dbw->update( 'page',
570 array( 'page_touched' => $timestamp ),
572 'page_namespace' => $title->getNamespace(),
573 'page_title' => $title->getDBkey() ),
579 * Escape a text fragment, say from a link, for a URL
581 static function escapeFragmentForURL( $fragment ) {
582 $fragment = str_replace( ' ', '_', $fragment );
583 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
584 $replaceArray = array(
588 return strtr( $fragment, $replaceArray );
591 #----------------------------------------------------------------------------
593 #----------------------------------------------------------------------------
595 /** Simple accessors */
597 * Get the text form (spaces not underscores) of the main part
601 function getText() { return $this->mTextform
; }
603 * Get the URL-encoded form of the main part
607 function getPartialURL() { return $this->mUrlform
; }
609 * Get the main part with underscores
613 function getDBkey() { return $this->mDbkeyform
; }
615 * Get the namespace index, i.e. one of the NS_xxxx constants
619 function getNamespace() { return $this->mNamespace
; }
621 * Get the namespace text
625 function getNsText() {
626 global $wgContLang, $wgCanonicalNamespaceNames;
628 if ( '' != $this->mInterwiki
) {
629 // This probably shouldn't even happen. ohh man, oh yuck.
630 // But for interwiki transclusion it sometimes does.
631 // Shit. Shit shit shit.
633 // Use the canonical namespaces if possible to try to
634 // resolve a foreign namespace.
635 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
636 return $wgCanonicalNamespaceNames[$this->mNamespace
];
639 return $wgContLang->getNsText( $this->mNamespace
);
642 * Get the namespace text of the subject (rather than talk) page
646 function getSubjectNsText() {
648 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
652 * Get the namespace text of the talk page
655 function getTalkNsText() {
657 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
661 * Could this title have a corresponding talk page?
665 return( Namespace::canTalk( $this->mNamespace
) );
669 * Get the interwiki prefix (or null string)
673 function getInterwiki() { return $this->mInterwiki
; }
675 * Get the Title fragment (i.e. the bit after the #) in text form
679 function getFragment() { return $this->mFragment
; }
681 * Get the fragment in URL form, including the "#" character if there is one
686 function getFragmentForURL() {
687 if ( $this->mFragment
== '' ) {
690 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
694 * Get the default namespace index, for when there is no namespace
698 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
701 * Get title for search index
702 * @return string a stripped-down title string ready for the
705 function getIndexTitle() {
706 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
710 * Get the prefixed database key form
711 * @return string the prefixed title, with underscores and
712 * any interwiki and namespace prefixes
715 function getPrefixedDBkey() {
716 $s = $this->prefix( $this->mDbkeyform
);
717 $s = str_replace( ' ', '_', $s );
722 * Get the prefixed title with spaces.
723 * This is the form usually used for display
724 * @return string the prefixed title, with spaces
727 function getPrefixedText() {
728 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
729 $s = $this->prefix( $this->mTextform
);
730 $s = str_replace( '_', ' ', $s );
731 $this->mPrefixedText
= $s;
733 return $this->mPrefixedText
;
737 * Get the prefixed title with spaces, plus any fragment
738 * (part beginning with '#')
739 * @return string the prefixed title, with spaces and
740 * the fragment, including '#'
743 function getFullText() {
744 $text = $this->getPrefixedText();
745 if( '' != $this->mFragment
) {
746 $text .= '#' . $this->mFragment
;
752 * Get the base name, i.e. the leftmost parts before the /
753 * @return string Base name
755 function getBaseText() {
756 global $wgNamespacesWithSubpages;
757 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
758 $parts = explode( '/', $this->getText() );
759 # Don't discard the real title if there's no subpage involved
760 if( count( $parts ) > 1 )
761 unset( $parts[ count( $parts ) - 1 ] );
762 return implode( '/', $parts );
764 return $this->getText();
769 * Get the lowest-level subpage name, i.e. the rightmost part after /
770 * @return string Subpage name
772 function getSubpageText() {
773 global $wgNamespacesWithSubpages;
774 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
775 $parts = explode( '/', $this->mTextform
);
776 return( $parts[ count( $parts ) - 1 ] );
778 return( $this->mTextform
);
783 * Get a URL-encoded form of the subpage text
784 * @return string URL-encoded subpage name
786 function getSubpageUrlForm() {
787 $text = $this->getSubpageText();
788 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
789 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
794 * Get a URL-encoded title (not an actual URL) including interwiki
795 * @return string the URL-encoded form
798 function getPrefixedURL() {
799 $s = $this->prefix( $this->mDbkeyform
);
800 $s = str_replace( ' ', '_', $s );
802 $s = wfUrlencode ( $s ) ;
804 # Cleaning up URL to make it look nice -- is this safe?
805 $s = str_replace( '%28', '(', $s );
806 $s = str_replace( '%29', ')', $s );
812 * Get a real URL referring to this title, with interwiki link and
815 * @param string $query an optional query string, not used
816 * for interwiki links
817 * @param string $variant language variant of url (for sr, zh..)
818 * @return string the URL
821 function getFullURL( $query = '', $variant = false ) {
822 global $wgContLang, $wgServer, $wgRequest;
824 if ( '' == $this->mInterwiki
) {
825 $url = $this->getLocalUrl( $query, $variant );
827 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
828 // Correct fix would be to move the prepending elsewhere.
829 if ($wgRequest->getVal('action') != 'render') {
830 $url = $wgServer . $url;
833 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
835 $namespace = wfUrlencode( $this->getNsText() );
836 if ( '' != $namespace ) {
837 # Can this actually happen? Interwikis shouldn't be parsed.
838 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
841 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
843 if( false === strpos( $url, '?' ) ) {
852 # Finally, add the fragment.
853 $url .= $this->getFragmentForURL();
855 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
860 * Get a URL with no fragment or server name. If this page is generated
861 * with action=render, $wgServer is prepended.
862 * @param string $query an optional query string; if not specified,
863 * $wgArticlePath will be used.
864 * @param string $variant language variant of url (for sr, zh..)
865 * @return string the URL
868 function getLocalURL( $query = '', $variant = false ) {
869 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
870 global $wgVariantArticlePath, $wgContLang, $wgUser;
872 // internal links should point to same variant as current page (only anonymous users)
873 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
874 $pref = $wgContLang->getPreferredVariant(false);
875 if($pref != $wgContLang->getCode())
879 if ( $this->isExternal() ) {
880 $url = $this->getFullURL();
882 // This is currently only used for edit section links in the
883 // context of interwiki transclusion. In theory we should
884 // append the query to the end of any existing query string,
885 // but interwiki transclusion is already broken in that case.
889 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
890 if ( $query == '' ) {
891 if($variant!=false && $wgContLang->hasVariants()){
892 if($wgVariantArticlePath==false)
893 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
895 $variantArticlePath = $wgVariantArticlePath;
897 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
898 $url = str_replace( '$1', $dbkey, $url );
902 $url = str_replace( '$1', $dbkey, $wgArticlePath );
904 global $wgActionPaths;
907 if( !empty( $wgActionPaths ) &&
908 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
910 $action = urldecode( $matches[2] );
911 if( isset( $wgActionPaths[$action] ) ) {
912 $query = $matches[1];
913 if( isset( $matches[4] ) ) $query .= $matches[4];
914 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
915 if( $query != '' ) $url .= '?' . $query;
918 if ( $url === false ) {
919 if ( $query == '-' ) {
922 $url = "{$wgScript}?title={$dbkey}&{$query}";
926 // FIXME: this causes breakage in various places when we
927 // actually expected a local URL and end up with dupe prefixes.
928 if ($wgRequest->getVal('action') == 'render') {
929 $url = $wgServer . $url;
932 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
937 * Get an HTML-escaped version of the URL form, suitable for
938 * using in a link, without a server name or fragment
939 * @param string $query an optional query string
940 * @return string the URL
943 function escapeLocalURL( $query = '' ) {
944 return htmlspecialchars( $this->getLocalURL( $query ) );
948 * Get an HTML-escaped version of the URL form, suitable for
949 * using in a link, including the server name and fragment
951 * @return string the URL
952 * @param string $query an optional query string
955 function escapeFullURL( $query = '' ) {
956 return htmlspecialchars( $this->getFullURL( $query ) );
960 * Get the URL form for an internal link.
961 * - Used in various Squid-related code, in case we have a different
962 * internal hostname for the server from the exposed one.
964 * @param string $query an optional query string
965 * @param string $variant language variant of url (for sr, zh..)
966 * @return string the URL
969 function getInternalURL( $query = '', $variant = false ) {
970 global $wgInternalServer;
971 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
972 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
977 * Get the edit URL for this Title
978 * @return string the URL, or a null string if this is an
982 function getEditURL() {
983 if ( '' != $this->mInterwiki
) { return ''; }
984 $s = $this->getLocalURL( 'action=edit' );
990 * Get the HTML-escaped displayable text form.
991 * Used for the title field in <a> tags.
992 * @return string the text, including any prefixes
995 function getEscapedText() {
996 return htmlspecialchars( $this->getPrefixedText() );
1000 * Is this Title interwiki?
1004 function isExternal() { return ( '' != $this->mInterwiki
); }
1007 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1009 * @param string Action to check (default: edit)
1012 function isSemiProtected( $action = 'edit' ) {
1013 if( $this->exists() ) {
1014 $restrictions = $this->getRestrictions( $action );
1015 if( count( $restrictions ) > 0 ) {
1016 foreach( $restrictions as $restriction ) {
1017 if( strtolower( $restriction ) != 'autoconfirmed' )
1026 # If it doesn't exist, it can't be protected
1032 * Does the title correspond to a protected article?
1033 * @param string $what the action the page is protected from,
1034 * by default checks move and edit
1038 function isProtected( $action = '' ) {
1039 global $wgRestrictionLevels;
1040 if ( NS_SPECIAL
== $this->mNamespace
) { return true; }
1042 if( $action == 'edit' ||
$action == '' ) {
1043 $r = $this->getRestrictions( 'edit' );
1044 foreach( $wgRestrictionLevels as $level ) {
1045 if( in_array( $level, $r ) && $level != '' ) {
1051 if( $action == 'move' ||
$action == '' ) {
1052 $r = $this->getRestrictions( 'move' );
1053 foreach( $wgRestrictionLevels as $level ) {
1054 if( in_array( $level, $r ) && $level != '' ) {
1064 * Is $wgUser is watching this page?
1068 function userIsWatching() {
1071 if ( is_null( $this->mWatched
) ) {
1072 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1073 $this->mWatched
= false;
1075 $this->mWatched
= $wgUser->isWatched( $this );
1078 return $this->mWatched
;
1082 * Can $wgUser perform $action this page?
1083 * @param string $action action that permission needs to be checked for
1087 function userCan($action) {
1088 $fname = 'Title::userCan';
1089 wfProfileIn( $fname );
1094 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1095 if ( $result !== null ) {
1096 wfProfileOut( $fname );
1100 if( NS_SPECIAL
== $this->mNamespace
) {
1101 wfProfileOut( $fname );
1104 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1105 // from taking effect -ævar
1106 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1107 !$wgUser->isAllowed('editinterface') ) {
1108 wfProfileOut( $fname );
1112 if( $this->mDbkeyform
== '_' ) {
1113 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1114 wfProfileOut( $fname );
1118 # protect css/js subpages of user pages
1119 # XXX: this might be better using restrictions
1120 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1121 if( $this->isCssJsSubpage()
1122 && !$wgUser->isAllowed('editinterface')
1123 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1124 wfProfileOut( $fname );
1128 foreach( $this->getRestrictions($action) as $right ) {
1129 // Backwards compatibility, rewrite sysop -> protect
1130 if ( $right == 'sysop' ) {
1133 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1134 wfProfileOut( $fname );
1139 if( $action == 'move' &&
1140 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1141 wfProfileOut( $fname );
1145 if( $action == 'create' ) {
1146 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1147 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1148 wfProfileOut( $fname );
1153 wfProfileOut( $fname );
1158 * Can $wgUser edit this page?
1162 function userCanEdit() {
1163 return $this->userCan('edit');
1167 * Can $wgUser create this page?
1171 function userCanCreate() {
1172 return $this->userCan('create');
1176 * Can $wgUser move this page?
1180 function userCanMove() {
1181 return $this->userCan('move');
1185 * Would anybody with sufficient privileges be able to move this page?
1186 * Some pages just aren't movable.
1191 function isMovable() {
1192 return Namespace::isMovable( $this->getNamespace() )
1193 && $this->getInterwiki() == '';
1197 * Can $wgUser read this page?
1201 function userCanRead() {
1205 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1206 if ( $result !== null ) {
1210 if( $wgUser->isAllowed('read') ) {
1213 global $wgWhitelistRead;
1216 * Always grant access to the login page.
1217 * Even anons need to be able to log in.
1219 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1223 /** some pages are explicitly allowed */
1224 $name = $this->getPrefixedText();
1225 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1229 # Compatibility with old settings
1230 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1231 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1240 * Is this a talk page of some sort?
1244 function isTalkPage() {
1245 return Namespace::isTalk( $this->getNamespace() );
1249 * Is this a subpage?
1253 function isSubpage() {
1254 global $wgNamespacesWithSubpages;
1256 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1257 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1264 * Is this a .css or .js subpage of a user page?
1268 function isCssJsSubpage() {
1269 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform
) );
1272 * Is this a *valid* .css or .js subpage of a user page?
1273 * Check that the corresponding skin exists
1275 function isValidCssJsSubpage() {
1276 if ( $this->isCssJsSubpage() ) {
1277 $skinNames = Skin
::getSkinNames();
1278 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1284 * Trim down a .css or .js subpage title to get the corresponding skin name
1286 function getSkinFromCssJsSubpage() {
1287 $subpage = explode( '/', $this->mTextform
);
1288 $subpage = $subpage[ count( $subpage ) - 1 ];
1289 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1292 * Is this a .css subpage of a user page?
1296 function isCssSubpage() {
1297 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1300 * Is this a .js subpage of a user page?
1304 function isJsSubpage() {
1305 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1308 * Protect css/js subpages of user pages: can $wgUser edit
1312 * @todo XXX: this might be better using restrictions
1315 function userCanEditCssJsSubpage() {
1317 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1321 * Loads a string into mRestrictions array
1322 * @param string $res restrictions in string format
1325 function loadRestrictions( $res ) {
1326 $this->mRestrictions
['edit'] = array();
1327 $this->mRestrictions
['move'] = array();
1330 # No restrictions (page_restrictions blank)
1331 $this->mRestrictionsLoaded
= true;
1335 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1336 $temp = explode( '=', trim( $restrict ) );
1337 if(count($temp) == 1) {
1338 // old format should be treated as edit/move restriction
1339 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1340 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1342 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1345 $this->mRestrictionsLoaded
= true;
1349 * Accessor/initialisation for mRestrictions
1352 * @param string $action action that permission needs to be checked for
1353 * @return array the array of groups allowed to edit this article
1355 function getRestrictions( $action ) {
1356 if( $this->exists() ) {
1357 if( !$this->mRestrictionsLoaded
) {
1358 $dbr =& wfGetDB( DB_SLAVE
);
1359 $res = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ) );
1360 $this->loadRestrictions( $res );
1362 return isset( $this->mRestrictions
[$action] )
1363 ?
$this->mRestrictions
[$action]
1371 * Is there a version of this page in the deletion archive?
1372 * @return int the number of archived revisions
1375 function isDeleted() {
1376 $fname = 'Title::isDeleted';
1377 if ( $this->getNamespace() < 0 ) {
1380 $dbr =& wfGetDB( DB_SLAVE
);
1381 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1382 'ar_title' => $this->getDBkey() ), $fname );
1383 if( $this->getNamespace() == NS_IMAGE
) {
1384 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1385 array( 'fa_name' => $this->getDBkey() ), $fname );
1392 * Get the article ID for this Title from the link cache,
1393 * adding it if necessary
1394 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1396 * @return int the ID
1398 public function getArticleID( $flags = 0 ) {
1399 $linkCache =& LinkCache
::singleton();
1400 if ( $flags & GAID_FOR_UPDATE
) {
1401 $oldUpdate = $linkCache->forUpdate( true );
1402 $this->mArticleID
= $linkCache->addLinkObj( $this );
1403 $linkCache->forUpdate( $oldUpdate );
1405 if ( -1 == $this->mArticleID
) {
1406 $this->mArticleID
= $linkCache->addLinkObj( $this );
1409 return $this->mArticleID
;
1413 * Return the associated Article object.
1417 public function getArticle() {
1418 return new Article( $this );
1421 function getLatestRevID() {
1422 if ($this->mLatestID
!== false)
1423 return $this->mLatestID
;
1425 $db =& wfGetDB(DB_SLAVE
);
1426 return $this->mLatestID
= $db->selectField( 'revision',
1428 array('rev_page' => $this->getArticleID()),
1429 'Title::getLatestRevID' );
1433 * This clears some fields in this object, and clears any associated
1434 * keys in the "bad links" section of the link cache.
1436 * - This is called from Article::insertNewArticle() to allow
1437 * loading of the new page_id. It's also called from
1438 * Article::doDeleteArticle()
1440 * @param int $newid the new Article ID
1443 function resetArticleID( $newid ) {
1444 $linkCache =& LinkCache
::singleton();
1445 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1447 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1448 else { $this->mArticleID
= $newid; }
1449 $this->mRestrictionsLoaded
= false;
1450 $this->mRestrictions
= array();
1454 * Updates page_touched for this page; called from LinksUpdate.php
1455 * @return bool true if the update succeded
1458 function invalidateCache() {
1459 global $wgUseFileCache;
1461 if ( wfReadOnly() ) {
1465 $dbw =& wfGetDB( DB_MASTER
);
1466 $success = $dbw->update( 'page',
1468 'page_touched' => $dbw->timestamp()
1469 ), array( /* WHERE */
1470 'page_namespace' => $this->getNamespace() ,
1471 'page_title' => $this->getDBkey()
1472 ), 'Title::invalidateCache'
1475 if ($wgUseFileCache) {
1476 $cache = new HTMLFileCache($this);
1477 @unlink
($cache->fileCacheName());
1484 * Prefix some arbitrary text with the namespace or interwiki prefix
1487 * @param string $name the text
1488 * @return string the prefixed text
1491 /* private */ function prefix( $name ) {
1493 if ( '' != $this->mInterwiki
) {
1494 $p = $this->mInterwiki
. ':';
1496 if ( 0 != $this->mNamespace
) {
1497 $p .= $this->getNsText() . ':';
1503 * Secure and split - main initialisation function for this object
1505 * Assumes that mDbkeyform has been set, and is urldecoded
1506 * and uses underscores, but not otherwise munged. This function
1507 * removes illegal characters, splits off the interwiki and
1508 * namespace prefixes, sets the other forms, and canonicalizes
1510 * @return bool true on success
1513 /* private */ function secureAndSplit() {
1514 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1517 static $rxTc = false;
1519 # % is needed as well
1520 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1523 $this->mInterwiki
= $this->mFragment
= '';
1524 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1526 $dbkey = $this->mDbkeyform
;
1528 # Strip Unicode bidi override characters.
1529 # Sometimes they slip into cut-n-pasted page titles, where the
1530 # override chars get included in list displays.
1531 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1532 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1534 # Clean up whitespace
1536 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1537 $dbkey = trim( $dbkey, '_' );
1539 if ( '' == $dbkey ) {
1543 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1544 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1548 $this->mDbkeyform
= $dbkey;
1550 # Initial colon indicates main namespace rather than specified default
1551 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1552 if ( ':' == $dbkey{0} ) {
1553 $this->mNamespace
= NS_MAIN
;
1554 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1557 # Namespace or interwiki prefix
1561 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1563 $lowerNs = $wgContLang->lc( $p );
1564 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1565 # Canonical namespace
1567 $this->mNamespace
= $ns;
1568 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1569 # Ordinary namespace
1571 $this->mNamespace
= $ns;
1572 } elseif( $this->getInterwikiLink( $p ) ) {
1574 # Can't make a local interwiki link to an interwiki link.
1575 # That's just crazy!
1581 $this->mInterwiki
= $wgContLang->lc( $p );
1583 # Redundant interwiki prefix to the local wiki
1584 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1585 if( $dbkey == '' ) {
1586 # Can't have an empty self-link
1589 $this->mInterwiki
= '';
1591 # Do another namespace split...
1595 # If there's an initial colon after the interwiki, that also
1596 # resets the default namespace
1597 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1598 $this->mNamespace
= NS_MAIN
;
1599 $dbkey = substr( $dbkey, 1 );
1602 # If there's no recognized interwiki or namespace,
1603 # then let the colon expression be part of the title.
1608 # We already know that some pages won't be in the database!
1610 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1611 $this->mArticleID
= 0;
1613 $fragment = strstr( $dbkey, '#' );
1614 if ( false !== $fragment ) {
1615 $this->setFragment( $fragment );
1616 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1617 # remove whitespace again: prevents "Foo_bar_#"
1618 # becoming "Foo_bar_"
1619 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1622 # Reject illegal characters.
1624 if( preg_match( $rxTc, $dbkey ) ) {
1629 * Pages with "/./" or "/../" appearing in the URLs will
1630 * often be unreachable due to the way web browsers deal
1631 * with 'relative' URLs. Forbid them explicitly.
1633 if ( strpos( $dbkey, '.' ) !== false &&
1634 ( $dbkey === '.' ||
$dbkey === '..' ||
1635 strpos( $dbkey, './' ) === 0 ||
1636 strpos( $dbkey, '../' ) === 0 ||
1637 strpos( $dbkey, '/./' ) !== false ||
1638 strpos( $dbkey, '/../' ) !== false ) )
1644 * Limit the size of titles to 255 bytes.
1645 * This is typically the size of the underlying database field.
1646 * We make an exception for special pages, which don't need to be stored
1647 * in the database, and may edge over 255 bytes due to subpage syntax
1648 * for long titles, e.g. [[Special:Block/Long name]]
1650 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1651 strlen( $dbkey ) > 512 )
1657 * Normally, all wiki links are forced to have
1658 * an initial capital letter so [[foo]] and [[Foo]]
1659 * point to the same place.
1661 * Don't force it for interwikis, since the other
1662 * site might be case-sensitive.
1664 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1665 $dbkey = $wgContLang->ucfirst( $dbkey );
1669 * Can't make a link to a namespace alone...
1670 * "empty" local links can only be self-links
1671 * with a fragment identifier.
1674 $this->mInterwiki
== '' &&
1675 $this->mNamespace
!= NS_MAIN
) {
1679 // Any remaining initial :s are illegal.
1680 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1685 $this->mDbkeyform
= $dbkey;
1686 $this->mUrlform
= wfUrlencode( $dbkey );
1688 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1694 * Set the fragment for this title
1695 * This is kind of bad, since except for this rarely-used function, Title objects
1696 * are immutable. The reason this is here is because it's better than setting the
1697 * members directly, which is what Linker::formatComment was doing previously.
1699 * @param string $fragment text
1700 * @access kind of public
1702 function setFragment( $fragment ) {
1703 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1707 * Get a Title object associated with the talk page of this article
1708 * @return Title the object for the talk page
1711 function getTalkPage() {
1712 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1716 * Get a title object associated with the subject page of this
1719 * @return Title the object for the subject page
1722 function getSubjectPage() {
1723 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1727 * Get an array of Title objects linking to this Title
1728 * Also stores the IDs in the link cache.
1730 * WARNING: do not use this function on arbitrary user-supplied titles!
1731 * On heavily-used templates it will max out the memory.
1733 * @param string $options may be FOR UPDATE
1734 * @return array the Title objects linking here
1737 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1738 $linkCache =& LinkCache
::singleton();
1741 $db =& wfGetDB( DB_MASTER
);
1743 $db =& wfGetDB( DB_SLAVE
);
1746 $res = $db->select( array( 'page', $table ),
1747 array( 'page_namespace', 'page_title', 'page_id' ),
1749 "{$prefix}_from=page_id",
1750 "{$prefix}_namespace" => $this->getNamespace(),
1751 "{$prefix}_title" => $this->getDbKey() ),
1752 'Title::getLinksTo',
1756 if ( $db->numRows( $res ) ) {
1757 while ( $row = $db->fetchObject( $res ) ) {
1758 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1759 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1760 $retVal[] = $titleObj;
1764 $db->freeResult( $res );
1769 * Get an array of Title objects using this Title as a template
1770 * Also stores the IDs in the link cache.
1772 * WARNING: do not use this function on arbitrary user-supplied titles!
1773 * On heavily-used templates it will max out the memory.
1775 * @param string $options may be FOR UPDATE
1776 * @return array the Title objects linking here
1779 function getTemplateLinksTo( $options = '' ) {
1780 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1784 * Get an array of Title objects referring to non-existent articles linked from this page
1786 * @param string $options may be FOR UPDATE
1787 * @return array the Title objects
1790 function getBrokenLinksFrom( $options = '' ) {
1792 $db =& wfGetDB( DB_MASTER
);
1794 $db =& wfGetDB( DB_SLAVE
);
1797 $res = $db->safeQuery(
1798 "SELECT pl_namespace, pl_title
1801 ON pl_namespace=page_namespace
1802 AND pl_title=page_title
1804 AND page_namespace IS NULL
1806 $db->tableName( 'pagelinks' ),
1807 $db->tableName( 'page' ),
1808 $this->getArticleId(),
1812 if ( $db->numRows( $res ) ) {
1813 while ( $row = $db->fetchObject( $res ) ) {
1814 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1817 $db->freeResult( $res );
1823 * Get a list of URLs to purge from the Squid cache when this
1826 * @return array the URLs
1829 function getSquidURLs() {
1833 $this->getInternalURL(),
1834 $this->getInternalURL( 'action=history' )
1837 // purge variant urls as well
1838 if($wgContLang->hasVariants()){
1839 $variants = $wgContLang->getVariants();
1840 foreach($variants as $vCode){
1841 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1842 $urls[] = $this->getInternalURL('',$vCode);
1849 function purgeSquid() {
1851 if ( $wgUseSquid ) {
1852 $urls = $this->getSquidURLs();
1853 $u = new SquidUpdate( $urls );
1859 * Move this page without authentication
1860 * @param Title &$nt the new page Title
1863 function moveNoAuth( &$nt ) {
1864 return $this->moveTo( $nt, false );
1868 * Check whether a given move operation would be valid.
1869 * Returns true if ok, or a message key string for an error message
1870 * if invalid. (Scarrrrry ugly interface this.)
1871 * @param Title &$nt the new title
1872 * @param bool $auth indicates whether $wgUser's permissions
1874 * @return mixed true on success, message name on failure
1877 function isValidMoveOperation( &$nt, $auth = true ) {
1878 if( !$this or !$nt ) {
1879 return 'badtitletext';
1881 if( $this->equals( $nt ) ) {
1884 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1885 return 'immobile_namespace';
1888 $oldid = $this->getArticleID();
1889 $newid = $nt->getArticleID();
1891 if ( strlen( $nt->getDBkey() ) < 1 ) {
1892 return 'articleexists';
1894 if ( ( '' == $this->getDBkey() ) ||
1896 ( '' == $nt->getDBkey() ) ) {
1897 return 'badarticleerror';
1901 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1902 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1903 return 'protectedpage';
1906 # The move is allowed only if (1) the target doesn't exist, or
1907 # (2) the target is a redirect to the source, and has no history
1908 # (so we can undo bad moves right after they're done).
1910 if ( 0 != $newid ) { # Target exists; check for validity
1911 if ( ! $this->isValidMoveTarget( $nt ) ) {
1912 return 'articleexists';
1919 * Move a title to a new location
1920 * @param Title &$nt the new title
1921 * @param bool $auth indicates whether $wgUser's permissions
1923 * @return mixed true on success, message name on failure
1926 function moveTo( &$nt, $auth = true, $reason = '' ) {
1927 $err = $this->isValidMoveOperation( $nt, $auth );
1928 if( is_string( $err ) ) {
1932 $pageid = $this->getArticleID();
1933 if( $nt->exists() ) {
1934 $this->moveOverExistingRedirect( $nt, $reason );
1935 $pageCountChange = 0;
1936 } else { # Target didn't exist, do normal move.
1937 $this->moveToNewTitle( $nt, $reason );
1938 $pageCountChange = 1;
1940 $redirid = $this->getArticleID();
1942 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1943 $dbw =& wfGetDB( DB_MASTER
);
1944 $categorylinks = $dbw->tableName( 'categorylinks' );
1945 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1946 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1947 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1948 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1952 $oldnamespace = $this->getNamespace() & ~
1;
1953 $newnamespace = $nt->getNamespace() & ~
1;
1954 $oldtitle = $this->getDBkey();
1955 $newtitle = $nt->getDBkey();
1957 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1958 WatchedItem
::duplicateEntries( $this, $nt );
1961 # Update search engine
1962 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1964 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1968 if( $this->isContentPage() && !$nt->isContentPage() ) {
1969 # No longer a content page
1970 # Not viewed, edited, removing
1971 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
1972 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
1973 # Now a content page
1974 # Not viewed, edited, adding
1975 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1976 } elseif( $pageCountChange ) {
1978 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1987 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1992 * Move page to a title which is at present a redirect to the
1995 * @param Title &$nt the page to move to, which should currently
1999 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2001 $fname = 'Title::moveOverExistingRedirect';
2002 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2005 $comment .= ": $reason";
2008 $now = wfTimestampNow();
2009 $newid = $nt->getArticleID();
2010 $oldid = $this->getArticleID();
2011 $dbw =& wfGetDB( DB_MASTER
);
2012 $linkCache =& LinkCache
::singleton();
2014 # Delete the old redirect. We don't save it to history since
2015 # by definition if we've got here it's rather uninteresting.
2016 # We have to remove it so that the next step doesn't trigger
2017 # a conflict on the unique namespace+title index...
2018 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2020 # Save a null revision in the page's history notifying of the move
2021 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2022 $nullRevId = $nullRevision->insertOn( $dbw );
2024 # Change the name of the target page:
2025 $dbw->update( 'page',
2027 'page_touched' => $dbw->timestamp($now),
2028 'page_namespace' => $nt->getNamespace(),
2029 'page_title' => $nt->getDBkey(),
2030 'page_latest' => $nullRevId,
2032 /* WHERE */ array( 'page_id' => $oldid ),
2035 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2037 # Recreate the redirect, this time in the other direction.
2038 $mwRedir = MagicWord
::get( 'redirect' );
2039 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2040 $redirectArticle = new Article( $this );
2041 $newid = $redirectArticle->insertOn( $dbw );
2042 $redirectRevision = new Revision( array(
2044 'comment' => $comment,
2045 'text' => $redirectText ) );
2046 $redirectRevision->insertOn( $dbw );
2047 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2048 $linkCache->clearLink( $this->getPrefixedDBkey() );
2051 $log = new LogPage( 'move' );
2052 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2054 # Now, we record the link from the redirect to the new title.
2055 # It should have no other outgoing links...
2056 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2057 $dbw->insert( 'pagelinks',
2059 'pl_from' => $newid,
2060 'pl_namespace' => $nt->getNamespace(),
2061 'pl_title' => $nt->getDbKey() ),
2065 if ( $wgUseSquid ) {
2066 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2067 $u = new SquidUpdate( $urls );
2073 * Move page to non-existing title.
2074 * @param Title &$nt the new Title
2077 function moveToNewTitle( &$nt, $reason = '' ) {
2079 $fname = 'MovePageForm::moveToNewTitle';
2080 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2082 $comment .= ": $reason";
2085 $newid = $nt->getArticleID();
2086 $oldid = $this->getArticleID();
2087 $dbw =& wfGetDB( DB_MASTER
);
2088 $now = $dbw->timestamp();
2089 $linkCache =& LinkCache
::singleton();
2091 # Save a null revision in the page's history notifying of the move
2092 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2093 $nullRevId = $nullRevision->insertOn( $dbw );
2096 $dbw->update( 'page',
2098 'page_touched' => $now,
2099 'page_namespace' => $nt->getNamespace(),
2100 'page_title' => $nt->getDBkey(),
2101 'page_latest' => $nullRevId,
2103 /* WHERE */ array( 'page_id' => $oldid ),
2107 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2110 $mwRedir = MagicWord
::get( 'redirect' );
2111 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2112 $redirectArticle = new Article( $this );
2113 $newid = $redirectArticle->insertOn( $dbw );
2114 $redirectRevision = new Revision( array(
2116 'comment' => $comment,
2117 'text' => $redirectText ) );
2118 $redirectRevision->insertOn( $dbw );
2119 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2120 $linkCache->clearLink( $this->getPrefixedDBkey() );
2123 $log = new LogPage( 'move' );
2124 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2126 # Purge caches as per article creation
2127 Article
::onArticleCreate( $nt );
2129 # Record the just-created redirect's linking to the page
2130 $dbw->insert( 'pagelinks',
2132 'pl_from' => $newid,
2133 'pl_namespace' => $nt->getNamespace(),
2134 'pl_title' => $nt->getDBkey() ),
2137 # Purge old title from squid
2138 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2139 $this->purgeSquid();
2143 * Checks if $this can be moved to a given Title
2144 * - Selects for update, so don't call it unless you mean business
2146 * @param Title &$nt the new title to check
2149 function isValidMoveTarget( $nt ) {
2151 $fname = 'Title::isValidMoveTarget';
2152 $dbw =& wfGetDB( DB_MASTER
);
2155 $id = $nt->getArticleID();
2156 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2157 array( 'page_is_redirect','old_text','old_flags' ),
2158 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2159 $fname, 'FOR UPDATE' );
2161 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2163 wfDebug( __METHOD__
. ": not a redirect\n" );
2166 $text = Revision
::getRevisionText( $obj );
2168 # Does the redirect point to the source?
2169 # Or is it a broken self-redirect, usually caused by namespace collisions?
2171 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2172 $redirTitle = Title
::newFromText( $m[1] );
2173 if( !is_object( $redirTitle ) ||
2174 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2175 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2176 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2181 wfDebug( __METHOD__
. ": failsafe\n" );
2185 # Does the article have a history?
2186 $row = $dbw->selectRow( array( 'page', 'revision'),
2188 array( 'page_namespace' => $nt->getNamespace(),
2189 'page_title' => $nt->getDBkey(),
2190 'page_id=rev_page AND page_latest != rev_id'
2191 ), $fname, 'FOR UPDATE'
2194 # Return true if there was no history
2195 return $row === false;
2199 * Create a redirect; fails if the title already exists; does
2202 * @param Title $dest the destination of the redirect
2203 * @param string $comment the comment string describing the move
2204 * @return bool true on success
2207 function createRedirect( $dest, $comment ) {
2208 if ( $this->getArticleID() ) {
2212 $fname = 'Title::createRedirect';
2213 $dbw =& wfGetDB( DB_MASTER
);
2215 $article = new Article( $this );
2216 $newid = $article->insertOn( $dbw );
2217 $revision = new Revision( array(
2219 'comment' => $comment,
2220 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2222 $revision->insertOn( $dbw );
2223 $article->updateRevisionOn( $dbw, $revision, 0 );
2226 $dbw->insert( 'pagelinks',
2228 'pl_from' => $newid,
2229 'pl_namespace' => $dest->getNamespace(),
2230 'pl_title' => $dest->getDbKey()
2234 Article
::onArticleCreate( $this );
2239 * Get categories to which this Title belongs and return an array of
2240 * categories' names.
2242 * @return array an array of parents in the form:
2243 * $parent => $currentarticle
2246 function getParentCategories() {
2249 $titlekey = $this->getArticleId();
2250 $dbr =& wfGetDB( DB_SLAVE
);
2251 $categorylinks = $dbr->tableName( 'categorylinks' );
2254 $sql = "SELECT * FROM $categorylinks"
2255 ." WHERE cl_from='$titlekey'"
2256 ." AND cl_from <> '0'"
2257 ." ORDER BY cl_sortkey";
2259 $res = $dbr->query ( $sql ) ;
2261 if($dbr->numRows($res) > 0) {
2262 while ( $x = $dbr->fetchObject ( $res ) )
2263 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2264 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2265 $dbr->freeResult ( $res ) ;
2273 * Get a tree of parent categories
2274 * @param array $children an array with the children in the keys, to check for circular refs
2278 function getParentCategoryTree( $children = array() ) {
2279 $parents = $this->getParentCategories();
2281 if($parents != '') {
2282 foreach($parents as $parent => $current) {
2283 if ( array_key_exists( $parent, $children ) ) {
2284 # Circular reference
2285 $stack[$parent] = array();
2287 $nt = Title
::newFromText($parent);
2289 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2301 * Get an associative array for selecting this title from
2307 function pageCond() {
2308 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2312 * Get the revision ID of the previous revision
2314 * @param integer $revision Revision ID. Get the revision that was before this one.
2315 * @return integer $oldrevision|false
2317 function getPreviousRevisionID( $revision ) {
2318 $dbr =& wfGetDB( DB_SLAVE
);
2319 return $dbr->selectField( 'revision', 'rev_id',
2320 'rev_page=' . intval( $this->getArticleId() ) .
2321 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2325 * Get the revision ID of the next revision
2327 * @param integer $revision Revision ID. Get the revision that was after this one.
2328 * @return integer $oldrevision|false
2330 function getNextRevisionID( $revision ) {
2331 $dbr =& wfGetDB( DB_SLAVE
);
2332 return $dbr->selectField( 'revision', 'rev_id',
2333 'rev_page=' . intval( $this->getArticleId() ) .
2334 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2338 * Get the number of revisions between the given revision IDs.
2340 * @param integer $old Revision ID.
2341 * @param integer $new Revision ID.
2342 * @return integer Number of revisions between these IDs.
2344 function countRevisionsBetween( $old, $new ) {
2345 $dbr =& wfGetDB( DB_SLAVE
);
2346 return $dbr->selectField( 'revision', 'count(*)',
2347 'rev_page = ' . intval( $this->getArticleId() ) .
2348 ' AND rev_id > ' . intval( $old ) .
2349 ' AND rev_id < ' . intval( $new ) );
2353 * Compare with another title.
2355 * @param Title $title
2358 function equals( $title ) {
2359 // Note: === is necessary for proper matching of number-like titles.
2360 return $this->getInterwiki() === $title->getInterwiki()
2361 && $this->getNamespace() == $title->getNamespace()
2362 && $this->getDbkey() === $title->getDbkey();
2366 * Check if page exists
2370 return $this->getArticleId() != 0;
2374 * Should a link should be displayed as a known link, just based on its title?
2376 * Currently, a self-link with a fragment and special pages are in
2377 * this category. Special pages never exist in the database.
2379 function isAlwaysKnown() {
2380 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2381 || NS_SPECIAL
== $this->mNamespace
;
2385 * Update page_touched timestamps and send squid purge messages for
2386 * pages linking to this title. May be sent to the job queue depending
2387 * on the number of links. Typically called on create and delete.
2389 function touchLinks() {
2390 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2393 if ( $this->getNamespace() == NS_CATEGORY
) {
2394 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2400 * Get the last touched timestamp
2402 function getTouched() {
2403 $dbr =& wfGetDB( DB_SLAVE
);
2404 $touched = $dbr->selectField( 'page', 'page_touched',
2406 'page_namespace' => $this->getNamespace(),
2407 'page_title' => $this->getDBkey()
2414 * Get a cached value from a global cache that is invalidated when this page changes
2415 * @param string $key the key
2416 * @param callback $callback A callback function which generates the value on cache miss
2418 * @deprecated use DependencyWrapper
2420 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2421 return DependencyWrapper
::getValueFromCache( $memc, $key, $expiry, $callback,
2422 $params, new TitleDependency( $this ) );
2425 function trackbackURL() {
2426 global $wgTitle, $wgScriptPath, $wgServer;
2428 return "$wgServer$wgScriptPath/trackback.php?article="
2429 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2432 function trackbackRDF() {
2433 $url = htmlspecialchars($this->getFullURL());
2434 $title = htmlspecialchars($this->getText());
2435 $tburl = $this->trackbackURL();
2438 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2439 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2440 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2443 dc:identifier=\"$url\"
2445 trackback:ping=\"$tburl\" />
2450 * Generate strings used for xml 'id' names in monobook tabs
2453 function getNamespaceKey() {
2455 switch ($this->getNamespace()) {
2458 return 'nstab-main';
2461 return 'nstab-user';
2463 return 'nstab-media';
2465 return 'nstab-special';
2467 case NS_PROJECT_TALK
:
2468 return 'nstab-project';
2471 return 'nstab-image';
2473 case NS_MEDIAWIKI_TALK
:
2474 return 'nstab-mediawiki';
2476 case NS_TEMPLATE_TALK
:
2477 return 'nstab-template';
2480 return 'nstab-help';
2482 case NS_CATEGORY_TALK
:
2483 return 'nstab-category';
2485 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2490 * Returns true if this title resolves to the named special page
2491 * @param string $name The special page name
2494 function isSpecial( $name ) {
2495 if ( $this->getNamespace() == NS_SPECIAL
) {
2496 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2497 if ( $name == $thisName ) {
2505 * If the Title refers to a special page alias which is not the local default,
2506 * returns a new Title which points to the local default. Otherwise, returns $this.
2508 function fixSpecialName() {
2509 if ( $this->getNamespace() == NS_SPECIAL
) {
2510 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2511 if ( $canonicalName ) {
2512 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2513 if ( $localName != $this->mDbkeyform
) {
2514 return Title
::makeTitle( NS_SPECIAL
, $localName );
2522 * Is this Title in a namespace which contains content?
2523 * In other words, is this a content page, for the purposes of calculating
2528 public function isContentPage() {
2529 return Namespace::isContent( $this->getNamespace() );