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 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
286 public static function newFromRedirect( $text ) {
287 $mwRedir = MagicWord
::get( 'redirect' );
289 if ( $mwRedir->matchStart( $text ) ) {
291 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
292 # categories are escaped using : for example one can enter:
293 # #REDIRECT [[:Category:Music]]. Need to remove it.
294 if ( substr($m[1],0,1) == ':') {
295 # We don't want to keep the ':'
296 $m[1] = substr( $m[1], 1 );
299 $rt = Title
::newFromText( $m[1] );
300 # Disallow redirects to Special:Userlogout
301 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
309 #----------------------------------------------------------------------------
311 #----------------------------------------------------------------------------
314 * Get the prefixed DB key associated with an ID
315 * @param int $id the page_id of the article
316 * @return Title an object representing the article, or NULL
317 * if no such article was found
321 function nameOf( $id ) {
322 $fname = 'Title::nameOf';
323 $dbr =& wfGetDB( DB_SLAVE
);
325 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
326 if ( $s === false ) { return NULL; }
328 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
333 * Get a regex character class describing the legal characters in a link
334 * @return string the list of characters, not delimited
338 public static function legalChars() {
339 global $wgLegalTitleChars;
340 return $wgLegalTitleChars;
344 * Get a string representation of a title suitable for
345 * including in a search index
347 * @param int $ns a namespace index
348 * @param string $title text-form main part
349 * @return string a stripped-down title string ready for the
352 /* static */ function indexTitle( $ns, $title ) {
355 $lc = SearchEngine
::legalSearchChars() . '&#;';
356 $t = $wgContLang->stripForSearch( $title );
357 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
358 $t = $wgContLang->lc( $t );
361 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
362 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
364 $t = preg_replace( "/\\s+/", ' ', $t );
366 if ( $ns == NS_IMAGE
) {
367 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
373 * Make a prefixed DB key from a DB key and a namespace index
374 * @param int $ns numerical representation of the namespace
375 * @param string $title the DB key form the title
376 * @return string the prefixed form of the title
378 public static function makeName( $ns, $title ) {
381 $n = $wgContLang->getNsText( $ns );
382 return $n == '' ?
$title : "$n:$title";
386 * Returns the URL associated with an interwiki prefix
387 * @param string $key the interwiki prefix (e.g. "MeatBall")
388 * @return the associated URL, containing "$1", which should be
389 * replaced by an article title
393 function getInterwikiLink( $key ) {
394 global $wgMemc, $wgInterwikiExpiry;
395 global $wgInterwikiCache, $wgContLang;
396 $fname = 'Title::getInterwikiLink';
398 $key = $wgContLang->lc( $key );
400 $k = wfMemcKey( 'interwiki', $key );
401 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
402 return Title
::$interwikiCache[$k]->iw_url
;
405 if ($wgInterwikiCache) {
406 return Title
::getInterwikiCached( $key );
409 $s = $wgMemc->get( $k );
410 # Ignore old keys with no iw_local
411 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
412 Title
::$interwikiCache[$k] = $s;
416 $dbr =& wfGetDB( DB_SLAVE
);
417 $res = $dbr->select( 'interwiki',
418 array( 'iw_url', 'iw_local', 'iw_trans' ),
419 array( 'iw_prefix' => $key ), $fname );
424 $s = $dbr->fetchObject( $res );
426 # Cache non-existence: create a blank object and save it to memcached
432 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
433 Title
::$interwikiCache[$k] = $s;
439 * Fetch interwiki prefix data from local cache in constant database
441 * More logic is explained in DefaultSettings
443 * @return string URL of interwiki site
446 function getInterwikiCached( $key ) {
447 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
451 $db=dba_open($wgInterwikiCache,'r','cdb');
452 /* Resolve site name */
453 if ($wgInterwikiScopes>=3 and !$site) {
454 $site = dba_fetch('__sites:' . wfWikiID(), $db);
456 $site = $wgInterwikiFallbackSite;
458 $value = dba_fetch( wfMemcKey( $key ), $db);
459 if ($value=='' and $wgInterwikiScopes>=3) {
461 $value = dba_fetch("_{$site}:{$key}", $db);
463 if ($value=='' and $wgInterwikiScopes>=2) {
465 $value = dba_fetch("__global:{$key}", $db);
474 list($local,$url)=explode(' ',$value,2);
476 $s->iw_local
=(int)$local;
478 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
482 * Determine whether the object refers to a page within
485 * @return bool TRUE if this is an in-project interwiki link
486 * or a wikilink, FALSE otherwise
490 if ( $this->mInterwiki
!= '' ) {
491 # Make sure key is loaded into cache
492 $this->getInterwikiLink( $this->mInterwiki
);
493 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
494 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
501 * Determine whether the object refers to a page within
502 * this project and is transcludable.
504 * @return bool TRUE if this is transcludable
508 if ($this->mInterwiki
== '')
510 # Make sure key is loaded into cache
511 $this->getInterwikiLink( $this->mInterwiki
);
512 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
513 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
517 * Update the page_touched field for an array of title objects
518 * @todo Inefficient unless the IDs are already loaded into the
520 * @param array $titles an array of Title objects to be touched
521 * @param string $timestamp the timestamp to use instead of the
522 * default current time
526 function touchArray( $titles, $timestamp = '' ) {
528 if ( count( $titles ) == 0 ) {
531 $dbw =& wfGetDB( DB_MASTER
);
532 if ( $timestamp == '' ) {
533 $timestamp = $dbw->timestamp();
536 $page = $dbw->tableName( 'page' );
537 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
540 foreach ( $titles as $title ) {
541 if ( $wgUseFileCache ) {
542 $cm = new HTMLFileCache($title);
543 @unlink($cm->fileCacheName());
550 $sql .= $title->getArticleID();
554 $dbw->query( $sql, 'Title::touchArray' );
557 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
558 // do them in small chunks:
559 $fname = 'Title::touchArray';
560 foreach( $titles as $title ) {
561 $dbw->update( 'page',
562 array( 'page_touched' => $timestamp ),
564 'page_namespace' => $title->getNamespace(),
565 'page_title' => $title->getDBkey() ),
571 * Escape a text fragment, say from a link, for a URL
573 static function escapeFragmentForURL( $fragment ) {
574 $fragment = str_replace( ' ', '_', $fragment );
575 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
576 $replaceArray = array(
580 return strtr( $fragment, $replaceArray );
583 #----------------------------------------------------------------------------
585 #----------------------------------------------------------------------------
587 /** Simple accessors */
589 * Get the text form (spaces not underscores) of the main part
593 function getText() { return $this->mTextform
; }
595 * Get the URL-encoded form of the main part
599 function getPartialURL() { return $this->mUrlform
; }
601 * Get the main part with underscores
605 function getDBkey() { return $this->mDbkeyform
; }
607 * Get the namespace index, i.e. one of the NS_xxxx constants
611 function getNamespace() { return $this->mNamespace
; }
613 * Get the namespace text
617 function getNsText() {
619 return $wgContLang->getNsText( $this->mNamespace
);
622 * Get the namespace text of the subject (rather than talk) page
626 function getSubjectNsText() {
628 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
632 * Get the namespace text of the talk page
635 function getTalkNsText() {
637 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
641 * Could this title have a corresponding talk page?
645 return( Namespace::canTalk( $this->mNamespace
) );
649 * Get the interwiki prefix (or null string)
653 function getInterwiki() { return $this->mInterwiki
; }
655 * Get the Title fragment (i.e. the bit after the #) in text form
659 function getFragment() { return $this->mFragment
; }
661 * Get the fragment in URL form, including the "#" character if there is one
666 function getFragmentForURL() {
667 if ( $this->mFragment
== '' ) {
670 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
674 * Get the default namespace index, for when there is no namespace
678 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
681 * Get title for search index
682 * @return string a stripped-down title string ready for the
685 function getIndexTitle() {
686 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
690 * Get the prefixed database key form
691 * @return string the prefixed title, with underscores and
692 * any interwiki and namespace prefixes
695 function getPrefixedDBkey() {
696 $s = $this->prefix( $this->mDbkeyform
);
697 $s = str_replace( ' ', '_', $s );
702 * Get the prefixed title with spaces.
703 * This is the form usually used for display
704 * @return string the prefixed title, with spaces
707 function getPrefixedText() {
708 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
709 $s = $this->prefix( $this->mTextform
);
710 $s = str_replace( '_', ' ', $s );
711 $this->mPrefixedText
= $s;
713 return $this->mPrefixedText
;
717 * Get the prefixed title with spaces, plus any fragment
718 * (part beginning with '#')
719 * @return string the prefixed title, with spaces and
720 * the fragment, including '#'
723 function getFullText() {
724 $text = $this->getPrefixedText();
725 if( '' != $this->mFragment
) {
726 $text .= '#' . $this->mFragment
;
732 * Get the base name, i.e. the leftmost parts before the /
733 * @return string Base name
735 function getBaseText() {
736 global $wgNamespacesWithSubpages;
737 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
738 $parts = explode( '/', $this->getText() );
739 # Don't discard the real title if there's no subpage involved
740 if( count( $parts ) > 1 )
741 unset( $parts[ count( $parts ) - 1 ] );
742 return implode( '/', $parts );
744 return $this->getText();
749 * Get the lowest-level subpage name, i.e. the rightmost part after /
750 * @return string Subpage name
752 function getSubpageText() {
753 global $wgNamespacesWithSubpages;
754 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
755 $parts = explode( '/', $this->mTextform
);
756 return( $parts[ count( $parts ) - 1 ] );
758 return( $this->mTextform
);
763 * Get a URL-encoded form of the subpage text
764 * @return string URL-encoded subpage name
766 function getSubpageUrlForm() {
767 $text = $this->getSubpageText();
768 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
769 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
774 * Get a URL-encoded title (not an actual URL) including interwiki
775 * @return string the URL-encoded form
778 function getPrefixedURL() {
779 $s = $this->prefix( $this->mDbkeyform
);
780 $s = str_replace( ' ', '_', $s );
782 $s = wfUrlencode ( $s ) ;
784 # Cleaning up URL to make it look nice -- is this safe?
785 $s = str_replace( '%28', '(', $s );
786 $s = str_replace( '%29', ')', $s );
792 * Get a real URL referring to this title, with interwiki link and
795 * @param string $query an optional query string, not used
796 * for interwiki links
797 * @param string $variant language variant of url (for sr, zh..)
798 * @return string the URL
801 function getFullURL( $query = '', $variant = false ) {
802 global $wgContLang, $wgServer, $wgRequest;
804 if ( '' == $this->mInterwiki
) {
805 $url = $this->getLocalUrl( $query, $variant );
807 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
808 // Correct fix would be to move the prepending elsewhere.
809 if ($wgRequest->getVal('action') != 'render') {
810 $url = $wgServer . $url;
813 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
815 $namespace = $wgContLang->getNsText( $this->mNamespace
);
816 if ( '' != $namespace ) {
817 # Can this actually happen? Interwikis shouldn't be parsed.
820 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
822 if( false === strpos( $url, '?' ) ) {
831 # Finally, add the fragment.
832 $url .= $this->getFragmentForURL();
834 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
839 * Get a URL with no fragment or server name. If this page is generated
840 * with action=render, $wgServer is prepended.
841 * @param string $query an optional query string; if not specified,
842 * $wgArticlePath will be used.
843 * @param string $variant language variant of url (for sr, zh..)
844 * @return string the URL
847 function getLocalURL( $query = '', $variant = false ) {
848 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
849 global $wgVariantArticlePath, $wgContLang, $wgUser;
851 // internal links should point to same variant as current page (only anonymous users)
852 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
853 $pref = $wgContLang->getPreferredVariant(false);
854 if($pref != $wgContLang->getCode())
858 if ( $this->isExternal() ) {
859 $url = $this->getFullURL();
861 // This is currently only used for edit section links in the
862 // context of interwiki transclusion. In theory we should
863 // append the query to the end of any existing query string,
864 // but interwiki transclusion is already broken in that case.
868 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
869 if ( $query == '' ) {
870 if($variant!=false && $wgContLang->hasVariants()){
871 if($wgVariantArticlePath==false)
872 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
874 $variantArticlePath = $wgVariantArticlePath;
876 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
877 $url = str_replace( '$1', $dbkey, $url );
881 $url = str_replace( '$1', $dbkey, $wgArticlePath );
883 global $wgActionPaths;
886 if( !empty( $wgActionPaths ) &&
887 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
889 $action = urldecode( $matches[2] );
890 if( isset( $wgActionPaths[$action] ) ) {
891 $query = $matches[1];
892 if( isset( $matches[4] ) ) $query .= $matches[4];
893 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
894 if( $query != '' ) $url .= '?' . $query;
897 if ( $url === false ) {
898 if ( $query == '-' ) {
901 $url = "{$wgScript}?title={$dbkey}&{$query}";
905 // FIXME: this causes breakage in various places when we
906 // actually expected a local URL and end up with dupe prefixes.
907 if ($wgRequest->getVal('action') == 'render') {
908 $url = $wgServer . $url;
911 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
916 * Get an HTML-escaped version of the URL form, suitable for
917 * using in a link, without a server name or fragment
918 * @param string $query an optional query string
919 * @return string the URL
922 function escapeLocalURL( $query = '' ) {
923 return htmlspecialchars( $this->getLocalURL( $query ) );
927 * Get an HTML-escaped version of the URL form, suitable for
928 * using in a link, including the server name and fragment
930 * @return string the URL
931 * @param string $query an optional query string
934 function escapeFullURL( $query = '' ) {
935 return htmlspecialchars( $this->getFullURL( $query ) );
939 * Get the URL form for an internal link.
940 * - Used in various Squid-related code, in case we have a different
941 * internal hostname for the server from the exposed one.
943 * @param string $query an optional query string
944 * @param string $variant language variant of url (for sr, zh..)
945 * @return string the URL
948 function getInternalURL( $query = '', $variant = false ) {
949 global $wgInternalServer;
950 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
951 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
956 * Get the edit URL for this Title
957 * @return string the URL, or a null string if this is an
961 function getEditURL() {
962 if ( '' != $this->mInterwiki
) { return ''; }
963 $s = $this->getLocalURL( 'action=edit' );
969 * Get the HTML-escaped displayable text form.
970 * Used for the title field in <a> tags.
971 * @return string the text, including any prefixes
974 function getEscapedText() {
975 return htmlspecialchars( $this->getPrefixedText() );
979 * Is this Title interwiki?
983 function isExternal() { return ( '' != $this->mInterwiki
); }
986 * Is this page "semi-protected" - the *only* protection is autoconfirm?
988 * @param string Action to check (default: edit)
991 function isSemiProtected( $action = 'edit' ) {
992 $restrictions = $this->getRestrictions( $action );
993 # We do a full compare because this could be an array
994 foreach( $restrictions as $restriction ) {
995 if( strtolower( $restriction ) != 'autoconfirmed' ) {
1003 * Does the title correspond to a protected article?
1004 * @param string $what the action the page is protected from,
1005 * by default checks move and edit
1009 function isProtected( $action = '' ) {
1010 global $wgRestrictionLevels;
1011 if ( NS_SPECIAL
== $this->mNamespace
) { return true; }
1013 if( $action == 'edit' ||
$action == '' ) {
1014 $r = $this->getRestrictions( 'edit' );
1015 foreach( $wgRestrictionLevels as $level ) {
1016 if( in_array( $level, $r ) && $level != '' ) {
1022 if( $action == 'move' ||
$action == '' ) {
1023 $r = $this->getRestrictions( 'move' );
1024 foreach( $wgRestrictionLevels as $level ) {
1025 if( in_array( $level, $r ) && $level != '' ) {
1035 * Is $wgUser is watching this page?
1039 function userIsWatching() {
1042 if ( is_null( $this->mWatched
) ) {
1043 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1044 $this->mWatched
= false;
1046 $this->mWatched
= $wgUser->isWatched( $this );
1049 return $this->mWatched
;
1053 * Can $wgUser perform $action this page?
1054 * @param string $action action that permission needs to be checked for
1058 function userCan($action) {
1059 $fname = 'Title::userCan';
1060 wfProfileIn( $fname );
1065 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1066 if ( $result !== null ) {
1067 wfProfileOut( $fname );
1071 if( NS_SPECIAL
== $this->mNamespace
) {
1072 wfProfileOut( $fname );
1075 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1076 // from taking effect -ævar
1077 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1078 !$wgUser->isAllowed('editinterface') ) {
1079 wfProfileOut( $fname );
1083 if( $this->mDbkeyform
== '_' ) {
1084 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1085 wfProfileOut( $fname );
1089 # protect css/js subpages of user pages
1090 # XXX: this might be better using restrictions
1091 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1092 if( NS_USER
== $this->mNamespace
1093 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1094 && !$wgUser->isAllowed('editinterface')
1095 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1096 wfProfileOut( $fname );
1100 foreach( $this->getRestrictions($action) as $right ) {
1101 // Backwards compatibility, rewrite sysop -> protect
1102 if ( $right == 'sysop' ) {
1105 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1106 wfProfileOut( $fname );
1111 if( $action == 'move' &&
1112 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1113 wfProfileOut( $fname );
1117 if( $action == 'create' ) {
1118 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1119 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1120 wfProfileOut( $fname );
1125 wfProfileOut( $fname );
1130 * Can $wgUser edit this page?
1134 function userCanEdit() {
1135 return $this->userCan('edit');
1139 * Can $wgUser create this page?
1143 function userCanCreate() {
1144 return $this->userCan('create');
1148 * Can $wgUser move this page?
1152 function userCanMove() {
1153 return $this->userCan('move');
1157 * Would anybody with sufficient privileges be able to move this page?
1158 * Some pages just aren't movable.
1163 function isMovable() {
1164 return Namespace::isMovable( $this->getNamespace() )
1165 && $this->getInterwiki() == '';
1169 * Can $wgUser read this page?
1173 function userCanRead() {
1177 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1178 if ( $result !== null ) {
1182 if( $wgUser->isAllowed('read') ) {
1185 global $wgWhitelistRead;
1188 * Always grant access to the login page.
1189 * Even anons need to be able to log in.
1191 if( $this->isSpecial( 'Userlogin' ) ) {
1195 /** some pages are explicitly allowed */
1196 $name = $this->getPrefixedText();
1197 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1201 # Compatibility with old settings
1202 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1203 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1212 * Is this a talk page of some sort?
1216 function isTalkPage() {
1217 return Namespace::isTalk( $this->getNamespace() );
1221 * Is this a .css or .js subpage of a user page?
1225 function isCssJsSubpage() {
1226 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1229 * Is this a *valid* .css or .js subpage of a user page?
1230 * Check that the corresponding skin exists
1232 function isValidCssJsSubpage() {
1233 if ( $this->isCssJsSubpage() ) {
1234 $skinNames = Skin
::getSkinNames();
1235 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1241 * Trim down a .css or .js subpage title to get the corresponding skin name
1243 function getSkinFromCssJsSubpage() {
1244 $subpage = explode( '/', $this->mTextform
);
1245 $subpage = $subpage[ count( $subpage ) - 1 ];
1246 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1249 * Is this a .css subpage of a user page?
1253 function isCssSubpage() {
1254 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1257 * Is this a .js subpage of a user page?
1261 function isJsSubpage() {
1262 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1265 * Protect css/js subpages of user pages: can $wgUser edit
1269 * @todo XXX: this might be better using restrictions
1272 function userCanEditCssJsSubpage() {
1274 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1278 * Loads a string into mRestrictions array
1279 * @param string $res restrictions in string format
1282 function loadRestrictions( $res ) {
1283 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1284 $temp = explode( '=', trim( $restrict ) );
1285 if(count($temp) == 1) {
1286 // old format should be treated as edit/move restriction
1287 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1288 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1290 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1293 $this->mRestrictionsLoaded
= true;
1297 * Accessor/initialisation for mRestrictions
1298 * @param string $action action that permission needs to be checked for
1299 * @return array the array of groups allowed to edit this article
1302 function getRestrictions($action) {
1303 $id = $this->getArticleID();
1304 if ( 0 == $id ) { return array(); }
1306 if ( ! $this->mRestrictionsLoaded
) {
1307 $dbr =& wfGetDB( DB_SLAVE
);
1308 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1309 $this->loadRestrictions( $res );
1311 if( isset( $this->mRestrictions
[$action] ) ) {
1312 return $this->mRestrictions
[$action];
1318 * Is there a version of this page in the deletion archive?
1319 * @return int the number of archived revisions
1322 function isDeleted() {
1323 $fname = 'Title::isDeleted';
1324 if ( $this->getNamespace() < 0 ) {
1327 $dbr =& wfGetDB( DB_SLAVE
);
1328 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1329 'ar_title' => $this->getDBkey() ), $fname );
1330 if( $this->getNamespace() == NS_IMAGE
) {
1331 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1332 array( 'fa_name' => $this->getDBkey() ), $fname );
1339 * Get the article ID for this Title from the link cache,
1340 * adding it if necessary
1341 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1343 * @return int the ID
1346 function getArticleID( $flags = 0 ) {
1347 $linkCache =& LinkCache
::singleton();
1348 if ( $flags & GAID_FOR_UPDATE
) {
1349 $oldUpdate = $linkCache->forUpdate( true );
1350 $this->mArticleID
= $linkCache->addLinkObj( $this );
1351 $linkCache->forUpdate( $oldUpdate );
1353 if ( -1 == $this->mArticleID
) {
1354 $this->mArticleID
= $linkCache->addLinkObj( $this );
1357 return $this->mArticleID
;
1360 function getLatestRevID() {
1361 if ($this->mLatestID
!== false)
1362 return $this->mLatestID
;
1364 $db =& wfGetDB(DB_SLAVE
);
1365 return $this->mLatestID
= $db->selectField( 'revision',
1367 array('rev_page' => $this->getArticleID()),
1368 'Title::getLatestRevID' );
1372 * This clears some fields in this object, and clears any associated
1373 * keys in the "bad links" section of the link cache.
1375 * - This is called from Article::insertNewArticle() to allow
1376 * loading of the new page_id. It's also called from
1377 * Article::doDeleteArticle()
1379 * @param int $newid the new Article ID
1382 function resetArticleID( $newid ) {
1383 $linkCache =& LinkCache
::singleton();
1384 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1386 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1387 else { $this->mArticleID
= $newid; }
1388 $this->mRestrictionsLoaded
= false;
1389 $this->mRestrictions
= array();
1393 * Updates page_touched for this page; called from LinksUpdate.php
1394 * @return bool true if the update succeded
1397 function invalidateCache() {
1398 global $wgUseFileCache;
1400 if ( wfReadOnly() ) {
1404 $dbw =& wfGetDB( DB_MASTER
);
1405 $success = $dbw->update( 'page',
1407 'page_touched' => $dbw->timestamp()
1408 ), array( /* WHERE */
1409 'page_namespace' => $this->getNamespace() ,
1410 'page_title' => $this->getDBkey()
1411 ), 'Title::invalidateCache'
1414 if ($wgUseFileCache) {
1415 $cache = new HTMLFileCache($this);
1416 @unlink
($cache->fileCacheName());
1423 * Prefix some arbitrary text with the namespace or interwiki prefix
1426 * @param string $name the text
1427 * @return string the prefixed text
1430 /* private */ function prefix( $name ) {
1434 if ( '' != $this->mInterwiki
) {
1435 $p = $this->mInterwiki
. ':';
1437 if ( 0 != $this->mNamespace
) {
1438 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1444 * Secure and split - main initialisation function for this object
1446 * Assumes that mDbkeyform has been set, and is urldecoded
1447 * and uses underscores, but not otherwise munged. This function
1448 * removes illegal characters, splits off the interwiki and
1449 * namespace prefixes, sets the other forms, and canonicalizes
1451 * @return bool true on success
1454 /* private */ function secureAndSplit() {
1455 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1458 static $rxTc = false;
1460 # % is needed as well
1461 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1464 $this->mInterwiki
= $this->mFragment
= '';
1465 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1467 # Clean up whitespace
1469 $dbkey = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1470 $dbkey = trim( $dbkey, '_' );
1472 if ( '' == $dbkey ) {
1476 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1477 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1481 $this->mDbkeyform
= $dbkey;
1483 # Initial colon indicates main namespace rather than specified default
1484 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1485 if ( ':' == $dbkey{0} ) {
1486 $this->mNamespace
= NS_MAIN
;
1487 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1490 # Namespace or interwiki prefix
1494 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1496 $lowerNs = $wgContLang->lc( $p );
1497 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1498 # Canonical namespace
1500 $this->mNamespace
= $ns;
1501 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1502 # Ordinary namespace
1504 $this->mNamespace
= $ns;
1505 } elseif( $this->getInterwikiLink( $p ) ) {
1507 # Can't make a local interwiki link to an interwiki link.
1508 # That's just crazy!
1514 $this->mInterwiki
= $wgContLang->lc( $p );
1516 # Redundant interwiki prefix to the local wiki
1517 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1518 if( $dbkey == '' ) {
1519 # Can't have an empty self-link
1522 $this->mInterwiki
= '';
1524 # Do another namespace split...
1528 # If there's an initial colon after the interwiki, that also
1529 # resets the default namespace
1530 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1531 $this->mNamespace
= NS_MAIN
;
1532 $dbkey = substr( $dbkey, 1 );
1535 # If there's no recognized interwiki or namespace,
1536 # then let the colon expression be part of the title.
1541 # We already know that some pages won't be in the database!
1543 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1544 $this->mArticleID
= 0;
1546 $fragment = strstr( $dbkey, '#' );
1547 if ( false !== $fragment ) {
1548 $this->setFragment( $fragment );
1549 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1550 # remove whitespace again: prevents "Foo_bar_#"
1551 # becoming "Foo_bar_"
1552 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1555 # Reject illegal characters.
1557 if( preg_match( $rxTc, $dbkey ) ) {
1562 * Pages with "/./" or "/../" appearing in the URLs will
1563 * often be unreachable due to the way web browsers deal
1564 * with 'relative' URLs. Forbid them explicitly.
1566 if ( strpos( $dbkey, '.' ) !== false &&
1567 ( $dbkey === '.' ||
$dbkey === '..' ||
1568 strpos( $dbkey, './' ) === 0 ||
1569 strpos( $dbkey, '../' ) === 0 ||
1570 strpos( $dbkey, '/./' ) !== false ||
1571 strpos( $dbkey, '/../' ) !== false ) )
1577 * Limit the size of titles to 255 bytes.
1578 * This is typically the size of the underlying database field.
1579 * We make an exception for special pages, which don't need to be stored
1580 * in the database, and may edge over 255 bytes due to subpage syntax
1581 * for long titles, e.g. [[Special:Block/Long name]]
1583 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1584 strlen( $dbkey ) > 512 )
1590 * Normally, all wiki links are forced to have
1591 * an initial capital letter so [[foo]] and [[Foo]]
1592 * point to the same place.
1594 * Don't force it for interwikis, since the other
1595 * site might be case-sensitive.
1597 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1598 $dbkey = $wgContLang->ucfirst( $dbkey );
1602 * Can't make a link to a namespace alone...
1603 * "empty" local links can only be self-links
1604 * with a fragment identifier.
1607 $this->mInterwiki
== '' &&
1608 $this->mNamespace
!= NS_MAIN
) {
1612 // Any remaining initial :s are illegal.
1613 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1618 $this->mDbkeyform
= $dbkey;
1619 $this->mUrlform
= wfUrlencode( $dbkey );
1621 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1627 * Set the fragment for this title
1628 * This is kind of bad, since except for this rarely-used function, Title objects
1629 * are immutable. The reason this is here is because it's better than setting the
1630 * members directly, which is what Linker::formatComment was doing previously.
1632 * @param string $fragment text
1633 * @access kind of public
1635 function setFragment( $fragment ) {
1636 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1640 * Get a Title object associated with the talk page of this article
1641 * @return Title the object for the talk page
1644 function getTalkPage() {
1645 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1649 * Get a title object associated with the subject page of this
1652 * @return Title the object for the subject page
1655 function getSubjectPage() {
1656 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1660 * Get an array of Title objects linking to this Title
1661 * Also stores the IDs in the link cache.
1663 * WARNING: do not use this function on arbitrary user-supplied titles!
1664 * On heavily-used templates it will max out the memory.
1666 * @param string $options may be FOR UPDATE
1667 * @return array the Title objects linking here
1670 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1671 $linkCache =& LinkCache
::singleton();
1674 $db =& wfGetDB( DB_MASTER
);
1676 $db =& wfGetDB( DB_SLAVE
);
1679 $res = $db->select( array( 'page', $table ),
1680 array( 'page_namespace', 'page_title', 'page_id' ),
1682 "{$prefix}_from=page_id",
1683 "{$prefix}_namespace" => $this->getNamespace(),
1684 "{$prefix}_title" => $this->getDbKey() ),
1685 'Title::getLinksTo',
1689 if ( $db->numRows( $res ) ) {
1690 while ( $row = $db->fetchObject( $res ) ) {
1691 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1692 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1693 $retVal[] = $titleObj;
1697 $db->freeResult( $res );
1702 * Get an array of Title objects using this Title as a template
1703 * Also stores the IDs in the link cache.
1705 * WARNING: do not use this function on arbitrary user-supplied titles!
1706 * On heavily-used templates it will max out the memory.
1708 * @param string $options may be FOR UPDATE
1709 * @return array the Title objects linking here
1712 function getTemplateLinksTo( $options = '' ) {
1713 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1717 * Get an array of Title objects referring to non-existent articles linked from this page
1719 * @param string $options may be FOR UPDATE
1720 * @return array the Title objects
1723 function getBrokenLinksFrom( $options = '' ) {
1725 $db =& wfGetDB( DB_MASTER
);
1727 $db =& wfGetDB( DB_SLAVE
);
1730 $res = $db->safeQuery(
1731 "SELECT pl_namespace, pl_title
1734 ON pl_namespace=page_namespace
1735 AND pl_title=page_title
1737 AND page_namespace IS NULL
1739 $db->tableName( 'pagelinks' ),
1740 $db->tableName( 'page' ),
1741 $this->getArticleId(),
1745 if ( $db->numRows( $res ) ) {
1746 while ( $row = $db->fetchObject( $res ) ) {
1747 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1750 $db->freeResult( $res );
1756 * Get a list of URLs to purge from the Squid cache when this
1759 * @return array the URLs
1762 function getSquidURLs() {
1766 $this->getInternalURL(),
1767 $this->getInternalURL( 'action=history' )
1770 // purge variant urls as well
1771 if($wgContLang->hasVariants()){
1772 $variants = $wgContLang->getVariants();
1773 foreach($variants as $vCode){
1774 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1775 $urls[] = $this->getInternalURL('',$vCode);
1782 function purgeSquid() {
1784 if ( $wgUseSquid ) {
1785 $urls = $this->getSquidURLs();
1786 $u = new SquidUpdate( $urls );
1792 * Move this page without authentication
1793 * @param Title &$nt the new page Title
1796 function moveNoAuth( &$nt ) {
1797 return $this->moveTo( $nt, false );
1801 * Check whether a given move operation would be valid.
1802 * Returns true if ok, or a message key string for an error message
1803 * if invalid. (Scarrrrry ugly interface this.)
1804 * @param Title &$nt the new title
1805 * @param bool $auth indicates whether $wgUser's permissions
1807 * @return mixed true on success, message name on failure
1810 function isValidMoveOperation( &$nt, $auth = true ) {
1811 if( !$this or !$nt ) {
1812 return 'badtitletext';
1814 if( $this->equals( $nt ) ) {
1817 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1818 return 'immobile_namespace';
1821 $oldid = $this->getArticleID();
1822 $newid = $nt->getArticleID();
1824 if ( strlen( $nt->getDBkey() ) < 1 ) {
1825 return 'articleexists';
1827 if ( ( '' == $this->getDBkey() ) ||
1829 ( '' == $nt->getDBkey() ) ) {
1830 return 'badarticleerror';
1834 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1835 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1836 return 'protectedpage';
1839 # The move is allowed only if (1) the target doesn't exist, or
1840 # (2) the target is a redirect to the source, and has no history
1841 # (so we can undo bad moves right after they're done).
1843 if ( 0 != $newid ) { # Target exists; check for validity
1844 if ( ! $this->isValidMoveTarget( $nt ) ) {
1845 return 'articleexists';
1852 * Move a title to a new location
1853 * @param Title &$nt the new title
1854 * @param bool $auth indicates whether $wgUser's permissions
1856 * @return mixed true on success, message name on failure
1859 function moveTo( &$nt, $auth = true, $reason = '' ) {
1860 $err = $this->isValidMoveOperation( $nt, $auth );
1861 if( is_string( $err ) ) {
1865 $pageid = $this->getArticleID();
1866 if( $nt->exists() ) {
1867 $this->moveOverExistingRedirect( $nt, $reason );
1868 $pageCountChange = 0;
1869 } else { # Target didn't exist, do normal move.
1870 $this->moveToNewTitle( $nt, $reason );
1871 $pageCountChange = 1;
1873 $redirid = $this->getArticleID();
1875 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1876 $dbw =& wfGetDB( DB_MASTER
);
1877 $categorylinks = $dbw->tableName( 'categorylinks' );
1878 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1879 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1880 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1881 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1885 $oldnamespace = $this->getNamespace() & ~
1;
1886 $newnamespace = $nt->getNamespace() & ~
1;
1887 $oldtitle = $this->getDBkey();
1888 $newtitle = $nt->getDBkey();
1890 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1891 WatchedItem
::duplicateEntries( $this, $nt );
1894 # Update search engine
1895 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1897 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1901 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1902 # Moved out of main namespace
1903 # not viewed, edited, removing
1904 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1905 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1906 # Moved into main namespace
1907 # not viewed, edited, adding
1908 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1909 } elseif ( $pageCountChange ) {
1911 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1920 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1925 * Move page to a title which is at present a redirect to the
1928 * @param Title &$nt the page to move to, which should currently
1932 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1934 $fname = 'Title::moveOverExistingRedirect';
1935 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1938 $comment .= ": $reason";
1941 $now = wfTimestampNow();
1942 $newid = $nt->getArticleID();
1943 $oldid = $this->getArticleID();
1944 $dbw =& wfGetDB( DB_MASTER
);
1945 $linkCache =& LinkCache
::singleton();
1947 # Delete the old redirect. We don't save it to history since
1948 # by definition if we've got here it's rather uninteresting.
1949 # We have to remove it so that the next step doesn't trigger
1950 # a conflict on the unique namespace+title index...
1951 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1953 # Save a null revision in the page's history notifying of the move
1954 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1955 $nullRevId = $nullRevision->insertOn( $dbw );
1957 # Change the name of the target page:
1958 $dbw->update( 'page',
1960 'page_touched' => $dbw->timestamp($now),
1961 'page_namespace' => $nt->getNamespace(),
1962 'page_title' => $nt->getDBkey(),
1963 'page_latest' => $nullRevId,
1965 /* WHERE */ array( 'page_id' => $oldid ),
1968 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1970 # Recreate the redirect, this time in the other direction.
1971 $mwRedir = MagicWord
::get( 'redirect' );
1972 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1973 $redirectArticle = new Article( $this );
1974 $newid = $redirectArticle->insertOn( $dbw );
1975 $redirectRevision = new Revision( array(
1977 'comment' => $comment,
1978 'text' => $redirectText ) );
1979 $redirectRevision->insertOn( $dbw );
1980 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1981 $linkCache->clearLink( $this->getPrefixedDBkey() );
1984 $log = new LogPage( 'move' );
1985 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1987 # Now, we record the link from the redirect to the new title.
1988 # It should have no other outgoing links...
1989 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1990 $dbw->insert( 'pagelinks',
1992 'pl_from' => $newid,
1993 'pl_namespace' => $nt->getNamespace(),
1994 'pl_title' => $nt->getDbKey() ),
1998 if ( $wgUseSquid ) {
1999 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2000 $u = new SquidUpdate( $urls );
2006 * Move page to non-existing title.
2007 * @param Title &$nt the new Title
2010 function moveToNewTitle( &$nt, $reason = '' ) {
2012 $fname = 'MovePageForm::moveToNewTitle';
2013 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2015 $comment .= ": $reason";
2018 $newid = $nt->getArticleID();
2019 $oldid = $this->getArticleID();
2020 $dbw =& wfGetDB( DB_MASTER
);
2021 $now = $dbw->timestamp();
2022 $linkCache =& LinkCache
::singleton();
2024 # Save a null revision in the page's history notifying of the move
2025 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2026 $nullRevId = $nullRevision->insertOn( $dbw );
2029 $dbw->update( 'page',
2031 'page_touched' => $now,
2032 'page_namespace' => $nt->getNamespace(),
2033 'page_title' => $nt->getDBkey(),
2034 'page_latest' => $nullRevId,
2036 /* WHERE */ array( 'page_id' => $oldid ),
2040 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2043 $mwRedir = MagicWord
::get( 'redirect' );
2044 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2045 $redirectArticle = new Article( $this );
2046 $newid = $redirectArticle->insertOn( $dbw );
2047 $redirectRevision = new Revision( array(
2049 'comment' => $comment,
2050 'text' => $redirectText ) );
2051 $redirectRevision->insertOn( $dbw );
2052 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2053 $linkCache->clearLink( $this->getPrefixedDBkey() );
2056 $log = new LogPage( 'move' );
2057 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2059 # Purge caches as per article creation
2060 Article
::onArticleCreate( $nt );
2062 # Record the just-created redirect's linking to the page
2063 $dbw->insert( 'pagelinks',
2065 'pl_from' => $newid,
2066 'pl_namespace' => $nt->getNamespace(),
2067 'pl_title' => $nt->getDBkey() ),
2070 # Purge old title from squid
2071 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2072 $this->purgeSquid();
2076 * Checks if $this can be moved to a given Title
2077 * - Selects for update, so don't call it unless you mean business
2079 * @param Title &$nt the new title to check
2082 function isValidMoveTarget( $nt ) {
2084 $fname = 'Title::isValidMoveTarget';
2085 $dbw =& wfGetDB( DB_MASTER
);
2088 $id = $nt->getArticleID();
2089 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2090 array( 'page_is_redirect','old_text','old_flags' ),
2091 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2092 $fname, 'FOR UPDATE' );
2094 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2096 wfDebug( __METHOD__
. ": not a redirect\n" );
2099 $text = Revision
::getRevisionText( $obj );
2101 # Does the redirect point to the source?
2102 # Or is it a broken self-redirect, usually caused by namespace collisions?
2104 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2105 $redirTitle = Title
::newFromText( $m[1] );
2106 if( !is_object( $redirTitle ) ||
2107 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2108 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2109 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2114 wfDebug( __METHOD__
. ": failsafe\n" );
2118 # Does the article have a history?
2119 $row = $dbw->selectRow( array( 'page', 'revision'),
2121 array( 'page_namespace' => $nt->getNamespace(),
2122 'page_title' => $nt->getDBkey(),
2123 'page_id=rev_page AND page_latest != rev_id'
2124 ), $fname, 'FOR UPDATE'
2127 # Return true if there was no history
2128 return $row === false;
2132 * Create a redirect; fails if the title already exists; does
2135 * @param Title $dest the destination of the redirect
2136 * @param string $comment the comment string describing the move
2137 * @return bool true on success
2140 function createRedirect( $dest, $comment ) {
2141 if ( $this->getArticleID() ) {
2145 $fname = 'Title::createRedirect';
2146 $dbw =& wfGetDB( DB_MASTER
);
2148 $article = new Article( $this );
2149 $newid = $article->insertOn( $dbw );
2150 $revision = new Revision( array(
2152 'comment' => $comment,
2153 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2155 $revision->insertOn( $dbw );
2156 $article->updateRevisionOn( $dbw, $revision, 0 );
2159 $dbw->insert( 'pagelinks',
2161 'pl_from' => $newid,
2162 'pl_namespace' => $dest->getNamespace(),
2163 'pl_title' => $dest->getDbKey()
2167 Article
::onArticleCreate( $this );
2172 * Get categories to which this Title belongs and return an array of
2173 * categories' names.
2175 * @return array an array of parents in the form:
2176 * $parent => $currentarticle
2179 function getParentCategories() {
2182 $titlekey = $this->getArticleId();
2183 $dbr =& wfGetDB( DB_SLAVE
);
2184 $categorylinks = $dbr->tableName( 'categorylinks' );
2187 $sql = "SELECT * FROM $categorylinks"
2188 ." WHERE cl_from='$titlekey'"
2189 ." AND cl_from <> '0'"
2190 ." ORDER BY cl_sortkey";
2192 $res = $dbr->query ( $sql ) ;
2194 if($dbr->numRows($res) > 0) {
2195 while ( $x = $dbr->fetchObject ( $res ) )
2196 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2197 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2198 $dbr->freeResult ( $res ) ;
2206 * Get a tree of parent categories
2207 * @param array $children an array with the children in the keys, to check for circular refs
2211 function getParentCategoryTree( $children = array() ) {
2212 $parents = $this->getParentCategories();
2214 if($parents != '') {
2215 foreach($parents as $parent => $current) {
2216 if ( array_key_exists( $parent, $children ) ) {
2217 # Circular reference
2218 $stack[$parent] = array();
2220 $nt = Title
::newFromText($parent);
2222 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2234 * Get an associative array for selecting this title from
2240 function pageCond() {
2241 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2245 * Get the revision ID of the previous revision
2247 * @param integer $revision Revision ID. Get the revision that was before this one.
2248 * @return integer $oldrevision|false
2250 function getPreviousRevisionID( $revision ) {
2251 $dbr =& wfGetDB( DB_SLAVE
);
2252 return $dbr->selectField( 'revision', 'rev_id',
2253 'rev_page=' . intval( $this->getArticleId() ) .
2254 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2258 * Get the revision ID of the next revision
2260 * @param integer $revision Revision ID. Get the revision that was after this one.
2261 * @return integer $oldrevision|false
2263 function getNextRevisionID( $revision ) {
2264 $dbr =& wfGetDB( DB_SLAVE
);
2265 return $dbr->selectField( 'revision', 'rev_id',
2266 'rev_page=' . intval( $this->getArticleId() ) .
2267 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2271 * Get the number of revisions between the given revision IDs.
2273 * @param integer $old Revision ID.
2274 * @param integer $new Revision ID.
2275 * @return integer Number of revisions between these IDs.
2277 function countRevisionsBetween( $old, $new ) {
2278 $dbr =& wfGetDB( DB_SLAVE
);
2279 return $dbr->selectField( 'revision', 'count(*)',
2280 'rev_page = ' . intval( $this->getArticleId() ) .
2281 ' AND rev_id > ' . intval( $old ) .
2282 ' AND rev_id < ' . intval( $new ) );
2286 * Compare with another title.
2288 * @param Title $title
2291 function equals( $title ) {
2292 // Note: === is necessary for proper matching of number-like titles.
2293 return $this->getInterwiki() === $title->getInterwiki()
2294 && $this->getNamespace() == $title->getNamespace()
2295 && $this->getDbkey() === $title->getDbkey();
2299 * Check if page exists
2303 return $this->getArticleId() != 0;
2307 * Should a link should be displayed as a known link, just based on its title?
2309 * Currently, a self-link with a fragment and special pages are in
2310 * this category. Special pages never exist in the database.
2312 function isAlwaysKnown() {
2313 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2314 || NS_SPECIAL
== $this->mNamespace
;
2318 * Update page_touched timestamps and send squid purge messages for
2319 * pages linking to this title. May be sent to the job queue depending
2320 * on the number of links. Typically called on create and delete.
2322 function touchLinks() {
2323 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2326 if ( $this->getNamespace() == NS_CATEGORY
) {
2327 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2333 * Get the last touched timestamp
2335 function getTouched() {
2336 $dbr =& wfGetDB( DB_SLAVE
);
2337 $touched = $dbr->selectField( 'page', 'page_touched',
2339 'page_namespace' => $this->getNamespace(),
2340 'page_title' => $this->getDBkey()
2347 * Get a cached value from a global cache that is invalidated when this page changes
2348 * @param string $key the key
2349 * @param callback $callback A callback function which generates the value on cache miss
2351 * @deprecated use DependencyWrapper
2353 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2354 return DependencyWrapper
::getValueFromCache( $memc, $key, $expiry, $callback,
2355 $params, new TitleDependency( $this ) );
2358 function trackbackURL() {
2359 global $wgTitle, $wgScriptPath, $wgServer;
2361 return "$wgServer$wgScriptPath/trackback.php?article="
2362 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2365 function trackbackRDF() {
2366 $url = htmlspecialchars($this->getFullURL());
2367 $title = htmlspecialchars($this->getText());
2368 $tburl = $this->trackbackURL();
2371 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2372 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2373 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2376 dc:identifier=\"$url\"
2378 trackback:ping=\"$tburl\" />
2383 * Generate strings used for xml 'id' names in monobook tabs
2386 function getNamespaceKey() {
2388 switch ($this->getNamespace()) {
2391 return 'nstab-main';
2394 return 'nstab-user';
2396 return 'nstab-media';
2398 return 'nstab-special';
2400 case NS_PROJECT_TALK
:
2401 return 'nstab-project';
2404 return 'nstab-image';
2406 case NS_MEDIAWIKI_TALK
:
2407 return 'nstab-mediawiki';
2409 case NS_TEMPLATE_TALK
:
2410 return 'nstab-template';
2413 return 'nstab-help';
2415 case NS_CATEGORY_TALK
:
2416 return 'nstab-category';
2418 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2423 * Returns true if this title resolves to the named special page
2424 * @param string $name The special page name
2427 function isSpecial( $name ) {
2428 if ( $this->getNamespace() == NS_SPECIAL
) {
2429 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2430 if ( $name == $thisName ) {
2438 * If the Title refers to a special page alias which is not the local default,
2439 * returns a new Title which points to the local default. Otherwise, returns $this.
2441 function fixSpecialName() {
2442 if ( $this->getNamespace() == NS_SPECIAL
) {
2443 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2444 if ( $canonicalName ) {
2445 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2446 if ( $localName != $this->mDbkeyform
) {
2447 return Title
::makeTitle( NS_SPECIAL
, $localName );