8 global $wgTitleInterwikiCache, $wgTitleCache;
10 $wgTitleInterwikiCache = array();
11 $wgTitleCache = array();
13 define ( 'GAID_FOR_UPDATE', 1 );
15 # Title::newFromTitle maintains a cache to avoid
16 # expensive re-normalization of commonly used titles.
17 # On a batch operation this can become a memory leak
18 # if not bounded. After hitting this many titles,
20 define( 'MW_TITLECACHE_MAX', 1000 );
24 * - Represents a title, which may contain an interwiki designation or namespace
25 * - Can fetch various kinds of data from the database, albeit inefficiently.
31 * All member variables should be considered private
32 * Please use the accessor functions
39 var $mTextform; # Text form (spaces not underscores) of the main part
40 var $mUrlform; # URL-encoded form of the main part
41 var $mDbkeyform; # Main part with underscores
42 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
43 var $mInterwiki; # Interwiki prefix (or null string)
44 var $mFragment; # Title fragment (i.e. the bit after the #)
45 var $mArticleID; # Article ID, fetched from the link cache on demand
46 var $mLatestID; # ID of most recent revision
47 var $mRestrictions; # Array of groups allowed to edit this article
48 # Only null or "sysop" are supported
49 var $mRestrictionsLoaded; # Boolean for initialisation on demand
50 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
51 var $mDefaultNamespace; # Namespace index when there is no namespace
52 # Zero except in {{transclusion}} tags
53 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
61 /* private */ function Title() {
62 $this->mInterwiki
= $this->mUrlform
=
63 $this->mTextform
= $this->mDbkeyform
= '';
64 $this->mArticleID
= -1;
65 $this->mNamespace
= NS_MAIN
;
66 $this->mRestrictionsLoaded
= false;
67 $this->mRestrictions
= array();
68 # Dont change the following, NS_MAIN is hardcoded in several place
70 $this->mDefaultNamespace
= NS_MAIN
;
71 $this->mWatched
= NULL;
72 $this->mLatestID
= false;
76 * Create a new Title from a prefixed DB key
77 * @param string $key The database key, which has underscores
78 * instead of spaces, possibly including namespace and
80 * @return Title the new object, or NULL on an error
84 /* static */ function newFromDBkey( $key ) {
86 $t->mDbkeyform
= $key;
87 if( $t->secureAndSplit() )
94 * Create a new Title from text, such as what one would
95 * find in a link. Decodes any HTML entities in the text.
97 * @param string $text the link text; spaces, prefixes,
98 * and an initial ':' indicating the main namespace
100 * @param int $defaultNamespace the namespace to use if
101 * none is specified by a prefix
102 * @return Title the new object, or NULL on an error
106 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
107 global $wgTitleCache;
108 $fname = 'Title::newFromText';
110 if( is_object( $text ) ) {
111 wfDebugDieBacktrace( 'Title::newFromText given an object' );
115 * Wiki pages often contain multiple links to the same page.
116 * Title normalization and parsing can become expensive on
117 * pages with many links, so we can save a little time by
120 * In theory these are value objects and won't get changed...
122 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
123 return $wgTitleCache[$text];
127 * Convert things like é ā or 〗 into real text...
129 $filteredText = Sanitizer
::decodeCharReferences( $text );
132 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
133 $t->mDefaultNamespace
= $defaultNamespace;
135 static $cachedcount = 0 ;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( $cachedcount >= MW_TITLECACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 $wgTitleCache = array();
144 $wgTitleCache[$text] =& $t;
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
161 function newFromURL( $url ) {
162 global $wgLegalTitleChars;
165 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
166 # but some URLs used it as a space replacement and they still come
167 # from some external search tools.
168 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
169 $url = str_replace( '+', ' ', $url );
172 $t->mDbkeyform
= str_replace( ' ', '_', $url );
173 if( $t->secureAndSplit() ) {
181 * Create a new Title from an article ID
183 * @todo This is inefficiently implemented, the page row is requested
184 * but not used for anything else
186 * @param int $id the page_id corresponding to the Title to create
187 * @return Title the new object, or NULL on an error
191 function newFromID( $id ) {
192 $fname = 'Title::newFromID';
193 $dbr =& wfGetDB( DB_SLAVE
);
194 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
195 array( 'page_id' => $id ), $fname );
196 if ( $row !== false ) {
197 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
205 * Create a new Title from a namespace index and a DB key.
206 * It's assumed that $ns and $title are *valid*, for instance when
207 * they came directly from the database or a special page name.
208 * For convenience, spaces are converted to underscores so that
209 * eg user_text fields can be used directly.
211 * @param int $ns the namespace of the article
212 * @param string $title the unprefixed database key form
213 * @return Title the new object
217 function &makeTitle( $ns, $title ) {
221 $t->mNamespace
= intval( $ns );
222 $t->mDbkeyform
= str_replace( ' ', '_', $title );
223 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
224 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
225 $t->mTextform
= str_replace( '_', ' ', $title );
230 * Create a new Title frrom a namespace index and a DB key.
231 * The parameters will be checked for validity, which is a bit slower
232 * than makeTitle() but safer for user-provided data.
234 * @param int $ns the namespace of the article
235 * @param string $title the database key form
236 * @return Title the new object, or NULL on an error
240 function makeTitleSafe( $ns, $title ) {
242 $t->mDbkeyform
= Title
::makeName( $ns, $title );
243 if( $t->secureAndSplit() ) {
251 * Create a new Title for the Main Page
254 * @return Title the new object
257 function newMainPage() {
258 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
262 * Create a new Title for a redirect
263 * @param string $text the redirect title text
264 * @return Title the new object, or NULL if the text is not a
269 function newFromRedirect( $text ) {
272 if ( $wgMwRedir->matchStart( $text ) ) {
273 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
274 # categories are escaped using : for example one can enter:
275 # #REDIRECT [[:Category:Music]]. Need to remove it.
276 if ( substr($m[1],0,1) == ':') {
277 # We don't want to keep the ':'
278 $m[1] = substr( $m[1], 1 );
281 $rt = Title
::newFromText( $m[1] );
282 # Disallow redirects to Special:Userlogout
283 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
291 #----------------------------------------------------------------------------
293 #----------------------------------------------------------------------------
296 * Get the prefixed DB key associated with an ID
297 * @param int $id the page_id of the article
298 * @return Title an object representing the article, or NULL
299 * if no such article was found
303 function nameOf( $id ) {
304 $fname = 'Title::nameOf';
305 $dbr =& wfGetDB( DB_SLAVE
);
307 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
308 if ( $s === false ) { return NULL; }
310 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
315 * Get a regex character class describing the legal characters in a link
316 * @return string the list of characters, not delimited
320 function legalChars() {
321 global $wgLegalTitleChars;
322 return $wgLegalTitleChars;
326 * Get a string representation of a title suitable for
327 * including in a search index
329 * @param int $ns a namespace index
330 * @param string $title text-form main part
331 * @return string a stripped-down title string ready for the
334 /* static */ function indexTitle( $ns, $title ) {
337 $lc = SearchEngine
::legalSearchChars() . '&#;';
338 $t = $wgContLang->stripForSearch( $title );
339 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
340 $t = strtolower( $t );
343 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
344 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
346 $t = preg_replace( "/\\s+/", ' ', $t );
348 if ( $ns == NS_IMAGE
) {
349 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
355 * Make a prefixed DB key from a DB key and a namespace index
356 * @param int $ns numerical representation of the namespace
357 * @param string $title the DB key form the title
358 * @return string the prefixed form of the title
360 /* static */ function makeName( $ns, $title ) {
363 $n = $wgContLang->getNsText( $ns );
364 return $n == '' ?
$title : "$n:$title";
368 * Returns the URL associated with an interwiki prefix
369 * @param string $key the interwiki prefix (e.g. "MeatBall")
370 * @return the associated URL, containing "$1", which should be
371 * replaced by an article title
375 function getInterwikiLink( $key ) {
376 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
377 global $wgInterwikiCache;
378 $fname = 'Title::getInterwikiLink';
380 $key = strtolower( $key );
382 $k = $wgDBname.':interwiki:'.$key;
383 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
384 return $wgTitleInterwikiCache[$k]->iw_url
;
387 if ($wgInterwikiCache) {
388 return Title
::getInterwikiCached( $key );
391 $s = $wgMemc->get( $k );
392 # Ignore old keys with no iw_local
393 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
394 $wgTitleInterwikiCache[$k] = $s;
398 $dbr =& wfGetDB( DB_SLAVE
);
399 $res = $dbr->select( 'interwiki',
400 array( 'iw_url', 'iw_local', 'iw_trans' ),
401 array( 'iw_prefix' => $key ), $fname );
406 $s = $dbr->fetchObject( $res );
408 # Cache non-existence: create a blank object and save it to memcached
414 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
415 $wgTitleInterwikiCache[$k] = $s;
421 * Fetch interwiki prefix data from local cache in constant database
423 * More logic is explained in DefaultSettings
425 * @return string URL of interwiki site
428 function getInterwikiCached( $key ) {
429 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
430 global $wgTitleInterwikiCache;
434 $db=dba_open($wgInterwikiCache,'r','cdb');
435 /* Resolve site name */
436 if ($wgInterwikiScopes>=3 and !$site) {
437 $site = dba_fetch("__sites:{$wgDBname}", $db);
439 $site = $wgInterwikiFallbackSite;
441 $value = dba_fetch("{$wgDBname}:{$key}", $db);
442 if ($value=='' and $wgInterwikiScopes>=3) {
444 $value = dba_fetch("_{$site}:{$key}", $db);
446 if ($value=='' and $wgInterwikiScopes>=2) {
448 $value = dba_fetch("__global:{$key}", $db);
457 list($local,$url)=explode(' ',$value,2);
459 $s->iw_local
=(int)$local;
461 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
465 * Determine whether the object refers to a page within
468 * @return bool TRUE if this is an in-project interwiki link
469 * or a wikilink, FALSE otherwise
473 global $wgTitleInterwikiCache, $wgDBname;
475 if ( $this->mInterwiki
!= '' ) {
476 # Make sure key is loaded into cache
477 $this->getInterwikiLink( $this->mInterwiki
);
478 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
479 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
486 * Determine whether the object refers to a page within
487 * this project and is transcludable.
489 * @return bool TRUE if this is transcludable
493 global $wgTitleInterwikiCache, $wgDBname;
495 if ($this->mInterwiki
== '')
497 # Make sure key is loaded into cache
498 $this->getInterwikiLink( $this->mInterwiki
);
499 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
500 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
504 * Update the page_touched field for an array of title objects
505 * @todo Inefficient unless the IDs are already loaded into the
507 * @param array $titles an array of Title objects to be touched
508 * @param string $timestamp the timestamp to use instead of the
509 * default current time
513 function touchArray( $titles, $timestamp = '' ) {
515 if ( count( $titles ) == 0 ) {
518 $dbw =& wfGetDB( DB_MASTER
);
519 if ( $timestamp == '' ) {
520 $timestamp = $dbw->timestamp();
523 $page = $dbw->tableName( 'page' );
524 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
527 foreach ( $titles as $title ) {
528 if ( $wgUseFileCache ) {
529 $cm = new CacheManager($title);
530 @unlink($cm->fileCacheName());
537 $sql .= $title->getArticleID();
541 $dbw->query( $sql, 'Title::touchArray' );
544 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
545 // do them in small chunks:
546 $fname = 'Title::touchArray';
547 foreach( $titles as $title ) {
548 $dbw->update( 'page',
549 array( 'page_touched' => $timestamp ),
551 'page_namespace' => $title->getNamespace(),
552 'page_title' => $title->getDBkey() ),
557 #----------------------------------------------------------------------------
559 #----------------------------------------------------------------------------
561 /** Simple accessors */
563 * Get the text form (spaces not underscores) of the main part
567 function getText() { return $this->mTextform
; }
569 * Get the URL-encoded form of the main part
573 function getPartialURL() { return $this->mUrlform
; }
575 * Get the main part with underscores
579 function getDBkey() { return $this->mDbkeyform
; }
581 * Get the namespace index, i.e. one of the NS_xxxx constants
585 function getNamespace() { return $this->mNamespace
; }
587 * Get the namespace text
591 function getNsText() {
593 return $wgContLang->getNsText( $this->mNamespace
);
596 * Get the namespace text of the subject (rather than talk) page
600 function getSubjectNsText() {
602 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
606 * Get the namespace text of the talk page
609 function getTalkNsText() {
611 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
615 * Could this title have a corresponding talk page?
619 return( Namespace::canTalk( $this->mNamespace
) );
623 * Get the interwiki prefix (or null string)
627 function getInterwiki() { return $this->mInterwiki
; }
629 * Get the Title fragment (i.e. the bit after the #)
633 function getFragment() { return $this->mFragment
; }
635 * Get the default namespace index, for when there is no namespace
639 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
642 * Get title for search index
643 * @return string a stripped-down title string ready for the
646 function getIndexTitle() {
647 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
651 * Get the prefixed database key form
652 * @return string the prefixed title, with underscores and
653 * any interwiki and namespace prefixes
656 function getPrefixedDBkey() {
657 $s = $this->prefix( $this->mDbkeyform
);
658 $s = str_replace( ' ', '_', $s );
663 * Get the prefixed title with spaces.
664 * This is the form usually used for display
665 * @return string the prefixed title, with spaces
668 function getPrefixedText() {
669 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
670 $s = $this->prefix( $this->mTextform
);
671 $s = str_replace( '_', ' ', $s );
672 $this->mPrefixedText
= $s;
674 return $this->mPrefixedText
;
678 * Get the prefixed title with spaces, plus any fragment
679 * (part beginning with '#')
680 * @return string the prefixed title, with spaces and
681 * the fragment, including '#'
684 function getFullText() {
685 $text = $this->getPrefixedText();
686 if( '' != $this->mFragment
) {
687 $text .= '#' . $this->mFragment
;
693 * Get the base name, i.e. the leftmost parts before the /
694 * @return string Base name
696 function getBaseText() {
697 global $wgNamespacesWithSubpages;
698 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
699 $parts = explode( '/', $this->getText() );
700 # Don't discard the real title if there's no subpage involved
701 if( count( $parts ) > 1 )
702 unset( $parts[ count( $parts ) - 1 ] );
703 return implode( '/', $parts );
705 return $this->getText();
710 * Get the lowest-level subpage name, i.e. the rightmost part after /
711 * @return string Subpage name
713 function getSubpageText() {
714 global $wgNamespacesWithSubpages;
715 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
716 $parts = explode( '/', $this->mTextform
);
717 return( $parts[ count( $parts ) - 1 ] );
719 return( $this->mTextform
);
724 * Get a URL-encoded form of the subpage text
725 * @return string URL-encoded subpage name
727 function getSubpageUrlForm() {
728 $text = $this->getSubpageText();
729 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
730 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
735 * Get a URL-encoded title (not an actual URL) including interwiki
736 * @return string the URL-encoded form
739 function getPrefixedURL() {
740 $s = $this->prefix( $this->mDbkeyform
);
741 $s = str_replace( ' ', '_', $s );
743 $s = wfUrlencode ( $s ) ;
745 # Cleaning up URL to make it look nice -- is this safe?
746 $s = str_replace( '%28', '(', $s );
747 $s = str_replace( '%29', ')', $s );
753 * Get a real URL referring to this title, with interwiki link and
756 * @param string $query an optional query string, not used
757 * for interwiki links
758 * @return string the URL
761 function getFullURL( $query = '' ) {
762 global $wgContLang, $wgServer, $wgRequest;
764 if ( '' == $this->mInterwiki
) {
765 $url = $this->getLocalUrl( $query );
767 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
768 // Correct fix would be to move the prepending elsewhere.
769 if ($wgRequest->getVal('action') != 'render') {
770 $url = $wgServer . $url;
773 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
775 $namespace = $wgContLang->getNsText( $this->mNamespace
);
776 if ( '' != $namespace ) {
777 # Can this actually happen? Interwikis shouldn't be parsed.
780 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
782 if( false === strpos( $url, '?' ) ) {
791 # Finally, add the fragment.
792 if ( '' != $this->mFragment
) {
793 $url .= '#' . $this->mFragment
;
796 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
801 * Get a URL with no fragment or server name. If this page is generated
802 * with action=render, $wgServer is prepended.
803 * @param string $query an optional query string; if not specified,
804 * $wgArticlePath will be used.
805 * @return string the URL
808 function getLocalURL( $query = '' ) {
809 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
811 if ( $this->isExternal() ) {
812 $url = $this->getFullURL();
814 // This is currently only used for edit section links in the
815 // context of interwiki transclusion. In theory we should
816 // append the query to the end of any existing query string,
817 // but interwiki transclusion is already broken in that case.
821 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
822 if ( $query == '' ) {
823 $url = str_replace( '$1', $dbkey, $wgArticlePath );
825 global $wgActionPaths;
827 if( !empty( $wgActionPaths ) &&
828 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
830 $action = urldecode( $matches[2] );
831 if( isset( $wgActionPaths[$action] ) ) {
832 $query = $matches[1];
833 if( isset( $matches[4] ) ) $query .= $matches[4];
834 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
835 if( $query != '' ) $url .= '?' . $query;
838 if ( $url === false ) {
839 if ( $query == '-' ) {
842 $url = "{$wgScript}?title={$dbkey}&{$query}";
846 // FIXME: this causes breakage in various places when we
847 // actually expected a local URL and end up with dupe prefixes.
848 if ($wgRequest->getVal('action') == 'render') {
849 $url = $wgServer . $url;
852 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
857 * Get an HTML-escaped version of the URL form, suitable for
858 * using in a link, without a server name or fragment
859 * @param string $query an optional query string
860 * @return string the URL
863 function escapeLocalURL( $query = '' ) {
864 return htmlspecialchars( $this->getLocalURL( $query ) );
868 * Get an HTML-escaped version of the URL form, suitable for
869 * using in a link, including the server name and fragment
871 * @return string the URL
872 * @param string $query an optional query string
875 function escapeFullURL( $query = '' ) {
876 return htmlspecialchars( $this->getFullURL( $query ) );
880 * Get the URL form for an internal link.
881 * - Used in various Squid-related code, in case we have a different
882 * internal hostname for the server from the exposed one.
884 * @param string $query an optional query string
885 * @return string the URL
888 function getInternalURL( $query = '' ) {
889 global $wgInternalServer;
890 $url = $wgInternalServer . $this->getLocalURL( $query );
891 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
896 * Get the edit URL for this Title
897 * @return string the URL, or a null string if this is an
901 function getEditURL() {
902 if ( '' != $this->mInterwiki
) { return ''; }
903 $s = $this->getLocalURL( 'action=edit' );
909 * Get the HTML-escaped displayable text form.
910 * Used for the title field in <a> tags.
911 * @return string the text, including any prefixes
914 function getEscapedText() {
915 return htmlspecialchars( $this->getPrefixedText() );
919 * Is this Title interwiki?
923 function isExternal() { return ( '' != $this->mInterwiki
); }
926 * Is this page "semi-protected" - the *only* protection is autoconfirm?
928 * @param string Action to check (default: edit)
931 function isSemiProtected( $action = 'edit' ) {
932 $restrictions = $this->getRestrictions( $action );
933 # We do a full compare because this could be an array
934 foreach( $restrictions as $restriction ) {
935 if( strtolower( $restriction ) != 'autoconfirmed' ) {
943 * Does the title correspond to a protected article?
944 * @param string $what the action the page is protected from,
945 * by default checks move and edit
949 function isProtected( $action = '' ) {
950 global $wgRestrictionLevels;
951 if ( -1 == $this->mNamespace
) { return true; }
953 if( $action == 'edit' ||
$action == '' ) {
954 $r = $this->getRestrictions( 'edit' );
955 foreach( $wgRestrictionLevels as $level ) {
956 if( in_array( $level, $r ) && $level != '' ) {
962 if( $action == 'move' ||
$action == '' ) {
963 $r = $this->getRestrictions( 'move' );
964 foreach( $wgRestrictionLevels as $level ) {
965 if( in_array( $level, $r ) && $level != '' ) {
975 * Is $wgUser is watching this page?
979 function userIsWatching() {
982 if ( is_null( $this->mWatched
) ) {
983 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
984 $this->mWatched
= false;
986 $this->mWatched
= $wgUser->isWatched( $this );
989 return $this->mWatched
;
993 * Can $wgUser perform $action this page?
994 * @param string $action action that permission needs to be checked for
998 function userCan($action) {
999 $fname = 'Title::userCan';
1000 wfProfileIn( $fname );
1005 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1006 if ( $result !== null ) {
1007 wfProfileOut( $fname );
1011 if( NS_SPECIAL
== $this->mNamespace
) {
1012 wfProfileOut( $fname );
1015 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1016 // from taking effect -ævar
1017 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1018 !$wgUser->isAllowed('editinterface') ) {
1019 wfProfileOut( $fname );
1023 if( $this->mDbkeyform
== '_' ) {
1024 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1025 wfProfileOut( $fname );
1029 # protect css/js subpages of user pages
1030 # XXX: this might be better using restrictions
1031 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1032 if( NS_USER
== $this->mNamespace
1033 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1034 && !$wgUser->isAllowed('editinterface')
1035 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1036 wfProfileOut( $fname );
1040 foreach( $this->getRestrictions($action) as $right ) {
1041 // Backwards compatibility, rewrite sysop -> protect
1042 if ( $right == 'sysop' ) {
1045 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1046 wfProfileOut( $fname );
1051 if( $action == 'move' &&
1052 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1053 wfProfileOut( $fname );
1057 if( $action == 'create' ) {
1058 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1059 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1064 wfProfileOut( $fname );
1069 * Can $wgUser edit this page?
1073 function userCanEdit() {
1074 return $this->userCan('edit');
1078 * Can $wgUser move this page?
1082 function userCanMove() {
1083 return $this->userCan('move');
1087 * Would anybody with sufficient privileges be able to move this page?
1088 * Some pages just aren't movable.
1093 function isMovable() {
1094 return Namespace::isMovable( $this->getNamespace() )
1095 && $this->getInterwiki() == '';
1099 * Can $wgUser read this page?
1103 function userCanRead() {
1107 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1108 if ( $result !== null ) {
1112 if( $wgUser->isAllowed('read') ) {
1115 global $wgWhitelistRead;
1117 /** If anon users can create an account,
1118 they need to reach the login page first! */
1119 if( $wgUser->isAllowed( 'createaccount' )
1120 && $this->getNamespace() == NS_SPECIAL
1121 && $this->getText() == 'Userlogin' ) {
1125 /** some pages are explicitly allowed */
1126 $name = $this->getPrefixedText();
1127 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1131 # Compatibility with old settings
1132 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1133 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1142 * Is this a talk page of some sort?
1146 function isTalkPage() {
1147 return Namespace::isTalk( $this->getNamespace() );
1151 * Is this a .css or .js subpage of a user page?
1155 function isCssJsSubpage() {
1156 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1159 * Is this a *valid* .css or .js subpage of a user page?
1160 * Check that the corresponding skin exists
1162 function isValidCssJsSubpage() {
1163 return( $this->isCssJsSubpage() && array_key_exists( $this->getSkinFromCssJsSubpage(), Skin
::getSkinNames() ) );
1166 * Trim down a .css or .js subpage title to get the corresponding skin name
1168 function getSkinFromCssJsSubpage() {
1169 $subpage = explode( '/', $this->mTextform
);
1170 $subpage = $subpage[ count( $subpage ) - 1 ];
1171 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1174 * Is this a .css subpage of a user page?
1178 function isCssSubpage() {
1179 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1182 * Is this a .js subpage of a user page?
1186 function isJsSubpage() {
1187 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1190 * Protect css/js subpages of user pages: can $wgUser edit
1194 * @todo XXX: this might be better using restrictions
1197 function userCanEditCssJsSubpage() {
1199 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1203 * Loads a string into mRestrictions array
1204 * @param string $res restrictions in string format
1207 function loadRestrictions( $res ) {
1208 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1209 $temp = explode( '=', trim( $restrict ) );
1210 if(count($temp) == 1) {
1211 // old format should be treated as edit/move restriction
1212 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1213 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1215 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1218 $this->mRestrictionsLoaded
= true;
1222 * Accessor/initialisation for mRestrictions
1223 * @param string $action action that permission needs to be checked for
1224 * @return array the array of groups allowed to edit this article
1227 function getRestrictions($action) {
1228 $id = $this->getArticleID();
1229 if ( 0 == $id ) { return array(); }
1231 if ( ! $this->mRestrictionsLoaded
) {
1232 $dbr =& wfGetDB( DB_SLAVE
);
1233 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1234 $this->loadRestrictions( $res );
1236 if( isset( $this->mRestrictions
[$action] ) ) {
1237 return $this->mRestrictions
[$action];
1243 * Is there a version of this page in the deletion archive?
1244 * @return int the number of archived revisions
1247 function isDeleted() {
1248 $fname = 'Title::isDeleted';
1249 if ( $this->getNamespace() < 0 ) {
1252 $dbr =& wfGetDB( DB_SLAVE
);
1253 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1254 'ar_title' => $this->getDBkey() ), $fname );
1260 * Get the article ID for this Title from the link cache,
1261 * adding it if necessary
1262 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1264 * @return int the ID
1267 function getArticleID( $flags = 0 ) {
1268 $linkCache =& LinkCache
::singleton();
1269 if ( $flags & GAID_FOR_UPDATE
) {
1270 $oldUpdate = $linkCache->forUpdate( true );
1271 $this->mArticleID
= $linkCache->addLinkObj( $this );
1272 $linkCache->forUpdate( $oldUpdate );
1274 if ( -1 == $this->mArticleID
) {
1275 $this->mArticleID
= $linkCache->addLinkObj( $this );
1278 return $this->mArticleID
;
1281 function getLatestRevID() {
1282 if ($this->mLatestID
!== false)
1283 return $this->mLatestID
;
1285 $db =& wfGetDB(DB_SLAVE
);
1286 return $this->mLatestID
= $db->selectField( 'revision',
1288 array('rev_page' => $this->getArticleID()),
1289 'Title::getLatestRevID' );
1293 * This clears some fields in this object, and clears any associated
1294 * keys in the "bad links" section of the link cache.
1296 * - This is called from Article::insertNewArticle() to allow
1297 * loading of the new page_id. It's also called from
1298 * Article::doDeleteArticle()
1300 * @param int $newid the new Article ID
1303 function resetArticleID( $newid ) {
1304 $linkCache =& LinkCache
::singleton();
1305 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1307 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1308 else { $this->mArticleID
= $newid; }
1309 $this->mRestrictionsLoaded
= false;
1310 $this->mRestrictions
= array();
1314 * Updates page_touched for this page; called from LinksUpdate.php
1315 * @return bool true if the update succeded
1318 function invalidateCache() {
1319 global $wgUseFileCache;
1321 if ( wfReadOnly() ) {
1325 $dbw =& wfGetDB( DB_MASTER
);
1326 $success = $dbw->update( 'page',
1328 'page_touched' => $dbw->timestamp()
1329 ), array( /* WHERE */
1330 'page_namespace' => $this->getNamespace() ,
1331 'page_title' => $this->getDBkey()
1332 ), 'Title::invalidateCache'
1335 if ($wgUseFileCache) {
1336 $cache = new CacheManager($this);
1337 @unlink
($cache->fileCacheName());
1344 * Prefix some arbitrary text with the namespace or interwiki prefix
1347 * @param string $name the text
1348 * @return string the prefixed text
1351 /* private */ function prefix( $name ) {
1355 if ( '' != $this->mInterwiki
) {
1356 $p = $this->mInterwiki
. ':';
1358 if ( 0 != $this->mNamespace
) {
1359 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1365 * Secure and split - main initialisation function for this object
1367 * Assumes that mDbkeyform has been set, and is urldecoded
1368 * and uses underscores, but not otherwise munged. This function
1369 * removes illegal characters, splits off the interwiki and
1370 * namespace prefixes, sets the other forms, and canonicalizes
1372 * @return bool true on success
1375 /* private */ function secureAndSplit() {
1376 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1377 $fname = 'Title::secureAndSplit';
1380 static $rxTc = false;
1382 # % is needed as well
1383 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1386 $this->mInterwiki
= $this->mFragment
= '';
1387 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1389 # Clean up whitespace
1391 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1392 $t = trim( $t, '_' );
1398 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1399 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1403 $this->mDbkeyform
= $t;
1405 # Initial colon indicates main namespace rather than specified default
1406 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1407 if ( ':' == $t{0} ) {
1408 $this->mNamespace
= NS_MAIN
;
1409 $t = substr( $t, 1 ); # remove the colon but continue processing
1412 # Namespace or interwiki prefix
1415 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1417 $lowerNs = strtolower( $p );
1418 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1419 # Canonical namespace
1421 $this->mNamespace
= $ns;
1422 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1423 # Ordinary namespace
1425 $this->mNamespace
= $ns;
1426 } elseif( $this->getInterwikiLink( $p ) ) {
1428 # Can't make a local interwiki link to an interwiki link.
1429 # That's just crazy!
1435 $this->mInterwiki
= strtolower( $p );
1437 # Redundant interwiki prefix to the local wiki
1438 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1440 # Can't have an empty self-link
1443 $this->mInterwiki
= '';
1445 # Do another namespace split...
1449 # If there's an initial colon after the interwiki, that also
1450 # resets the default namespace
1451 if ( $t !== '' && $t[0] == ':' ) {
1452 $this->mNamespace
= NS_MAIN
;
1453 $t = substr( $t, 1 );
1456 # If there's no recognized interwiki or namespace,
1457 # then let the colon expression be part of the title.
1463 # We already know that some pages won't be in the database!
1465 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1466 $this->mArticleID
= 0;
1468 $f = strstr( $r, '#' );
1469 if ( false !== $f ) {
1470 $this->mFragment
= substr( $f, 1 );
1471 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1472 # remove whitespace again: prevents "Foo_bar_#"
1473 # becoming "Foo_bar_"
1474 $r = preg_replace( '/_*$/', '', $r );
1477 # Reject illegal characters.
1479 if( preg_match( $rxTc, $r ) ) {
1484 * Pages with "/./" or "/../" appearing in the URLs will
1485 * often be unreachable due to the way web browsers deal
1486 * with 'relative' URLs. Forbid them explicitly.
1488 if ( strpos( $r, '.' ) !== false &&
1489 ( $r === '.' ||
$r === '..' ||
1490 strpos( $r, './' ) === 0 ||
1491 strpos( $r, '../' ) === 0 ||
1492 strpos( $r, '/./' ) !== false ||
1493 strpos( $r, '/../' ) !== false ) )
1498 # We shouldn't need to query the DB for the size.
1499 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1500 if ( strlen( $r ) > 255 ) {
1505 * Normally, all wiki links are forced to have
1506 * an initial capital letter so [[foo]] and [[Foo]]
1507 * point to the same place.
1509 * Don't force it for interwikis, since the other
1510 * site might be case-sensitive.
1512 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1513 $t = $wgContLang->ucfirst( $r );
1519 * Can't make a link to a namespace alone...
1520 * "empty" local links can only be self-links
1521 * with a fragment identifier.
1524 $this->mInterwiki
== '' &&
1525 $this->mNamespace
!= NS_MAIN
) {
1529 // Any remaining initial :s are illegal.
1530 if ( $t !== '' && ':' == $t{0} ) {
1535 $this->mDbkeyform
= $t;
1536 $this->mUrlform
= wfUrlencode( $t );
1538 $this->mTextform
= str_replace( '_', ' ', $t );
1544 * Get a Title object associated with the talk page of this article
1545 * @return Title the object for the talk page
1548 function getTalkPage() {
1549 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1553 * Get a title object associated with the subject page of this
1556 * @return Title the object for the subject page
1559 function getSubjectPage() {
1560 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1564 * Get an array of Title objects linking to this Title
1565 * Also stores the IDs in the link cache.
1567 * @param string $options may be FOR UPDATE
1568 * @return array the Title objects linking here
1571 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1572 $linkCache =& LinkCache
::singleton();
1573 $id = $this->getArticleID();
1576 $db =& wfGetDB( DB_MASTER
);
1578 $db =& wfGetDB( DB_SLAVE
);
1581 $res = $db->select( array( 'page', $table ),
1582 array( 'page_namespace', 'page_title', 'page_id' ),
1584 "{$prefix}_from=page_id",
1585 "{$prefix}_namespace" => $this->getNamespace(),
1586 "{$prefix}_title" => $this->getDbKey() ),
1587 'Title::getLinksTo',
1591 if ( $db->numRows( $res ) ) {
1592 while ( $row = $db->fetchObject( $res ) ) {
1593 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1594 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1595 $retVal[] = $titleObj;
1599 $db->freeResult( $res );
1604 * Get an array of Title objects using this Title as a template
1605 * Also stores the IDs in the link cache.
1607 * @param string $options may be FOR UPDATE
1608 * @return array the Title objects linking here
1611 function getTemplateLinksTo( $options = '' ) {
1612 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1616 * Get an array of Title objects referring to non-existent articles linked from this page
1618 * @param string $options may be FOR UPDATE
1619 * @return array the Title objects
1622 function getBrokenLinksFrom( $options = '' ) {
1624 $db =& wfGetDB( DB_MASTER
);
1626 $db =& wfGetDB( DB_SLAVE
);
1629 $res = $db->safeQuery(
1630 "SELECT pl_namespace, pl_title
1633 ON pl_namespace=page_namespace
1634 AND pl_title=page_title
1636 AND page_namespace IS NULL
1638 $db->tableName( 'pagelinks' ),
1639 $db->tableName( 'page' ),
1640 $this->getArticleId(),
1644 if ( $db->numRows( $res ) ) {
1645 while ( $row = $db->fetchObject( $res ) ) {
1646 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1649 $db->freeResult( $res );
1655 * Get a list of URLs to purge from the Squid cache when this
1658 * @return array the URLs
1661 function getSquidURLs() {
1663 $this->getInternalURL(),
1664 $this->getInternalURL( 'action=history' )
1669 * Move this page without authentication
1670 * @param Title &$nt the new page Title
1673 function moveNoAuth( &$nt ) {
1674 return $this->moveTo( $nt, false );
1678 * Check whether a given move operation would be valid.
1679 * Returns true if ok, or a message key string for an error message
1680 * if invalid. (Scarrrrry ugly interface this.)
1681 * @param Title &$nt the new title
1682 * @param bool $auth indicates whether $wgUser's permissions
1684 * @return mixed true on success, message name on failure
1687 function isValidMoveOperation( &$nt, $auth = true ) {
1688 if( !$this or !$nt ) {
1689 return 'badtitletext';
1691 if( $this->equals( $nt ) ) {
1694 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1695 return 'immobile_namespace';
1698 $oldid = $this->getArticleID();
1699 $newid = $nt->getArticleID();
1701 if ( strlen( $nt->getDBkey() ) < 1 ) {
1702 return 'articleexists';
1704 if ( ( '' == $this->getDBkey() ) ||
1706 ( '' == $nt->getDBkey() ) ) {
1707 return 'badarticleerror';
1711 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1712 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1713 return 'protectedpage';
1716 # The move is allowed only if (1) the target doesn't exist, or
1717 # (2) the target is a redirect to the source, and has no history
1718 # (so we can undo bad moves right after they're done).
1720 if ( 0 != $newid ) { # Target exists; check for validity
1721 if ( ! $this->isValidMoveTarget( $nt ) ) {
1722 return 'articleexists';
1729 * Move a title to a new location
1730 * @param Title &$nt the new title
1731 * @param bool $auth indicates whether $wgUser's permissions
1733 * @return mixed true on success, message name on failure
1736 function moveTo( &$nt, $auth = true, $reason = '' ) {
1737 $err = $this->isValidMoveOperation( $nt, $auth );
1738 if( is_string( $err ) ) {
1742 $pageid = $this->getArticleID();
1743 if( $nt->exists() ) {
1744 $this->moveOverExistingRedirect( $nt, $reason );
1745 $pageCountChange = 0;
1746 } else { # Target didn't exist, do normal move.
1747 $this->moveToNewTitle( $nt, $reason );
1748 $pageCountChange = 1;
1750 $redirid = $this->getArticleID();
1752 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1753 $dbw =& wfGetDB( DB_MASTER
);
1754 $categorylinks = $dbw->tableName( 'categorylinks' );
1755 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1756 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1757 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1758 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1762 $oldnamespace = $this->getNamespace() & ~
1;
1763 $newnamespace = $nt->getNamespace() & ~
1;
1764 $oldtitle = $this->getDBkey();
1765 $newtitle = $nt->getDBkey();
1767 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1768 WatchedItem
::duplicateEntries( $this, $nt );
1771 # Update search engine
1772 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1774 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1778 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1779 # Moved out of main namespace
1780 # not viewed, edited, removing
1781 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1782 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1783 # Moved into main namespace
1784 # not viewed, edited, adding
1785 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1786 } elseif ( $pageCountChange ) {
1788 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1797 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1802 * Move page to a title which is at present a redirect to the
1805 * @param Title &$nt the page to move to, which should currently
1809 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1810 global $wgUseSquid, $wgMwRedir;
1811 $fname = 'Title::moveOverExistingRedirect';
1812 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1815 $comment .= ": $reason";
1818 $now = wfTimestampNow();
1820 $newid = $nt->getArticleID();
1821 $oldid = $this->getArticleID();
1822 $dbw =& wfGetDB( DB_MASTER
);
1823 $linkCache =& LinkCache
::singleton();
1825 # Delete the old redirect. We don't save it to history since
1826 # by definition if we've got here it's rather uninteresting.
1827 # We have to remove it so that the next step doesn't trigger
1828 # a conflict on the unique namespace+title index...
1829 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1831 # Save a null revision in the page's history notifying of the move
1832 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1833 $nullRevId = $nullRevision->insertOn( $dbw );
1835 # Change the name of the target page:
1836 $dbw->update( 'page',
1838 'page_touched' => $dbw->timestamp($now),
1839 'page_namespace' => $nt->getNamespace(),
1840 'page_title' => $nt->getDBkey(),
1841 'page_latest' => $nullRevId,
1843 /* WHERE */ array( 'page_id' => $oldid ),
1846 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1848 # Recreate the redirect, this time in the other direction.
1849 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1850 $redirectArticle = new Article( $this );
1851 $newid = $redirectArticle->insertOn( $dbw );
1852 $redirectRevision = new Revision( array(
1854 'comment' => $comment,
1855 'text' => $redirectText ) );
1856 $revid = $redirectRevision->insertOn( $dbw );
1857 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1858 $linkCache->clearLink( $this->getPrefixedDBkey() );
1861 $log = new LogPage( 'move' );
1862 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1864 # Now, we record the link from the redirect to the new title.
1865 # It should have no other outgoing links...
1866 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1867 $dbw->insert( 'pagelinks',
1869 'pl_from' => $newid,
1870 'pl_namespace' => $nt->getNamespace(),
1871 'pl_title' => $nt->getDbKey() ),
1875 if ( $wgUseSquid ) {
1876 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1877 $u = new SquidUpdate( $urls );
1883 * Move page to non-existing title.
1884 * @param Title &$nt the new Title
1887 function moveToNewTitle( &$nt, $reason = '' ) {
1890 $fname = 'MovePageForm::moveToNewTitle';
1891 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1893 $comment .= ": $reason";
1896 $newid = $nt->getArticleID();
1897 $oldid = $this->getArticleID();
1898 $dbw =& wfGetDB( DB_MASTER
);
1899 $now = $dbw->timestamp();
1901 $linkCache =& LinkCache
::singleton();
1903 # Save a null revision in the page's history notifying of the move
1904 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1905 $nullRevId = $nullRevision->insertOn( $dbw );
1908 $dbw->update( 'page',
1910 'page_touched' => $now,
1911 'page_namespace' => $nt->getNamespace(),
1912 'page_title' => $nt->getDBkey(),
1913 'page_latest' => $nullRevId,
1915 /* WHERE */ array( 'page_id' => $oldid ),
1919 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1922 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1923 $redirectArticle = new Article( $this );
1924 $newid = $redirectArticle->insertOn( $dbw );
1925 $redirectRevision = new Revision( array(
1927 'comment' => $comment,
1928 'text' => $redirectText ) );
1929 $revid = $redirectRevision->insertOn( $dbw );
1930 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1931 $linkCache->clearLink( $this->getPrefixedDBkey() );
1934 $log = new LogPage( 'move' );
1935 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1937 # Purge caches as per article creation
1938 Article
::onArticleCreate( $nt );
1940 # Record the just-created redirect's linking to the page
1941 $dbw->insert( 'pagelinks',
1943 'pl_from' => $newid,
1944 'pl_namespace' => $nt->getNamespace(),
1945 'pl_title' => $nt->getDBkey() ),
1948 # Non-existent target may have had broken links to it; these must
1949 # now be touched to update link coloring.
1952 # Purge old title from squid
1953 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1954 $titles = $nt->getLinksTo();
1955 if ( $wgUseSquid ) {
1956 $urls = $this->getSquidURLs();
1957 foreach ( $titles as $linkTitle ) {
1958 $urls[] = $linkTitle->getInternalURL();
1960 $u = new SquidUpdate( $urls );
1966 * Checks if $this can be moved to a given Title
1967 * - Selects for update, so don't call it unless you mean business
1969 * @param Title &$nt the new title to check
1972 function isValidMoveTarget( $nt ) {
1974 $fname = 'Title::isValidMoveTarget';
1975 $dbw =& wfGetDB( DB_MASTER
);
1978 $id = $nt->getArticleID();
1979 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1980 array( 'page_is_redirect','old_text','old_flags' ),
1981 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1982 $fname, 'FOR UPDATE' );
1984 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1988 $text = Revision
::getRevisionText( $obj );
1990 # Does the redirect point to the source?
1991 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1992 $redirTitle = Title
::newFromText( $m[1] );
1993 if( !is_object( $redirTitle ) ||
1994 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
2002 # Does the article have a history?
2003 $row = $dbw->selectRow( array( 'page', 'revision'),
2005 array( 'page_namespace' => $nt->getNamespace(),
2006 'page_title' => $nt->getDBkey(),
2007 'page_id=rev_page AND page_latest != rev_id'
2008 ), $fname, 'FOR UPDATE'
2011 # Return true if there was no history
2012 return $row === false;
2016 * Create a redirect; fails if the title already exists; does
2019 * @param Title $dest the destination of the redirect
2020 * @param string $comment the comment string describing the move
2021 * @return bool true on success
2024 function createRedirect( $dest, $comment ) {
2025 if ( $this->getArticleID() ) {
2029 $fname = 'Title::createRedirect';
2030 $dbw =& wfGetDB( DB_MASTER
);
2032 $article = new Article( $this );
2033 $newid = $article->insertOn( $dbw );
2034 $revision = new Revision( array(
2036 'comment' => $comment,
2037 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2039 $revisionId = $revision->insertOn( $dbw );
2040 $article->updateRevisionOn( $dbw, $revision, 0 );
2043 $dbw->insert( 'pagelinks',
2045 'pl_from' => $newid,
2046 'pl_namespace' => $dest->getNamespace(),
2047 'pl_title' => $dest->getDbKey()
2051 Article
::onArticleCreate( $this );
2056 * Get categories to which this Title belongs and return an array of
2057 * categories' names.
2059 * @return array an array of parents in the form:
2060 * $parent => $currentarticle
2063 function getParentCategories() {
2066 $titlekey = $this->getArticleId();
2067 $dbr =& wfGetDB( DB_SLAVE
);
2068 $categorylinks = $dbr->tableName( 'categorylinks' );
2071 $sql = "SELECT * FROM $categorylinks"
2072 ." WHERE cl_from='$titlekey'"
2073 ." AND cl_from <> '0'"
2074 ." ORDER BY cl_sortkey";
2076 $res = $dbr->query ( $sql ) ;
2078 if($dbr->numRows($res) > 0) {
2079 while ( $x = $dbr->fetchObject ( $res ) )
2080 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2081 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2082 $dbr->freeResult ( $res ) ;
2090 * Get a tree of parent categories
2091 * @param array $children an array with the children in the keys, to check for circular refs
2095 function getParentCategoryTree( $children = array() ) {
2096 $parents = $this->getParentCategories();
2098 if($parents != '') {
2099 foreach($parents as $parent => $current) {
2100 if ( array_key_exists( $parent, $children ) ) {
2101 # Circular reference
2102 $stack[$parent] = array();
2104 $nt = Title
::newFromText($parent);
2105 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2116 * Get an associative array for selecting this title from
2122 function pageCond() {
2123 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2127 * Get the revision ID of the previous revision
2129 * @param integer $revision Revision ID. Get the revision that was before this one.
2130 * @return interger $oldrevision|false
2132 function getPreviousRevisionID( $revision ) {
2133 $dbr =& wfGetDB( DB_SLAVE
);
2134 return $dbr->selectField( 'revision', 'rev_id',
2135 'rev_page=' . intval( $this->getArticleId() ) .
2136 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2140 * Get the revision ID of the next revision
2142 * @param integer $revision Revision ID. Get the revision that was after this one.
2143 * @return interger $oldrevision|false
2145 function getNextRevisionID( $revision ) {
2146 $dbr =& wfGetDB( DB_SLAVE
);
2147 return $dbr->selectField( 'revision', 'rev_id',
2148 'rev_page=' . intval( $this->getArticleId() ) .
2149 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2153 * Compare with another title.
2155 * @param Title $title
2158 function equals( $title ) {
2159 // Note: === is necessary for proper matching of number-like titles.
2160 return $this->getInterwiki() === $title->getInterwiki()
2161 && $this->getNamespace() == $title->getNamespace()
2162 && $this->getDbkey() === $title->getDbkey();
2166 * Check if page exists
2170 return $this->getArticleId() != 0;
2174 * Should a link should be displayed as a known link, just based on its title?
2176 * Currently, a self-link with a fragment and special pages are in
2177 * this category. Special pages never exist in the database.
2179 function isAlwaysKnown() {
2180 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2181 || NS_SPECIAL
== $this->mNamespace
;
2185 * Update page_touched timestamps on pages linking to this title.
2186 * In principal, this could be backgrounded and could also do squid
2189 function touchLinks() {
2190 $fname = 'Title::touchLinks';
2192 $dbw =& wfGetDB( DB_MASTER
);
2194 $res = $dbw->select( 'pagelinks',
2197 'pl_namespace' => $this->getNamespace(),
2198 'pl_title' => $this->getDbKey() ),
2201 $toucharr = array();
2202 while( $row = $dbw->fetchObject( $res ) ) {
2203 $toucharr[] = $row->pl_from
;
2205 $dbw->freeResult( $res );
2207 if( $this->getNamespace() == NS_CATEGORY
) {
2208 // Categories show up in a separate set of links as well
2209 $res = $dbw->select( 'categorylinks',
2211 array( 'cl_to' => $this->getDbKey() ),
2213 while( $row = $dbw->fetchObject( $res ) ) {
2214 $toucharr[] = $row->cl_from
;
2216 $dbw->freeResult( $res );
2219 if (!count($toucharr))
2221 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2222 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2225 function trackbackURL() {
2226 global $wgTitle, $wgScriptPath, $wgServer;
2228 return "$wgServer$wgScriptPath/trackback.php?article="
2229 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2232 function trackbackRDF() {
2233 $url = htmlspecialchars($this->getFullURL());
2234 $title = htmlspecialchars($this->getText());
2235 $tburl = $this->trackbackURL();
2238 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2239 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2240 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2243 dc:identifier=\"$url\"
2245 trackback:ping=\"$tburl\" />
2250 * Generate strings used for xml 'id' names in monobook tabs
2253 function getNamespaceKey() {
2254 switch ($this->getNamespace()) {
2257 return 'nstab-main';
2260 return 'nstab-user';
2262 return 'nstab-media';
2264 return 'nstab-special';
2266 case NS_PROJECT_TALK
:
2267 return 'nstab-project';
2270 return 'nstab-image';
2272 case NS_MEDIAWIKI_TALK
:
2273 return 'nstab-mediawiki';
2275 case NS_TEMPLATE_TALK
:
2276 return 'nstab-template';
2279 return 'nstab-help';
2281 case NS_CATEGORY_TALK
:
2282 return 'nstab-category';
2284 return 'nstab-' . strtolower( $this->getSubjectNsText() );