9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 $wgTitleCache = array();
14 define ( 'GAID_FOR_UPDATE', 1 );
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
21 define( 'MW_TITLECACHE_MAX', 1000 );
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
32 * All member variables should be considered private
33 * Please use the accessor functions
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
62 /* private */ function Title() {
63 $this->mInterwiki
= $this->mUrlform
=
64 $this->mTextform
= $this->mDbkeyform
= '';
65 $this->mArticleID
= -1;
66 $this->mNamespace
= NS_MAIN
;
67 $this->mRestrictionsLoaded
= false;
68 $this->mRestrictions
= array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
71 $this->mDefaultNamespace
= NS_MAIN
;
72 $this->mWatched
= NULL;
73 $this->mLatestID
= false;
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
81 * @return Title the new object, or NULL on an error
85 /* static */ function newFromDBkey( $key ) {
87 $t->mDbkeyform
= $key;
88 if( $t->secureAndSplit() )
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
107 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
111 if( is_object( $text ) ) {
112 wfDebugDieBacktrace( 'Title::newFromText given an object' );
116 * Wiki pages often contain multiple links to the same page.
117 * Title normalization and parsing can become expensive on
118 * pages with many links, so we can save a little time by
121 * In theory these are value objects and won't get changed...
123 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
124 return $wgTitleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 static $cachedcount = 0 ;
137 if( $t->secureAndSplit() ) {
138 if( $defaultNamespace == NS_MAIN
) {
139 if( $cachedcount >= MW_TITLECACHE_MAX
) {
140 # Avoid memory leaks on mass operations...
141 $wgTitleCache = array();
145 $wgTitleCache[$text] =& $t;
155 * Create a new Title from URL-encoded text. Ensures that
156 * the given title's length does not exceed the maximum.
157 * @param string $url the title, as might be taken from a URL
158 * @return Title the new object, or NULL on an error
162 function newFromURL( $url ) {
163 global $wgLegalTitleChars;
166 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
167 # but some URLs used it as a space replacement and they still come
168 # from some external search tools.
169 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
170 $url = str_replace( '+', ' ', $url );
173 $t->mDbkeyform
= str_replace( ' ', '_', $url );
174 if( $t->secureAndSplit() ) {
182 * Create a new Title from an article ID
184 * @todo This is inefficiently implemented, the page row is requested
185 * but not used for anything else
187 * @param int $id the page_id corresponding to the Title to create
188 * @return Title the new object, or NULL on an error
192 function newFromID( $id ) {
193 $fname = 'Title::newFromID';
194 $dbr =& wfGetDB( DB_SLAVE
);
195 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
196 array( 'page_id' => $id ), $fname );
197 if ( $row !== false ) {
198 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
206 * Create a new Title from a namespace index and a DB key.
207 * It's assumed that $ns and $title are *valid*, for instance when
208 * they came directly from the database or a special page name.
209 * For convenience, spaces are converted to underscores so that
210 * eg user_text fields can be used directly.
212 * @param int $ns the namespace of the article
213 * @param string $title the unprefixed database key form
214 * @return Title the new object
218 function &makeTitle( $ns, $title ) {
222 $t->mNamespace
= intval( $ns );
223 $t->mDbkeyform
= str_replace( ' ', '_', $title );
224 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
225 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
226 $t->mTextform
= str_replace( '_', ' ', $title );
231 * Create a new Title frrom a namespace index and a DB key.
232 * The parameters will be checked for validity, which is a bit slower
233 * than makeTitle() but safer for user-provided data.
235 * @param int $ns the namespace of the article
236 * @param string $title the database key form
237 * @return Title the new object, or NULL on an error
241 function makeTitleSafe( $ns, $title ) {
243 $t->mDbkeyform
= Title
::makeName( $ns, $title );
244 if( $t->secureAndSplit() ) {
252 * Create a new Title for the Main Page
255 * @return Title the new object
258 function newMainPage() {
259 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
263 * Create a new Title for a redirect
264 * @param string $text the redirect title text
265 * @return Title the new object, or NULL if the text is not a
270 function newFromRedirect( $text ) {
273 if ( $wgMwRedir->matchStart( $text ) ) {
274 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
275 # categories are escaped using : for example one can enter:
276 # #REDIRECT [[:Category:Music]]. Need to remove it.
277 if ( substr($m[1],0,1) == ':') {
278 # We don't want to keep the ':'
279 $m[1] = substr( $m[1], 1 );
282 $rt = Title
::newFromText( $m[1] );
283 # Disallow redirects to Special:Userlogout
284 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
292 #----------------------------------------------------------------------------
294 #----------------------------------------------------------------------------
297 * Get the prefixed DB key associated with an ID
298 * @param int $id the page_id of the article
299 * @return Title an object representing the article, or NULL
300 * if no such article was found
304 function nameOf( $id ) {
305 $fname = 'Title::nameOf';
306 $dbr =& wfGetDB( DB_SLAVE
);
308 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
309 if ( $s === false ) { return NULL; }
311 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
316 * Get a regex character class describing the legal characters in a link
317 * @return string the list of characters, not delimited
321 function legalChars() {
322 global $wgLegalTitleChars;
323 return $wgLegalTitleChars;
327 * Get a string representation of a title suitable for
328 * including in a search index
330 * @param int $ns a namespace index
331 * @param string $title text-form main part
332 * @return string a stripped-down title string ready for the
335 /* static */ function indexTitle( $ns, $title ) {
337 require_once( 'SearchEngine.php' );
339 $lc = SearchEngine
::legalSearchChars() . '&#;';
340 $t = $wgContLang->stripForSearch( $title );
341 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
342 $t = strtolower( $t );
345 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
346 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
348 $t = preg_replace( "/\\s+/", ' ', $t );
350 if ( $ns == NS_IMAGE
) {
351 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
357 * Make a prefixed DB key from a DB key and a namespace index
358 * @param int $ns numerical representation of the namespace
359 * @param string $title the DB key form the title
360 * @return string the prefixed form of the title
362 /* static */ function makeName( $ns, $title ) {
365 $n = $wgContLang->getNsText( $ns );
366 return $n == '' ?
$title : "$n:$title";
370 * Returns the URL associated with an interwiki prefix
371 * @param string $key the interwiki prefix (e.g. "MeatBall")
372 * @return the associated URL, containing "$1", which should be
373 * replaced by an article title
377 function getInterwikiLink( $key ) {
378 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
379 global $wgInterwikiCache;
380 $fname = 'Title::getInterwikiLink';
382 $key = strtolower( $key );
384 $k = $wgDBname.':interwiki:'.$key;
385 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
386 return $wgTitleInterwikiCache[$k]->iw_url
;
389 if ($wgInterwikiCache) {
390 return Title
::getInterwikiCached( $key );
393 $s = $wgMemc->get( $k );
394 # Ignore old keys with no iw_local
395 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
396 $wgTitleInterwikiCache[$k] = $s;
400 $dbr =& wfGetDB( DB_SLAVE
);
401 $res = $dbr->select( 'interwiki',
402 array( 'iw_url', 'iw_local', 'iw_trans' ),
403 array( 'iw_prefix' => $key ), $fname );
408 $s = $dbr->fetchObject( $res );
410 # Cache non-existence: create a blank object and save it to memcached
416 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
417 $wgTitleInterwikiCache[$k] = $s;
423 * Fetch interwiki prefix data from local cache in constant database
425 * More logic is explained in DefaultSettings
427 * @return string URL of interwiki site
430 function getInterwikiCached( $key ) {
431 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
432 global $wgTitleInterwikiCache;
436 $db=dba_open($wgInterwikiCache,'r','cdb');
437 /* Resolve site name */
438 if ($wgInterwikiScopes>=3 and !$site) {
439 $site = dba_fetch("__sites:{$wgDBname}", $db);
441 $site = $wgInterwikiFallbackSite;
443 $value = dba_fetch("{$wgDBname}:{$key}", $db);
444 if ($value=='' and $wgInterwikiScopes>=3) {
446 $value = dba_fetch("_{$site}:{$key}", $db);
448 if ($value=='' and $wgInterwikiScopes>=2) {
450 $value = dba_fetch("__global:{$key}", $db);
459 list($local,$url)=explode(' ',$value,2);
461 $s->iw_local
=(int)$local;
463 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
467 * Determine whether the object refers to a page within
470 * @return bool TRUE if this is an in-project interwiki link
471 * or a wikilink, FALSE otherwise
475 global $wgTitleInterwikiCache, $wgDBname;
477 if ( $this->mInterwiki
!= '' ) {
478 # Make sure key is loaded into cache
479 $this->getInterwikiLink( $this->mInterwiki
);
480 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
481 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return bool TRUE if this is transcludable
495 global $wgTitleInterwikiCache, $wgDBname;
497 if ($this->mInterwiki
== '')
499 # Make sure key is loaded into cache
500 $this->getInterwikiLink( $this->mInterwiki
);
501 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
502 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
506 * Update the page_touched field for an array of title objects
507 * @todo Inefficient unless the IDs are already loaded into the
509 * @param array $titles an array of Title objects to be touched
510 * @param string $timestamp the timestamp to use instead of the
511 * default current time
515 function touchArray( $titles, $timestamp = '' ) {
517 if ( count( $titles ) == 0 ) {
520 $dbw =& wfGetDB( DB_MASTER
);
521 if ( $timestamp == '' ) {
522 $timestamp = $dbw->timestamp();
525 $page = $dbw->tableName( 'page' );
526 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
529 foreach ( $titles as $title ) {
530 if ( $wgUseFileCache ) {
531 $cm = new CacheManager($title);
532 @unlink($cm->fileCacheName());
539 $sql .= $title->getArticleID();
543 $dbw->query( $sql, 'Title::touchArray' );
546 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
547 // do them in small chunks:
548 $fname = 'Title::touchArray';
549 foreach( $titles as $title ) {
550 $dbw->update( 'page',
551 array( 'page_touched' => $timestamp ),
553 'page_namespace' => $title->getNamespace(),
554 'page_title' => $title->getDBkey() ),
559 #----------------------------------------------------------------------------
561 #----------------------------------------------------------------------------
563 /** Simple accessors */
565 * Get the text form (spaces not underscores) of the main part
569 function getText() { return $this->mTextform
; }
571 * Get the URL-encoded form of the main part
575 function getPartialURL() { return $this->mUrlform
; }
577 * Get the main part with underscores
581 function getDBkey() { return $this->mDbkeyform
; }
583 * Get the namespace index, i.e. one of the NS_xxxx constants
587 function getNamespace() { return $this->mNamespace
; }
589 * Get the namespace text
593 function getNsText() {
595 return $wgContLang->getNsText( $this->mNamespace
);
598 * Get the namespace text of the subject (rather than talk) page
602 function getSubjectNsText() {
604 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
608 * Get the namespace text of the talk page
611 function getTalkNsText() {
613 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
617 * Could this title have a corresponding talk page?
621 return( Namespace::canTalk( $this->mNamespace
) );
625 * Get the interwiki prefix (or null string)
629 function getInterwiki() { return $this->mInterwiki
; }
631 * Get the Title fragment (i.e. the bit after the #)
635 function getFragment() { return $this->mFragment
; }
637 * Get the default namespace index, for when there is no namespace
641 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
644 * Get title for search index
645 * @return string a stripped-down title string ready for the
648 function getIndexTitle() {
649 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
653 * Get the prefixed database key form
654 * @return string the prefixed title, with underscores and
655 * any interwiki and namespace prefixes
658 function getPrefixedDBkey() {
659 $s = $this->prefix( $this->mDbkeyform
);
660 $s = str_replace( ' ', '_', $s );
665 * Get the prefixed title with spaces.
666 * This is the form usually used for display
667 * @return string the prefixed title, with spaces
670 function getPrefixedText() {
671 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
672 $s = $this->prefix( $this->mTextform
);
673 $s = str_replace( '_', ' ', $s );
674 $this->mPrefixedText
= $s;
676 return $this->mPrefixedText
;
680 * Get the prefixed title with spaces, plus any fragment
681 * (part beginning with '#')
682 * @return string the prefixed title, with spaces and
683 * the fragment, including '#'
686 function getFullText() {
687 $text = $this->getPrefixedText();
688 if( '' != $this->mFragment
) {
689 $text .= '#' . $this->mFragment
;
695 * Get the lowest-level subpage name, i.e. the rightmost part after /
696 * @return string Subpage name
698 function getSubpageText() {
699 global $wgNamespacesWithSubpages;
700 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
701 $parts = explode( '/', $this->mTextform
);
702 return( $parts[ count( $parts ) - 1 ] );
704 return( $this->mTextform
);
709 * Get a URL-encoded form of the subpage text
710 * @return string URL-encoded subpage name
712 function getSubpageUrlForm() {
713 $text = $this->getSubpageText();
714 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
715 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
720 * Get a URL-encoded title (not an actual URL) including interwiki
721 * @return string the URL-encoded form
724 function getPrefixedURL() {
725 $s = $this->prefix( $this->mDbkeyform
);
726 $s = str_replace( ' ', '_', $s );
728 $s = wfUrlencode ( $s ) ;
730 # Cleaning up URL to make it look nice -- is this safe?
731 $s = str_replace( '%28', '(', $s );
732 $s = str_replace( '%29', ')', $s );
738 * Get a real URL referring to this title, with interwiki link and
741 * @param string $query an optional query string, not used
742 * for interwiki links
743 * @return string the URL
746 function getFullURL( $query = '' ) {
747 global $wgContLang, $wgServer, $wgRequest;
749 if ( '' == $this->mInterwiki
) {
750 $url = $this->getLocalUrl( $query );
752 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
753 // Correct fix would be to move the prepending elsewhere.
754 if ($wgRequest->getVal('action') != 'render') {
755 $url = $wgServer . $url;
758 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
760 $namespace = $wgContLang->getNsText( $this->mNamespace
);
761 if ( '' != $namespace ) {
762 # Can this actually happen? Interwikis shouldn't be parsed.
765 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
767 if( false === strpos( $url, '?' ) ) {
776 # Finally, add the fragment.
777 if ( '' != $this->mFragment
) {
778 $url .= '#' . $this->mFragment
;
781 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
786 * Get a URL with no fragment or server name. If this page is generated
787 * with action=render, $wgServer is prepended.
788 * @param string $query an optional query string; if not specified,
789 * $wgArticlePath will be used.
790 * @return string the URL
793 function getLocalURL( $query = '' ) {
794 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
796 if ( $this->isExternal() ) {
797 $url = $this->getFullURL();
799 // This is currently only used for edit section links in the
800 // context of interwiki transclusion. In theory we should
801 // append the query to the end of any existing query string,
802 // but interwiki transclusion is already broken in that case.
806 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
807 if ( $query == '' ) {
808 $url = str_replace( '$1', $dbkey, $wgArticlePath );
810 global $wgActionPaths;
812 if( !empty( $wgActionPaths ) &&
813 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
815 $action = urldecode( $matches[2] );
816 if( isset( $wgActionPaths[$action] ) ) {
817 $query = $matches[1];
818 if( isset( $matches[4] ) ) $query .= $matches[4];
819 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
820 if( $query != '' ) $url .= '?' . $query;
823 if ( $url === false ) {
824 if ( $query == '-' ) {
827 $url = "{$wgScript}?title={$dbkey}&{$query}";
831 // FIXME: this causes breakage in various places when we
832 // actually expected a local URL and end up with dupe prefixes.
833 if ($wgRequest->getVal('action') == 'render') {
834 $url = $wgServer . $url;
837 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
842 * Get an HTML-escaped version of the URL form, suitable for
843 * using in a link, without a server name or fragment
844 * @param string $query an optional query string
845 * @return string the URL
848 function escapeLocalURL( $query = '' ) {
849 return htmlspecialchars( $this->getLocalURL( $query ) );
853 * Get an HTML-escaped version of the URL form, suitable for
854 * using in a link, including the server name and fragment
856 * @return string the URL
857 * @param string $query an optional query string
860 function escapeFullURL( $query = '' ) {
861 return htmlspecialchars( $this->getFullURL( $query ) );
865 * Get the URL form for an internal link.
866 * - Used in various Squid-related code, in case we have a different
867 * internal hostname for the server from the exposed one.
869 * @param string $query an optional query string
870 * @return string the URL
873 function getInternalURL( $query = '' ) {
874 global $wgInternalServer;
875 $url = $wgInternalServer . $this->getLocalURL( $query );
876 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
881 * Get the edit URL for this Title
882 * @return string the URL, or a null string if this is an
886 function getEditURL() {
887 if ( '' != $this->mInterwiki
) { return ''; }
888 $s = $this->getLocalURL( 'action=edit' );
894 * Get the HTML-escaped displayable text form.
895 * Used for the title field in <a> tags.
896 * @return string the text, including any prefixes
899 function getEscapedText() {
900 return htmlspecialchars( $this->getPrefixedText() );
904 * Is this Title interwiki?
908 function isExternal() { return ( '' != $this->mInterwiki
); }
911 * Is this page "semi-protected" - the *only* protection is autoconfirm?
913 * @param string Action to check (default: edit)
916 function isSemiProtected( $action = 'edit' ) {
917 $restrictions = $this->getRestrictions( $action );
918 # We do a full compare because this could be an array
919 foreach( $restrictions as $restriction ) {
920 if( strtolower( $restriction ) != 'autoconfirmed' ) {
928 * Does the title correspond to a protected article?
929 * @param string $what the action the page is protected from,
930 * by default checks move and edit
934 function isProtected( $action = '' ) {
935 global $wgRestrictionLevels;
936 if ( -1 == $this->mNamespace
) { return true; }
938 if( $action == 'edit' ||
$action == '' ) {
939 $r = $this->getRestrictions( 'edit' );
940 foreach( $wgRestrictionLevels as $level ) {
941 if( in_array( $level, $r ) && $level != '' ) {
947 if( $action == 'move' ||
$action == '' ) {
948 $r = $this->getRestrictions( 'move' );
949 foreach( $wgRestrictionLevels as $level ) {
950 if( in_array( $level, $r ) && $level != '' ) {
960 * Is $wgUser is watching this page?
964 function userIsWatching() {
967 if ( is_null( $this->mWatched
) ) {
968 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
969 $this->mWatched
= false;
971 $this->mWatched
= $wgUser->isWatched( $this );
974 return $this->mWatched
;
978 * Can $wgUser perform $action this page?
979 * @param string $action action that permission needs to be checked for
983 function userCan($action) {
984 $fname = 'Title::userCan';
985 wfProfileIn( $fname );
990 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
991 if ( $result !== null ) {
992 wfProfileOut( $fname );
996 if( NS_SPECIAL
== $this->mNamespace
) {
997 wfProfileOut( $fname );
1000 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1001 // from taking effect -ævar
1002 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1003 !$wgUser->isAllowed('editinterface') ) {
1004 wfProfileOut( $fname );
1008 if( $this->mDbkeyform
== '_' ) {
1009 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1010 wfProfileOut( $fname );
1014 # protect global styles and js
1015 if ( NS_MEDIAWIKI
== $this->mNamespace
1016 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1017 && !$wgUser->isAllowed('editinterface') ) {
1018 wfProfileOut( $fname );
1022 # protect css/js subpages of user pages
1023 # XXX: this might be better using restrictions
1024 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1025 if( NS_USER
== $this->mNamespace
1026 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1027 && !$wgUser->isAllowed('editinterface')
1028 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1029 wfProfileOut( $fname );
1033 foreach( $this->getRestrictions($action) as $right ) {
1034 // Backwards compatibility, rewrite sysop -> protect
1035 if ( $right == 'sysop' ) {
1038 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1039 wfProfileOut( $fname );
1044 if( $action == 'move' &&
1045 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1046 wfProfileOut( $fname );
1050 if( $action == 'create' ) {
1051 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1052 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1057 wfProfileOut( $fname );
1062 * Can $wgUser edit this page?
1066 function userCanEdit() {
1067 return $this->userCan('edit');
1071 * Can $wgUser move this page?
1075 function userCanMove() {
1076 return $this->userCan('move');
1080 * Would anybody with sufficient privileges be able to move this page?
1081 * Some pages just aren't movable.
1086 function isMovable() {
1087 return Namespace::isMovable( $this->getNamespace() )
1088 && $this->getInterwiki() == '';
1092 * Can $wgUser read this page?
1096 function userCanRead() {
1100 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1101 if ( $result !== null ) {
1105 if( $wgUser->isAllowed('read') ) {
1108 global $wgWhitelistRead;
1110 /** If anon users can create an account,
1111 they need to reach the login page first! */
1112 if( $wgUser->isAllowed( 'createaccount' )
1113 && $this->getNamespace() == NS_SPECIAL
1114 && $this->getText() == 'Userlogin' ) {
1118 /** some pages are explicitly allowed */
1119 $name = $this->getPrefixedText();
1120 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1124 # Compatibility with old settings
1125 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1126 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1135 * Is this a talk page of some sort?
1139 function isTalkPage() {
1140 return Namespace::isTalk( $this->getNamespace() );
1144 * Is this a .css or .js subpage of a user page?
1148 function isCssJsSubpage() {
1149 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1152 * Is this a *valid* .css or .js subpage of a user page?
1153 * Check that the corresponding skin exists
1155 function isValidCssJsSubpage() {
1156 global $wgValidSkinNames;
1157 return( $this->isCssJsSubpage() && array_key_exists( $this->getSkinFromCssJsSubpage(), $wgValidSkinNames ) );
1160 * Trim down a .css or .js subpage title to get the corresponding skin name
1162 function getSkinFromCssJsSubpage() {
1163 $subpage = explode( '/', $this->mTextform
);
1164 $subpage = $subpage[ count( $subpage ) - 1 ];
1165 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1168 * Is this a .css subpage of a user page?
1172 function isCssSubpage() {
1173 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1176 * Is this a .js subpage of a user page?
1180 function isJsSubpage() {
1181 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1184 * Protect css/js subpages of user pages: can $wgUser edit
1188 * @todo XXX: this might be better using restrictions
1191 function userCanEditCssJsSubpage() {
1193 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1197 * Loads a string into mRestrictions array
1198 * @param string $res restrictions in string format
1201 function loadRestrictions( $res ) {
1202 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1203 $temp = explode( '=', trim( $restrict ) );
1204 if(count($temp) == 1) {
1205 // old format should be treated as edit/move restriction
1206 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1207 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1209 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1212 $this->mRestrictionsLoaded
= true;
1216 * Accessor/initialisation for mRestrictions
1217 * @param string $action action that permission needs to be checked for
1218 * @return array the array of groups allowed to edit this article
1221 function getRestrictions($action) {
1222 $id = $this->getArticleID();
1223 if ( 0 == $id ) { return array(); }
1225 if ( ! $this->mRestrictionsLoaded
) {
1226 $dbr =& wfGetDB( DB_SLAVE
);
1227 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1228 $this->loadRestrictions( $res );
1230 if( isset( $this->mRestrictions
[$action] ) ) {
1231 return $this->mRestrictions
[$action];
1237 * Is there a version of this page in the deletion archive?
1238 * @return int the number of archived revisions
1241 function isDeleted() {
1242 $fname = 'Title::isDeleted';
1243 if ( $this->getNamespace() < 0 ) {
1246 $dbr =& wfGetDB( DB_SLAVE
);
1247 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1248 'ar_title' => $this->getDBkey() ), $fname );
1254 * Get the article ID for this Title from the link cache,
1255 * adding it if necessary
1256 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1258 * @return int the ID
1261 function getArticleID( $flags = 0 ) {
1262 $linkCache =& LinkCache
::singleton();
1263 if ( $flags & GAID_FOR_UPDATE
) {
1264 $oldUpdate = $linkCache->forUpdate( true );
1265 $this->mArticleID
= $linkCache->addLinkObj( $this );
1266 $linkCache->forUpdate( $oldUpdate );
1268 if ( -1 == $this->mArticleID
) {
1269 $this->mArticleID
= $linkCache->addLinkObj( $this );
1272 return $this->mArticleID
;
1275 function getLatestRevID() {
1276 if ($this->mLatestID
!== false)
1277 return $this->mLatestID
;
1279 $db =& wfGetDB(DB_SLAVE
);
1280 return $this->mLatestID
= $db->selectField( 'revision',
1282 array('rev_page' => $this->getArticleID()),
1283 'Title::getLatestRevID' );
1287 * This clears some fields in this object, and clears any associated
1288 * keys in the "bad links" section of the link cache.
1290 * - This is called from Article::insertNewArticle() to allow
1291 * loading of the new page_id. It's also called from
1292 * Article::doDeleteArticle()
1294 * @param int $newid the new Article ID
1297 function resetArticleID( $newid ) {
1298 $linkCache =& LinkCache
::singleton();
1299 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1301 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1302 else { $this->mArticleID
= $newid; }
1303 $this->mRestrictionsLoaded
= false;
1304 $this->mRestrictions
= array();
1308 * Updates page_touched for this page; called from LinksUpdate.php
1309 * @return bool true if the update succeded
1312 function invalidateCache() {
1313 global $wgUseFileCache;
1315 if ( wfReadOnly() ) {
1319 $dbw =& wfGetDB( DB_MASTER
);
1320 $success = $dbw->update( 'page',
1322 'page_touched' => $dbw->timestamp()
1323 ), array( /* WHERE */
1324 'page_namespace' => $this->getNamespace() ,
1325 'page_title' => $this->getDBkey()
1326 ), 'Title::invalidateCache'
1329 if ($wgUseFileCache) {
1330 $cache = new CacheManager($this);
1331 @unlink
($cache->fileCacheName());
1338 * Prefix some arbitrary text with the namespace or interwiki prefix
1341 * @param string $name the text
1342 * @return string the prefixed text
1345 /* private */ function prefix( $name ) {
1349 if ( '' != $this->mInterwiki
) {
1350 $p = $this->mInterwiki
. ':';
1352 if ( 0 != $this->mNamespace
) {
1353 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1359 * Secure and split - main initialisation function for this object
1361 * Assumes that mDbkeyform has been set, and is urldecoded
1362 * and uses underscores, but not otherwise munged. This function
1363 * removes illegal characters, splits off the interwiki and
1364 * namespace prefixes, sets the other forms, and canonicalizes
1366 * @return bool true on success
1369 /* private */ function secureAndSplit() {
1370 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1371 $fname = 'Title::secureAndSplit';
1374 static $rxTc = false;
1376 # % is needed as well
1377 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1380 $this->mInterwiki
= $this->mFragment
= '';
1381 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1383 # Clean up whitespace
1385 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1386 $t = trim( $t, '_' );
1392 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1393 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1397 $this->mDbkeyform
= $t;
1399 # Initial colon indicates main namespace rather than specified default
1400 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1401 if ( ':' == $t{0} ) {
1402 $this->mNamespace
= NS_MAIN
;
1403 $t = substr( $t, 1 ); # remove the colon but continue processing
1406 # Namespace or interwiki prefix
1409 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1411 $lowerNs = strtolower( $p );
1412 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1413 # Canonical namespace
1415 $this->mNamespace
= $ns;
1416 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1417 # Ordinary namespace
1419 $this->mNamespace
= $ns;
1420 } elseif( $this->getInterwikiLink( $p ) ) {
1422 # Can't make a local interwiki link to an interwiki link.
1423 # That's just crazy!
1429 $this->mInterwiki
= strtolower( $p );
1431 # Redundant interwiki prefix to the local wiki
1432 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1434 # Can't have an empty self-link
1437 $this->mInterwiki
= '';
1439 # Do another namespace split...
1443 # If there's an initial colon after the interwiki, that also
1444 # resets the default namespace
1445 if ( $t !== '' && $t[0] == ':' ) {
1446 $this->mNamespace
= NS_MAIN
;
1447 $t = substr( $t, 1 );
1450 # If there's no recognized interwiki or namespace,
1451 # then let the colon expression be part of the title.
1457 # We already know that some pages won't be in the database!
1459 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1460 $this->mArticleID
= 0;
1462 $f = strstr( $r, '#' );
1463 if ( false !== $f ) {
1464 $this->mFragment
= substr( $f, 1 );
1465 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1466 # remove whitespace again: prevents "Foo_bar_#"
1467 # becoming "Foo_bar_"
1468 $r = preg_replace( '/_*$/', '', $r );
1471 # Reject illegal characters.
1473 if( preg_match( $rxTc, $r ) ) {
1478 * Pages with "/./" or "/../" appearing in the URLs will
1479 * often be unreachable due to the way web browsers deal
1480 * with 'relative' URLs. Forbid them explicitly.
1482 if ( strpos( $r, '.' ) !== false &&
1483 ( $r === '.' ||
$r === '..' ||
1484 strpos( $r, './' ) === 0 ||
1485 strpos( $r, '../' ) === 0 ||
1486 strpos( $r, '/./' ) !== false ||
1487 strpos( $r, '/../' ) !== false ) )
1492 # We shouldn't need to query the DB for the size.
1493 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1494 if ( strlen( $r ) > 255 ) {
1499 * Normally, all wiki links are forced to have
1500 * an initial capital letter so [[foo]] and [[Foo]]
1501 * point to the same place.
1503 * Don't force it for interwikis, since the other
1504 * site might be case-sensitive.
1506 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1507 $t = $wgContLang->ucfirst( $r );
1513 * Can't make a link to a namespace alone...
1514 * "empty" local links can only be self-links
1515 * with a fragment identifier.
1518 $this->mInterwiki
== '' &&
1519 $this->mNamespace
!= NS_MAIN
) {
1523 // Any remaining initial :s are illegal.
1524 if ( $t !== '' && ':' == $t{0} ) {
1529 $this->mDbkeyform
= $t;
1530 $this->mUrlform
= wfUrlencode( $t );
1532 $this->mTextform
= str_replace( '_', ' ', $t );
1538 * Get a Title object associated with the talk page of this article
1539 * @return Title the object for the talk page
1542 function getTalkPage() {
1543 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1547 * Get a title object associated with the subject page of this
1550 * @return Title the object for the subject page
1553 function getSubjectPage() {
1554 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1558 * Get an array of Title objects linking to this Title
1559 * Also stores the IDs in the link cache.
1561 * @param string $options may be FOR UPDATE
1562 * @return array the Title objects linking here
1565 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1566 $linkCache =& LinkCache
::singleton();
1567 $id = $this->getArticleID();
1570 $db =& wfGetDB( DB_MASTER
);
1572 $db =& wfGetDB( DB_SLAVE
);
1575 $res = $db->select( array( 'page', $table ),
1576 array( 'page_namespace', 'page_title', 'page_id' ),
1578 "{$prefix}_from=page_id",
1579 "{$prefix}_namespace" => $this->getNamespace(),
1580 "{$prefix}_title" => $this->getDbKey() ),
1581 'Title::getLinksTo',
1585 if ( $db->numRows( $res ) ) {
1586 while ( $row = $db->fetchObject( $res ) ) {
1587 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1588 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1589 $retVal[] = $titleObj;
1593 $db->freeResult( $res );
1598 * Get an array of Title objects using this Title as a template
1599 * Also stores the IDs in the link cache.
1601 * @param string $options may be FOR UPDATE
1602 * @return array the Title objects linking here
1605 function getTemplateLinksTo( $options = '' ) {
1606 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1610 * Get an array of Title objects referring to non-existent articles linked from this page
1612 * @param string $options may be FOR UPDATE
1613 * @return array the Title objects
1616 function getBrokenLinksFrom( $options = '' ) {
1618 $db =& wfGetDB( DB_MASTER
);
1620 $db =& wfGetDB( DB_SLAVE
);
1623 $res = $db->safeQuery(
1624 "SELECT pl_namespace, pl_title
1627 ON pl_namespace=page_namespace
1628 AND pl_title=page_title
1630 AND page_namespace IS NULL
1632 $db->tableName( 'pagelinks' ),
1633 $db->tableName( 'page' ),
1634 $this->getArticleId(),
1638 if ( $db->numRows( $res ) ) {
1639 while ( $row = $db->fetchObject( $res ) ) {
1640 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1643 $db->freeResult( $res );
1649 * Get a list of URLs to purge from the Squid cache when this
1652 * @return array the URLs
1655 function getSquidURLs() {
1657 $this->getInternalURL(),
1658 $this->getInternalURL( 'action=history' )
1663 * Move this page without authentication
1664 * @param Title &$nt the new page Title
1667 function moveNoAuth( &$nt ) {
1668 return $this->moveTo( $nt, false );
1672 * Check whether a given move operation would be valid.
1673 * Returns true if ok, or a message key string for an error message
1674 * if invalid. (Scarrrrry ugly interface this.)
1675 * @param Title &$nt the new title
1676 * @param bool $auth indicates whether $wgUser's permissions
1678 * @return mixed true on success, message name on failure
1681 function isValidMoveOperation( &$nt, $auth = true ) {
1682 if( !$this or !$nt ) {
1683 return 'badtitletext';
1685 if( $this->equals( $nt ) ) {
1688 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1689 return 'immobile_namespace';
1692 $oldid = $this->getArticleID();
1693 $newid = $nt->getArticleID();
1695 if ( strlen( $nt->getDBkey() ) < 1 ) {
1696 return 'articleexists';
1698 if ( ( '' == $this->getDBkey() ) ||
1700 ( '' == $nt->getDBkey() ) ) {
1701 return 'badarticleerror';
1705 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1706 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1707 return 'protectedpage';
1710 # The move is allowed only if (1) the target doesn't exist, or
1711 # (2) the target is a redirect to the source, and has no history
1712 # (so we can undo bad moves right after they're done).
1714 if ( 0 != $newid ) { # Target exists; check for validity
1715 if ( ! $this->isValidMoveTarget( $nt ) ) {
1716 return 'articleexists';
1723 * Move a title to a new location
1724 * @param Title &$nt the new title
1725 * @param bool $auth indicates whether $wgUser's permissions
1727 * @return mixed true on success, message name on failure
1730 function moveTo( &$nt, $auth = true, $reason = '' ) {
1731 $err = $this->isValidMoveOperation( $nt, $auth );
1732 if( is_string( $err ) ) {
1736 $pageid = $this->getArticleID();
1737 if( $nt->exists() ) {
1738 $this->moveOverExistingRedirect( $nt, $reason );
1739 $pageCountChange = 0;
1740 } else { # Target didn't exist, do normal move.
1741 $this->moveToNewTitle( $nt, $reason );
1742 $pageCountChange = 1;
1744 $redirid = $this->getArticleID();
1746 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1747 $dbw =& wfGetDB( DB_MASTER
);
1748 $categorylinks = $dbw->tableName( 'categorylinks' );
1749 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1750 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1751 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1752 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1756 $oldnamespace = $this->getNamespace() & ~
1;
1757 $newnamespace = $nt->getNamespace() & ~
1;
1758 $oldtitle = $this->getDBkey();
1759 $newtitle = $nt->getDBkey();
1761 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1762 WatchedItem
::duplicateEntries( $this, $nt );
1765 # Update search engine
1766 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1768 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1772 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1773 # Moved out of main namespace
1774 # not viewed, edited, removing
1775 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1776 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1777 # Moved into main namespace
1778 # not viewed, edited, adding
1779 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1780 } elseif ( $pageCountChange ) {
1782 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1791 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1796 * Move page to a title which is at present a redirect to the
1799 * @param Title &$nt the page to move to, which should currently
1803 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1804 global $wgUseSquid, $wgMwRedir;
1805 $fname = 'Title::moveOverExistingRedirect';
1806 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1809 $comment .= ": $reason";
1812 $now = wfTimestampNow();
1814 $newid = $nt->getArticleID();
1815 $oldid = $this->getArticleID();
1816 $dbw =& wfGetDB( DB_MASTER
);
1817 $linkCache =& LinkCache
::singleton();
1819 # Delete the old redirect. We don't save it to history since
1820 # by definition if we've got here it's rather uninteresting.
1821 # We have to remove it so that the next step doesn't trigger
1822 # a conflict on the unique namespace+title index...
1823 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1825 # Save a null revision in the page's history notifying of the move
1826 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1827 $nullRevId = $nullRevision->insertOn( $dbw );
1829 # Change the name of the target page:
1830 $dbw->update( 'page',
1832 'page_touched' => $dbw->timestamp($now),
1833 'page_namespace' => $nt->getNamespace(),
1834 'page_title' => $nt->getDBkey(),
1835 'page_latest' => $nullRevId,
1837 /* WHERE */ array( 'page_id' => $oldid ),
1840 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1842 # Recreate the redirect, this time in the other direction.
1843 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1844 $redirectArticle = new Article( $this );
1845 $newid = $redirectArticle->insertOn( $dbw );
1846 $redirectRevision = new Revision( array(
1848 'comment' => $comment,
1849 'text' => $redirectText ) );
1850 $revid = $redirectRevision->insertOn( $dbw );
1851 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1852 $linkCache->clearLink( $this->getPrefixedDBkey() );
1855 $log = new LogPage( 'move' );
1856 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1858 # Now, we record the link from the redirect to the new title.
1859 # It should have no other outgoing links...
1860 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1861 $dbw->insert( 'pagelinks',
1863 'pl_from' => $newid,
1864 'pl_namespace' => $nt->getNamespace(),
1865 'pl_title' => $nt->getDbKey() ),
1869 if ( $wgUseSquid ) {
1870 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1871 $u = new SquidUpdate( $urls );
1877 * Move page to non-existing title.
1878 * @param Title &$nt the new Title
1881 function moveToNewTitle( &$nt, $reason = '' ) {
1884 $fname = 'MovePageForm::moveToNewTitle';
1885 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1887 $comment .= ": $reason";
1890 $newid = $nt->getArticleID();
1891 $oldid = $this->getArticleID();
1892 $dbw =& wfGetDB( DB_MASTER
);
1893 $now = $dbw->timestamp();
1895 $linkCache =& LinkCache
::singleton();
1897 # Save a null revision in the page's history notifying of the move
1898 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1899 $nullRevId = $nullRevision->insertOn( $dbw );
1902 $dbw->update( 'page',
1904 'page_touched' => $now,
1905 'page_namespace' => $nt->getNamespace(),
1906 'page_title' => $nt->getDBkey(),
1907 'page_latest' => $nullRevId,
1909 /* WHERE */ array( 'page_id' => $oldid ),
1913 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1916 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1917 $redirectArticle = new Article( $this );
1918 $newid = $redirectArticle->insertOn( $dbw );
1919 $redirectRevision = new Revision( array(
1921 'comment' => $comment,
1922 'text' => $redirectText ) );
1923 $revid = $redirectRevision->insertOn( $dbw );
1924 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1925 $linkCache->clearLink( $this->getPrefixedDBkey() );
1928 $log = new LogPage( 'move' );
1929 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1931 # Purge caches as per article creation
1932 Article
::onArticleCreate( $nt );
1934 # Record the just-created redirect's linking to the page
1935 $dbw->insert( 'pagelinks',
1937 'pl_from' => $newid,
1938 'pl_namespace' => $nt->getNamespace(),
1939 'pl_title' => $nt->getDBkey() ),
1942 # Non-existent target may have had broken links to it; these must
1943 # now be touched to update link coloring.
1946 # Purge old title from squid
1947 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1948 $titles = $nt->getLinksTo();
1949 if ( $wgUseSquid ) {
1950 $urls = $this->getSquidURLs();
1951 foreach ( $titles as $linkTitle ) {
1952 $urls[] = $linkTitle->getInternalURL();
1954 $u = new SquidUpdate( $urls );
1960 * Checks if $this can be moved to a given Title
1961 * - Selects for update, so don't call it unless you mean business
1963 * @param Title &$nt the new title to check
1966 function isValidMoveTarget( $nt ) {
1968 $fname = 'Title::isValidMoveTarget';
1969 $dbw =& wfGetDB( DB_MASTER
);
1972 $id = $nt->getArticleID();
1973 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1974 array( 'page_is_redirect','old_text','old_flags' ),
1975 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1976 $fname, 'FOR UPDATE' );
1978 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1982 $text = Revision
::getRevisionText( $obj );
1984 # Does the redirect point to the source?
1985 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1986 $redirTitle = Title
::newFromText( $m[1] );
1987 if( !is_object( $redirTitle ) ||
1988 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1996 # Does the article have a history?
1997 $row = $dbw->selectRow( array( 'page', 'revision'),
1999 array( 'page_namespace' => $nt->getNamespace(),
2000 'page_title' => $nt->getDBkey(),
2001 'page_id=rev_page AND page_latest != rev_id'
2002 ), $fname, 'FOR UPDATE'
2005 # Return true if there was no history
2006 return $row === false;
2010 * Create a redirect; fails if the title already exists; does
2013 * @param Title $dest the destination of the redirect
2014 * @param string $comment the comment string describing the move
2015 * @return bool true on success
2018 function createRedirect( $dest, $comment ) {
2019 if ( $this->getArticleID() ) {
2023 $fname = 'Title::createRedirect';
2024 $dbw =& wfGetDB( DB_MASTER
);
2026 $article = new Article( $this );
2027 $newid = $article->insertOn( $dbw );
2028 $revision = new Revision( array(
2030 'comment' => $comment,
2031 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2033 $revisionId = $revision->insertOn( $dbw );
2034 $article->updateRevisionOn( $dbw, $revision, 0 );
2037 $dbw->insert( 'pagelinks',
2039 'pl_from' => $newid,
2040 'pl_namespace' => $dest->getNamespace(),
2041 'pl_title' => $dest->getDbKey()
2045 Article
::onArticleCreate( $this );
2050 * Get categories to which this Title belongs and return an array of
2051 * categories' names.
2053 * @return array an array of parents in the form:
2054 * $parent => $currentarticle
2057 function getParentCategories() {
2060 $titlekey = $this->getArticleId();
2061 $dbr =& wfGetDB( DB_SLAVE
);
2062 $categorylinks = $dbr->tableName( 'categorylinks' );
2065 $sql = "SELECT * FROM $categorylinks"
2066 ." WHERE cl_from='$titlekey'"
2067 ." AND cl_from <> '0'"
2068 ." ORDER BY cl_sortkey";
2070 $res = $dbr->query ( $sql ) ;
2072 if($dbr->numRows($res) > 0) {
2073 while ( $x = $dbr->fetchObject ( $res ) )
2074 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2075 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2076 $dbr->freeResult ( $res ) ;
2084 * Get a tree of parent categories
2085 * @param array $children an array with the children in the keys, to check for circular refs
2089 function getParentCategoryTree( $children = array() ) {
2090 $parents = $this->getParentCategories();
2092 if($parents != '') {
2093 foreach($parents as $parent => $current) {
2094 if ( array_key_exists( $parent, $children ) ) {
2095 # Circular reference
2096 $stack[$parent] = array();
2098 $nt = Title
::newFromText($parent);
2099 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2110 * Get an associative array for selecting this title from
2116 function pageCond() {
2117 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2121 * Get the revision ID of the previous revision
2123 * @param integer $revision Revision ID. Get the revision that was before this one.
2124 * @return interger $oldrevision|false
2126 function getPreviousRevisionID( $revision ) {
2127 $dbr =& wfGetDB( DB_SLAVE
);
2128 return $dbr->selectField( 'revision', 'rev_id',
2129 'rev_page=' . intval( $this->getArticleId() ) .
2130 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2134 * Get the revision ID of the next revision
2136 * @param integer $revision Revision ID. Get the revision that was after this one.
2137 * @return interger $oldrevision|false
2139 function getNextRevisionID( $revision ) {
2140 $dbr =& wfGetDB( DB_SLAVE
);
2141 return $dbr->selectField( 'revision', 'rev_id',
2142 'rev_page=' . intval( $this->getArticleId() ) .
2143 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2147 * Compare with another title.
2149 * @param Title $title
2152 function equals( $title ) {
2153 // Note: === is necessary for proper matching of number-like titles.
2154 return $this->getInterwiki() === $title->getInterwiki()
2155 && $this->getNamespace() == $title->getNamespace()
2156 && $this->getDbkey() === $title->getDbkey();
2160 * Check if page exists
2164 return $this->getArticleId() != 0;
2168 * Should a link should be displayed as a known link, just based on its title?
2170 * Currently, a self-link with a fragment and special pages are in
2171 * this category. Special pages never exist in the database.
2173 function isAlwaysKnown() {
2174 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2175 || NS_SPECIAL
== $this->mNamespace
;
2179 * Update page_touched timestamps on pages linking to this title.
2180 * In principal, this could be backgrounded and could also do squid
2183 function touchLinks() {
2184 $fname = 'Title::touchLinks';
2186 $dbw =& wfGetDB( DB_MASTER
);
2188 $res = $dbw->select( 'pagelinks',
2191 'pl_namespace' => $this->getNamespace(),
2192 'pl_title' => $this->getDbKey() ),
2195 $toucharr = array();
2196 while( $row = $dbw->fetchObject( $res ) ) {
2197 $toucharr[] = $row->pl_from
;
2199 $dbw->freeResult( $res );
2201 if( $this->getNamespace() == NS_CATEGORY
) {
2202 // Categories show up in a separate set of links as well
2203 $res = $dbw->select( 'categorylinks',
2205 array( 'cl_to' => $this->getDbKey() ),
2207 while( $row = $dbw->fetchObject( $res ) ) {
2208 $toucharr[] = $row->cl_from
;
2210 $dbw->freeResult( $res );
2213 if (!count($toucharr))
2215 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2216 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2219 function trackbackURL() {
2220 global $wgTitle, $wgScriptPath, $wgServer;
2222 return "$wgServer$wgScriptPath/trackback.php?article="
2223 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2226 function trackbackRDF() {
2227 $url = htmlspecialchars($this->getFullURL());
2228 $title = htmlspecialchars($this->getText());
2229 $tburl = $this->trackbackURL();
2232 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2233 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2234 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2237 dc:identifier=\"$url\"
2239 trackback:ping=\"$tburl\" />
2244 * Generate strings used for xml 'id' names in monobook tabs
2247 function getNamespaceKey() {
2248 switch ($this->getNamespace()) {
2251 return 'nstab-main';
2254 return 'nstab-user';
2256 return 'nstab-media';
2258 return 'nstab-special';
2260 case NS_PROJECT_TALK
:
2264 return 'nstab-image';
2266 case NS_MEDIAWIKI_TALK
:
2267 return 'nstab-mediawiki';
2269 case NS_TEMPLATE_TALK
:
2270 return 'nstab-template';
2273 return 'nstab-help';
2275 case NS_CATEGORY_TALK
:
2276 return 'nstab-category';
2278 return 'nstab-' . strtolower( $this->getSubjectNsText() );