9 require_once( 'normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * Static cache variables
31 static private $titleCache=array();
32 static private $interwikiCache=array();
36 * All member variables should be considered private
37 * Please use the accessor functions
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
66 /* private */ function Title() {
67 $this->mInterwiki
= $this->mUrlform
=
68 $this->mTextform
= $this->mDbkeyform
= '';
69 $this->mArticleID
= -1;
70 $this->mNamespace
= NS_MAIN
;
71 $this->mRestrictionsLoaded
= false;
72 $this->mRestrictions
= array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
75 $this->mDefaultNamespace
= NS_MAIN
;
76 $this->mWatched
= NULL;
77 $this->mLatestID
= false;
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return Title the new object, or NULL on an error
89 /* static */ function newFromDBkey( $key ) {
91 $t->mDbkeyform
= $key;
92 if( $t->secureAndSplit() )
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
111 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
112 $fname = 'Title::newFromText';
114 if( is_object( $text ) ) {
115 throw new MWException( 'Title::newFromText given an object' );
119 * Wiki pages often contain multiple links to the same page.
120 * Title normalization and parsing can become expensive on
121 * pages with many links, so we can save a little time by
124 * In theory these are value objects and won't get changed...
126 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
127 return Title
::$titleCache[$text];
131 * Convert things like é ā or 〗 into real text...
133 $filteredText = Sanitizer
::decodeCharReferences( $text );
136 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
137 $t->mDefaultNamespace
= $defaultNamespace;
139 static $cachedcount = 0 ;
140 if( $t->secureAndSplit() ) {
141 if( $defaultNamespace == NS_MAIN
) {
142 if( $cachedcount >= MW_TITLECACHE_MAX
) {
143 # Avoid memory leaks on mass operations...
144 Title
::$titleCache = array();
148 Title
::$titleCache[$text] =& $t;
158 * Create a new Title from URL-encoded text. Ensures that
159 * the given title's length does not exceed the maximum.
160 * @param string $url the title, as might be taken from a URL
161 * @return Title the new object, or NULL on an error
165 function newFromURL( $url ) {
166 global $wgLegalTitleChars;
169 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
170 # but some URLs used it as a space replacement and they still come
171 # from some external search tools.
172 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
173 $url = str_replace( '+', ' ', $url );
176 $t->mDbkeyform
= str_replace( ' ', '_', $url );
177 if( $t->secureAndSplit() ) {
185 * Create a new Title from an article ID
187 * @todo This is inefficiently implemented, the page row is requested
188 * but not used for anything else
190 * @param int $id the page_id corresponding to the Title to create
191 * @return Title the new object, or NULL on an error
195 function newFromID( $id ) {
196 $fname = 'Title::newFromID';
197 $dbr =& wfGetDB( DB_SLAVE
);
198 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
199 array( 'page_id' => $id ), $fname );
200 if ( $row !== false ) {
201 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
209 * Make an array of titles from an array of IDs
211 function newFromIDs( $ids ) {
212 $dbr =& wfGetDB( DB_SLAVE
);
213 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
214 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
217 while ( $row = $dbr->fetchObject( $res ) ) {
218 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
224 * Create a new Title from a namespace index and a DB key.
225 * It's assumed that $ns and $title are *valid*, for instance when
226 * they came directly from the database or a special page name.
227 * For convenience, spaces are converted to underscores so that
228 * eg user_text fields can be used directly.
230 * @param int $ns the namespace of the article
231 * @param string $title the unprefixed database key form
232 * @return Title the new object
236 function &makeTitle( $ns, $title ) {
240 $t->mNamespace
= intval( $ns );
241 $t->mDbkeyform
= str_replace( ' ', '_', $title );
242 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
243 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
244 $t->mTextform
= str_replace( '_', ' ', $title );
249 * Create a new Title frrom a namespace index and a DB key.
250 * The parameters will be checked for validity, which is a bit slower
251 * than makeTitle() but safer for user-provided data.
253 * @param int $ns the namespace of the article
254 * @param string $title the database key form
255 * @return Title the new object, or NULL on an error
259 function makeTitleSafe( $ns, $title ) {
261 $t->mDbkeyform
= Title
::makeName( $ns, $title );
262 if( $t->secureAndSplit() ) {
270 * Create a new Title for the Main Page
273 * @return Title the new object
276 function newMainPage() {
277 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
281 * Create a new Title for a redirect
282 * @param string $text the redirect title text
283 * @return Title the new object, or NULL if the text is not a
288 function newFromRedirect( $text ) {
291 if ( $wgMwRedir->matchStart( $text ) ) {
292 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
293 # categories are escaped using : for example one can enter:
294 # #REDIRECT [[:Category:Music]]. Need to remove it.
295 if ( substr($m[1],0,1) == ':') {
296 # We don't want to keep the ':'
297 $m[1] = substr( $m[1], 1 );
300 $rt = Title
::newFromText( $m[1] );
301 # Disallow redirects to Special:Userlogout
302 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
310 #----------------------------------------------------------------------------
312 #----------------------------------------------------------------------------
315 * Get the prefixed DB key associated with an ID
316 * @param int $id the page_id of the article
317 * @return Title an object representing the article, or NULL
318 * if no such article was found
322 function nameOf( $id ) {
323 $fname = 'Title::nameOf';
324 $dbr =& wfGetDB( DB_SLAVE
);
326 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
327 if ( $s === false ) { return NULL; }
329 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
334 * Get a regex character class describing the legal characters in a link
335 * @return string the list of characters, not delimited
339 function legalChars() {
340 global $wgLegalTitleChars;
341 return $wgLegalTitleChars;
345 * Get a string representation of a title suitable for
346 * including in a search index
348 * @param int $ns a namespace index
349 * @param string $title text-form main part
350 * @return string a stripped-down title string ready for the
353 /* static */ function indexTitle( $ns, $title ) {
356 $lc = SearchEngine
::legalSearchChars() . '&#;';
357 $t = $wgContLang->stripForSearch( $title );
358 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
359 $t = strtolower( $t );
362 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
363 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
365 $t = preg_replace( "/\\s+/", ' ', $t );
367 if ( $ns == NS_IMAGE
) {
368 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
374 * Make a prefixed DB key from a DB key and a namespace index
375 * @param int $ns numerical representation of the namespace
376 * @param string $title the DB key form the title
377 * @return string the prefixed form of the title
379 /* static */ function makeName( $ns, $title ) {
382 $n = $wgContLang->getNsText( $ns );
383 return $n == '' ?
$title : "$n:$title";
387 * Returns the URL associated with an interwiki prefix
388 * @param string $key the interwiki prefix (e.g. "MeatBall")
389 * @return the associated URL, containing "$1", which should be
390 * replaced by an article title
394 function getInterwikiLink( $key ) {
395 global $wgMemc, $wgDBname, $wgInterwikiExpiry;
396 global $wgInterwikiCache;
397 $fname = 'Title::getInterwikiLink';
399 $key = strtolower( $key );
401 $k = $wgDBname.':interwiki:'.$key;
402 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
403 return Title
::$interwikiCache[$k]->iw_url
;
406 if ($wgInterwikiCache) {
407 return Title
::getInterwikiCached( $key );
410 $s = $wgMemc->get( $k );
411 # Ignore old keys with no iw_local
412 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
413 Title
::$interwikiCache[$k] = $s;
417 $dbr =& wfGetDB( DB_SLAVE
);
418 $res = $dbr->select( 'interwiki',
419 array( 'iw_url', 'iw_local', 'iw_trans' ),
420 array( 'iw_prefix' => $key ), $fname );
425 $s = $dbr->fetchObject( $res );
427 # Cache non-existence: create a blank object and save it to memcached
433 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
434 Title
::$interwikiCache[$k] = $s;
440 * Fetch interwiki prefix data from local cache in constant database
442 * More logic is explained in DefaultSettings
444 * @return string URL of interwiki site
447 function getInterwikiCached( $key ) {
448 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
452 $db=dba_open($wgInterwikiCache,'r','cdb');
453 /* Resolve site name */
454 if ($wgInterwikiScopes>=3 and !$site) {
455 $site = dba_fetch("__sites:{$wgDBname}", $db);
457 $site = $wgInterwikiFallbackSite;
459 $value = dba_fetch("{$wgDBname}:{$key}", $db);
460 if ($value=='' and $wgInterwikiScopes>=3) {
462 $value = dba_fetch("_{$site}:{$key}", $db);
464 if ($value=='' and $wgInterwikiScopes>=2) {
466 $value = dba_fetch("__global:{$key}", $db);
475 list($local,$url)=explode(' ',$value,2);
477 $s->iw_local
=(int)$local;
479 Title
::$interwikiCache[$wgDBname.':interwiki:'.$key] = $s;
483 * Determine whether the object refers to a page within
486 * @return bool TRUE if this is an in-project interwiki link
487 * or a wikilink, FALSE otherwise
493 if ( $this->mInterwiki
!= '' ) {
494 # Make sure key is loaded into cache
495 $this->getInterwikiLink( $this->mInterwiki
);
496 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
497 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
504 * Determine whether the object refers to a page within
505 * this project and is transcludable.
507 * @return bool TRUE if this is transcludable
513 if ($this->mInterwiki
== '')
515 # Make sure key is loaded into cache
516 $this->getInterwikiLink( $this->mInterwiki
);
517 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
518 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
522 * Update the page_touched field for an array of title objects
523 * @todo Inefficient unless the IDs are already loaded into the
525 * @param array $titles an array of Title objects to be touched
526 * @param string $timestamp the timestamp to use instead of the
527 * default current time
531 function touchArray( $titles, $timestamp = '' ) {
533 if ( count( $titles ) == 0 ) {
536 $dbw =& wfGetDB( DB_MASTER
);
537 if ( $timestamp == '' ) {
538 $timestamp = $dbw->timestamp();
541 $page = $dbw->tableName( 'page' );
542 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
545 foreach ( $titles as $title ) {
546 if ( $wgUseFileCache ) {
547 $cm = new CacheManager($title);
548 @unlink($cm->fileCacheName());
555 $sql .= $title->getArticleID();
559 $dbw->query( $sql, 'Title::touchArray' );
562 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
563 // do them in small chunks:
564 $fname = 'Title::touchArray';
565 foreach( $titles as $title ) {
566 $dbw->update( 'page',
567 array( 'page_touched' => $timestamp ),
569 'page_namespace' => $title->getNamespace(),
570 'page_title' => $title->getDBkey() ),
575 #----------------------------------------------------------------------------
577 #----------------------------------------------------------------------------
579 /** Simple accessors */
581 * Get the text form (spaces not underscores) of the main part
585 function getText() { return $this->mTextform
; }
587 * Get the URL-encoded form of the main part
591 function getPartialURL() { return $this->mUrlform
; }
593 * Get the main part with underscores
597 function getDBkey() { return $this->mDbkeyform
; }
599 * Get the namespace index, i.e. one of the NS_xxxx constants
603 function getNamespace() { return $this->mNamespace
; }
605 * Get the namespace text
609 function getNsText() {
611 return $wgContLang->getNsText( $this->mNamespace
);
614 * Get the namespace text of the subject (rather than talk) page
618 function getSubjectNsText() {
620 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
624 * Get the namespace text of the talk page
627 function getTalkNsText() {
629 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
633 * Could this title have a corresponding talk page?
637 return( Namespace::canTalk( $this->mNamespace
) );
641 * Get the interwiki prefix (or null string)
645 function getInterwiki() { return $this->mInterwiki
; }
647 * Get the Title fragment (i.e. the bit after the #)
651 function getFragment() { return $this->mFragment
; }
653 * Get the default namespace index, for when there is no namespace
657 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
660 * Get title for search index
661 * @return string a stripped-down title string ready for the
664 function getIndexTitle() {
665 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
669 * Get the prefixed database key form
670 * @return string the prefixed title, with underscores and
671 * any interwiki and namespace prefixes
674 function getPrefixedDBkey() {
675 $s = $this->prefix( $this->mDbkeyform
);
676 $s = str_replace( ' ', '_', $s );
681 * Get the prefixed title with spaces.
682 * This is the form usually used for display
683 * @return string the prefixed title, with spaces
686 function getPrefixedText() {
687 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
688 $s = $this->prefix( $this->mTextform
);
689 $s = str_replace( '_', ' ', $s );
690 $this->mPrefixedText
= $s;
692 return $this->mPrefixedText
;
696 * Get the prefixed title with spaces, plus any fragment
697 * (part beginning with '#')
698 * @return string the prefixed title, with spaces and
699 * the fragment, including '#'
702 function getFullText() {
703 $text = $this->getPrefixedText();
704 if( '' != $this->mFragment
) {
705 $text .= '#' . $this->mFragment
;
711 * Get the base name, i.e. the leftmost parts before the /
712 * @return string Base name
714 function getBaseText() {
715 global $wgNamespacesWithSubpages;
716 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
717 $parts = explode( '/', $this->getText() );
718 # Don't discard the real title if there's no subpage involved
719 if( count( $parts ) > 1 )
720 unset( $parts[ count( $parts ) - 1 ] );
721 return implode( '/', $parts );
723 return $this->getText();
728 * Get the lowest-level subpage name, i.e. the rightmost part after /
729 * @return string Subpage name
731 function getSubpageText() {
732 global $wgNamespacesWithSubpages;
733 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
734 $parts = explode( '/', $this->mTextform
);
735 return( $parts[ count( $parts ) - 1 ] );
737 return( $this->mTextform
);
742 * Get a URL-encoded form of the subpage text
743 * @return string URL-encoded subpage name
745 function getSubpageUrlForm() {
746 $text = $this->getSubpageText();
747 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
748 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
753 * Get a URL-encoded title (not an actual URL) including interwiki
754 * @return string the URL-encoded form
757 function getPrefixedURL() {
758 $s = $this->prefix( $this->mDbkeyform
);
759 $s = str_replace( ' ', '_', $s );
761 $s = wfUrlencode ( $s ) ;
763 # Cleaning up URL to make it look nice -- is this safe?
764 $s = str_replace( '%28', '(', $s );
765 $s = str_replace( '%29', ')', $s );
771 * Get a real URL referring to this title, with interwiki link and
774 * @param string $query an optional query string, not used
775 * for interwiki links
776 * @return string the URL
779 function getFullURL( $query = '' ) {
780 global $wgContLang, $wgServer, $wgRequest;
782 if ( '' == $this->mInterwiki
) {
783 $url = $this->getLocalUrl( $query );
785 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
786 // Correct fix would be to move the prepending elsewhere.
787 if ($wgRequest->getVal('action') != 'render') {
788 $url = $wgServer . $url;
791 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
793 $namespace = $wgContLang->getNsText( $this->mNamespace
);
794 if ( '' != $namespace ) {
795 # Can this actually happen? Interwikis shouldn't be parsed.
798 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
800 if( false === strpos( $url, '?' ) ) {
809 # Finally, add the fragment.
810 if ( '' != $this->mFragment
) {
811 $url .= '#' . $this->mFragment
;
814 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
819 * Get a URL with no fragment or server name. If this page is generated
820 * with action=render, $wgServer is prepended.
821 * @param string $query an optional query string; if not specified,
822 * $wgArticlePath will be used.
823 * @return string the URL
826 function getLocalURL( $query = '' ) {
827 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
829 if ( $this->isExternal() ) {
830 $url = $this->getFullURL();
832 // This is currently only used for edit section links in the
833 // context of interwiki transclusion. In theory we should
834 // append the query to the end of any existing query string,
835 // but interwiki transclusion is already broken in that case.
839 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
840 if ( $query == '' ) {
841 $url = str_replace( '$1', $dbkey, $wgArticlePath );
843 global $wgActionPaths;
845 if( !empty( $wgActionPaths ) &&
846 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
848 $action = urldecode( $matches[2] );
849 if( isset( $wgActionPaths[$action] ) ) {
850 $query = $matches[1];
851 if( isset( $matches[4] ) ) $query .= $matches[4];
852 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
853 if( $query != '' ) $url .= '?' . $query;
856 if ( $url === false ) {
857 if ( $query == '-' ) {
860 $url = "{$wgScript}?title={$dbkey}&{$query}";
864 // FIXME: this causes breakage in various places when we
865 // actually expected a local URL and end up with dupe prefixes.
866 if ($wgRequest->getVal('action') == 'render') {
867 $url = $wgServer . $url;
870 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
875 * Get an HTML-escaped version of the URL form, suitable for
876 * using in a link, without a server name or fragment
877 * @param string $query an optional query string
878 * @return string the URL
881 function escapeLocalURL( $query = '' ) {
882 return htmlspecialchars( $this->getLocalURL( $query ) );
886 * Get an HTML-escaped version of the URL form, suitable for
887 * using in a link, including the server name and fragment
889 * @return string the URL
890 * @param string $query an optional query string
893 function escapeFullURL( $query = '' ) {
894 return htmlspecialchars( $this->getFullURL( $query ) );
898 * Get the URL form for an internal link.
899 * - Used in various Squid-related code, in case we have a different
900 * internal hostname for the server from the exposed one.
902 * @param string $query an optional query string
903 * @return string the URL
906 function getInternalURL( $query = '' ) {
907 global $wgInternalServer;
908 $url = $wgInternalServer . $this->getLocalURL( $query );
909 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
914 * Get the edit URL for this Title
915 * @return string the URL, or a null string if this is an
919 function getEditURL() {
920 if ( '' != $this->mInterwiki
) { return ''; }
921 $s = $this->getLocalURL( 'action=edit' );
927 * Get the HTML-escaped displayable text form.
928 * Used for the title field in <a> tags.
929 * @return string the text, including any prefixes
932 function getEscapedText() {
933 return htmlspecialchars( $this->getPrefixedText() );
937 * Is this Title interwiki?
941 function isExternal() { return ( '' != $this->mInterwiki
); }
944 * Is this page "semi-protected" - the *only* protection is autoconfirm?
946 * @param string Action to check (default: edit)
949 function isSemiProtected( $action = 'edit' ) {
950 $restrictions = $this->getRestrictions( $action );
951 # We do a full compare because this could be an array
952 foreach( $restrictions as $restriction ) {
953 if( strtolower( $restriction ) != 'autoconfirmed' ) {
961 * Does the title correspond to a protected article?
962 * @param string $what the action the page is protected from,
963 * by default checks move and edit
967 function isProtected( $action = '' ) {
968 global $wgRestrictionLevels;
969 if ( -1 == $this->mNamespace
) { return true; }
971 if( $action == 'edit' ||
$action == '' ) {
972 $r = $this->getRestrictions( 'edit' );
973 foreach( $wgRestrictionLevels as $level ) {
974 if( in_array( $level, $r ) && $level != '' ) {
980 if( $action == 'move' ||
$action == '' ) {
981 $r = $this->getRestrictions( 'move' );
982 foreach( $wgRestrictionLevels as $level ) {
983 if( in_array( $level, $r ) && $level != '' ) {
993 * Is $wgUser is watching this page?
997 function userIsWatching() {
1000 if ( is_null( $this->mWatched
) ) {
1001 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
1002 $this->mWatched
= false;
1004 $this->mWatched
= $wgUser->isWatched( $this );
1007 return $this->mWatched
;
1011 * Can $wgUser perform $action this page?
1012 * @param string $action action that permission needs to be checked for
1016 function userCan($action) {
1017 $fname = 'Title::userCan';
1018 wfProfileIn( $fname );
1023 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1024 if ( $result !== null ) {
1025 wfProfileOut( $fname );
1029 if( NS_SPECIAL
== $this->mNamespace
) {
1030 wfProfileOut( $fname );
1033 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1034 // from taking effect -ævar
1035 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1036 !$wgUser->isAllowed('editinterface') ) {
1037 wfProfileOut( $fname );
1041 if( $this->mDbkeyform
== '_' ) {
1042 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1043 wfProfileOut( $fname );
1047 # protect css/js subpages of user pages
1048 # XXX: this might be better using restrictions
1049 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1050 if( NS_USER
== $this->mNamespace
1051 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1052 && !$wgUser->isAllowed('editinterface')
1053 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1054 wfProfileOut( $fname );
1058 foreach( $this->getRestrictions($action) as $right ) {
1059 // Backwards compatibility, rewrite sysop -> protect
1060 if ( $right == 'sysop' ) {
1063 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1064 wfProfileOut( $fname );
1069 if( $action == 'move' &&
1070 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1071 wfProfileOut( $fname );
1075 if( $action == 'create' ) {
1076 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1077 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1082 wfProfileOut( $fname );
1087 * Can $wgUser edit this page?
1091 function userCanEdit() {
1092 return $this->userCan('edit');
1096 * Can $wgUser move this page?
1100 function userCanMove() {
1101 return $this->userCan('move');
1105 * Would anybody with sufficient privileges be able to move this page?
1106 * Some pages just aren't movable.
1111 function isMovable() {
1112 return Namespace::isMovable( $this->getNamespace() )
1113 && $this->getInterwiki() == '';
1117 * Can $wgUser read this page?
1121 function userCanRead() {
1125 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1126 if ( $result !== null ) {
1130 if( $wgUser->isAllowed('read') ) {
1133 global $wgWhitelistRead;
1135 /** If anon users can create an account,
1136 they need to reach the login page first! */
1137 if( $wgUser->isAllowed( 'createaccount' )
1138 && $this->getNamespace() == NS_SPECIAL
1139 && $this->getText() == 'Userlogin' ) {
1143 /** some pages are explicitly allowed */
1144 $name = $this->getPrefixedText();
1145 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1149 # Compatibility with old settings
1150 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1151 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1160 * Is this a talk page of some sort?
1164 function isTalkPage() {
1165 return Namespace::isTalk( $this->getNamespace() );
1169 * Is this a .css or .js subpage of a user page?
1173 function isCssJsSubpage() {
1174 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1177 * Is this a *valid* .css or .js subpage of a user page?
1178 * Check that the corresponding skin exists
1180 function isValidCssJsSubpage() {
1181 global $wgValidSkinNames;
1182 return( $this->isCssJsSubpage() && array_key_exists( $this->getSkinFromCssJsSubpage(), $wgValidSkinNames ) );
1185 * Trim down a .css or .js subpage title to get the corresponding skin name
1187 function getSkinFromCssJsSubpage() {
1188 $subpage = explode( '/', $this->mTextform
);
1189 $subpage = $subpage[ count( $subpage ) - 1 ];
1190 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1193 * Is this a .css subpage of a user page?
1197 function isCssSubpage() {
1198 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1201 * Is this a .js subpage of a user page?
1205 function isJsSubpage() {
1206 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1209 * Protect css/js subpages of user pages: can $wgUser edit
1213 * @todo XXX: this might be better using restrictions
1216 function userCanEditCssJsSubpage() {
1218 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1222 * Loads a string into mRestrictions array
1223 * @param string $res restrictions in string format
1226 function loadRestrictions( $res ) {
1227 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1228 $temp = explode( '=', trim( $restrict ) );
1229 if(count($temp) == 1) {
1230 // old format should be treated as edit/move restriction
1231 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1232 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1234 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1237 $this->mRestrictionsLoaded
= true;
1241 * Accessor/initialisation for mRestrictions
1242 * @param string $action action that permission needs to be checked for
1243 * @return array the array of groups allowed to edit this article
1246 function getRestrictions($action) {
1247 $id = $this->getArticleID();
1248 if ( 0 == $id ) { return array(); }
1250 if ( ! $this->mRestrictionsLoaded
) {
1251 $dbr =& wfGetDB( DB_SLAVE
);
1252 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1253 $this->loadRestrictions( $res );
1255 if( isset( $this->mRestrictions
[$action] ) ) {
1256 return $this->mRestrictions
[$action];
1262 * Is there a version of this page in the deletion archive?
1263 * @return int the number of archived revisions
1266 function isDeleted() {
1267 $fname = 'Title::isDeleted';
1268 if ( $this->getNamespace() < 0 ) {
1271 $dbr =& wfGetDB( DB_SLAVE
);
1272 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1273 'ar_title' => $this->getDBkey() ), $fname );
1274 if( $this->getNamespace() == NS_IMAGE
) {
1275 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1276 array( 'fa_name' => $this->getDBkey() ), $fname );
1283 * Get the article ID for this Title from the link cache,
1284 * adding it if necessary
1285 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1287 * @return int the ID
1290 function getArticleID( $flags = 0 ) {
1291 $linkCache =& LinkCache
::singleton();
1292 if ( $flags & GAID_FOR_UPDATE
) {
1293 $oldUpdate = $linkCache->forUpdate( true );
1294 $this->mArticleID
= $linkCache->addLinkObj( $this );
1295 $linkCache->forUpdate( $oldUpdate );
1297 if ( -1 == $this->mArticleID
) {
1298 $this->mArticleID
= $linkCache->addLinkObj( $this );
1301 return $this->mArticleID
;
1304 function getLatestRevID() {
1305 if ($this->mLatestID
!== false)
1306 return $this->mLatestID
;
1308 $db =& wfGetDB(DB_SLAVE
);
1309 return $this->mLatestID
= $db->selectField( 'revision',
1311 array('rev_page' => $this->getArticleID()),
1312 'Title::getLatestRevID' );
1316 * This clears some fields in this object, and clears any associated
1317 * keys in the "bad links" section of the link cache.
1319 * - This is called from Article::insertNewArticle() to allow
1320 * loading of the new page_id. It's also called from
1321 * Article::doDeleteArticle()
1323 * @param int $newid the new Article ID
1326 function resetArticleID( $newid ) {
1327 $linkCache =& LinkCache
::singleton();
1328 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1330 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1331 else { $this->mArticleID
= $newid; }
1332 $this->mRestrictionsLoaded
= false;
1333 $this->mRestrictions
= array();
1337 * Updates page_touched for this page; called from LinksUpdate.php
1338 * @return bool true if the update succeded
1341 function invalidateCache() {
1342 global $wgUseFileCache;
1344 if ( wfReadOnly() ) {
1348 $dbw =& wfGetDB( DB_MASTER
);
1349 $success = $dbw->update( 'page',
1351 'page_touched' => $dbw->timestamp()
1352 ), array( /* WHERE */
1353 'page_namespace' => $this->getNamespace() ,
1354 'page_title' => $this->getDBkey()
1355 ), 'Title::invalidateCache'
1358 if ($wgUseFileCache) {
1359 $cache = new CacheManager($this);
1360 @unlink
($cache->fileCacheName());
1367 * Prefix some arbitrary text with the namespace or interwiki prefix
1370 * @param string $name the text
1371 * @return string the prefixed text
1374 /* private */ function prefix( $name ) {
1378 if ( '' != $this->mInterwiki
) {
1379 $p = $this->mInterwiki
. ':';
1381 if ( 0 != $this->mNamespace
) {
1382 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1388 * Secure and split - main initialisation function for this object
1390 * Assumes that mDbkeyform has been set, and is urldecoded
1391 * and uses underscores, but not otherwise munged. This function
1392 * removes illegal characters, splits off the interwiki and
1393 * namespace prefixes, sets the other forms, and canonicalizes
1395 * @return bool true on success
1398 /* private */ function secureAndSplit() {
1399 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1400 $fname = 'Title::secureAndSplit';
1403 static $rxTc = false;
1405 # % is needed as well
1406 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1409 $this->mInterwiki
= $this->mFragment
= '';
1410 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1412 # Clean up whitespace
1414 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1415 $t = trim( $t, '_' );
1421 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1422 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1426 $this->mDbkeyform
= $t;
1428 # Initial colon indicates main namespace rather than specified default
1429 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1430 if ( ':' == $t{0} ) {
1431 $this->mNamespace
= NS_MAIN
;
1432 $t = substr( $t, 1 ); # remove the colon but continue processing
1435 # Namespace or interwiki prefix
1438 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1440 $lowerNs = strtolower( $p );
1441 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1442 # Canonical namespace
1444 $this->mNamespace
= $ns;
1445 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1446 # Ordinary namespace
1448 $this->mNamespace
= $ns;
1449 } elseif( $this->getInterwikiLink( $p ) ) {
1451 # Can't make a local interwiki link to an interwiki link.
1452 # That's just crazy!
1458 $this->mInterwiki
= strtolower( $p );
1460 # Redundant interwiki prefix to the local wiki
1461 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1463 # Can't have an empty self-link
1466 $this->mInterwiki
= '';
1468 # Do another namespace split...
1472 # If there's an initial colon after the interwiki, that also
1473 # resets the default namespace
1474 if ( $t !== '' && $t[0] == ':' ) {
1475 $this->mNamespace
= NS_MAIN
;
1476 $t = substr( $t, 1 );
1479 # If there's no recognized interwiki or namespace,
1480 # then let the colon expression be part of the title.
1486 # We already know that some pages won't be in the database!
1488 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1489 $this->mArticleID
= 0;
1491 $f = strstr( $r, '#' );
1492 if ( false !== $f ) {
1493 $this->mFragment
= substr( $f, 1 );
1494 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1495 # remove whitespace again: prevents "Foo_bar_#"
1496 # becoming "Foo_bar_"
1497 $r = preg_replace( '/_*$/', '', $r );
1500 # Reject illegal characters.
1502 if( preg_match( $rxTc, $r ) ) {
1507 * Pages with "/./" or "/../" appearing in the URLs will
1508 * often be unreachable due to the way web browsers deal
1509 * with 'relative' URLs. Forbid them explicitly.
1511 if ( strpos( $r, '.' ) !== false &&
1512 ( $r === '.' ||
$r === '..' ||
1513 strpos( $r, './' ) === 0 ||
1514 strpos( $r, '../' ) === 0 ||
1515 strpos( $r, '/./' ) !== false ||
1516 strpos( $r, '/../' ) !== false ) )
1521 # We shouldn't need to query the DB for the size.
1522 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1523 if ( strlen( $r ) > 255 ) {
1528 * Normally, all wiki links are forced to have
1529 * an initial capital letter so [[foo]] and [[Foo]]
1530 * point to the same place.
1532 * Don't force it for interwikis, since the other
1533 * site might be case-sensitive.
1535 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1536 $t = $wgContLang->ucfirst( $r );
1542 * Can't make a link to a namespace alone...
1543 * "empty" local links can only be self-links
1544 * with a fragment identifier.
1547 $this->mInterwiki
== '' &&
1548 $this->mNamespace
!= NS_MAIN
) {
1552 // Any remaining initial :s are illegal.
1553 if ( $t !== '' && ':' == $t{0} ) {
1558 $this->mDbkeyform
= $t;
1559 $this->mUrlform
= wfUrlencode( $t );
1561 $this->mTextform
= str_replace( '_', ' ', $t );
1567 * Get a Title object associated with the talk page of this article
1568 * @return Title the object for the talk page
1571 function getTalkPage() {
1572 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1576 * Get a title object associated with the subject page of this
1579 * @return Title the object for the subject page
1582 function getSubjectPage() {
1583 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1587 * Get an array of Title objects linking to this Title
1588 * Also stores the IDs in the link cache.
1590 * WARNING: do not use this function on arbitrary user-supplied titles!
1591 * On heavily-used templates it will max out the memory.
1593 * @param string $options may be FOR UPDATE
1594 * @return array the Title objects linking here
1597 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1598 $linkCache =& LinkCache
::singleton();
1599 $id = $this->getArticleID();
1602 $db =& wfGetDB( DB_MASTER
);
1604 $db =& wfGetDB( DB_SLAVE
);
1607 $res = $db->select( array( 'page', $table ),
1608 array( 'page_namespace', 'page_title', 'page_id' ),
1610 "{$prefix}_from=page_id",
1611 "{$prefix}_namespace" => $this->getNamespace(),
1612 "{$prefix}_title" => $this->getDbKey() ),
1613 'Title::getLinksTo',
1617 if ( $db->numRows( $res ) ) {
1618 while ( $row = $db->fetchObject( $res ) ) {
1619 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1620 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1621 $retVal[] = $titleObj;
1625 $db->freeResult( $res );
1630 * Get an array of Title objects using this Title as a template
1631 * Also stores the IDs in the link cache.
1633 * WARNING: do not use this function on arbitrary user-supplied titles!
1634 * On heavily-used templates it will max out the memory.
1636 * @param string $options may be FOR UPDATE
1637 * @return array the Title objects linking here
1640 function getTemplateLinksTo( $options = '' ) {
1641 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1645 * Get an array of Title objects referring to non-existent articles linked from this page
1647 * @param string $options may be FOR UPDATE
1648 * @return array the Title objects
1651 function getBrokenLinksFrom( $options = '' ) {
1653 $db =& wfGetDB( DB_MASTER
);
1655 $db =& wfGetDB( DB_SLAVE
);
1658 $res = $db->safeQuery(
1659 "SELECT pl_namespace, pl_title
1662 ON pl_namespace=page_namespace
1663 AND pl_title=page_title
1665 AND page_namespace IS NULL
1667 $db->tableName( 'pagelinks' ),
1668 $db->tableName( 'page' ),
1669 $this->getArticleId(),
1673 if ( $db->numRows( $res ) ) {
1674 while ( $row = $db->fetchObject( $res ) ) {
1675 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1678 $db->freeResult( $res );
1684 * Get a list of URLs to purge from the Squid cache when this
1687 * @return array the URLs
1690 function getSquidURLs() {
1692 $this->getInternalURL(),
1693 $this->getInternalURL( 'action=history' )
1697 function purgeSquid() {
1699 if ( $wgUseSquid ) {
1700 $urls = $this->getSquidURLs();
1701 $u = new SquidUpdate( $urls );
1707 * Move this page without authentication
1708 * @param Title &$nt the new page Title
1711 function moveNoAuth( &$nt ) {
1712 return $this->moveTo( $nt, false );
1716 * Check whether a given move operation would be valid.
1717 * Returns true if ok, or a message key string for an error message
1718 * if invalid. (Scarrrrry ugly interface this.)
1719 * @param Title &$nt the new title
1720 * @param bool $auth indicates whether $wgUser's permissions
1722 * @return mixed true on success, message name on failure
1725 function isValidMoveOperation( &$nt, $auth = true ) {
1726 if( !$this or !$nt ) {
1727 return 'badtitletext';
1729 if( $this->equals( $nt ) ) {
1732 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1733 return 'immobile_namespace';
1736 $oldid = $this->getArticleID();
1737 $newid = $nt->getArticleID();
1739 if ( strlen( $nt->getDBkey() ) < 1 ) {
1740 return 'articleexists';
1742 if ( ( '' == $this->getDBkey() ) ||
1744 ( '' == $nt->getDBkey() ) ) {
1745 return 'badarticleerror';
1749 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1750 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1751 return 'protectedpage';
1754 # The move is allowed only if (1) the target doesn't exist, or
1755 # (2) the target is a redirect to the source, and has no history
1756 # (so we can undo bad moves right after they're done).
1758 if ( 0 != $newid ) { # Target exists; check for validity
1759 if ( ! $this->isValidMoveTarget( $nt ) ) {
1760 return 'articleexists';
1767 * Move a title to a new location
1768 * @param Title &$nt the new title
1769 * @param bool $auth indicates whether $wgUser's permissions
1771 * @return mixed true on success, message name on failure
1774 function moveTo( &$nt, $auth = true, $reason = '' ) {
1775 $err = $this->isValidMoveOperation( $nt, $auth );
1776 if( is_string( $err ) ) {
1780 $pageid = $this->getArticleID();
1781 if( $nt->exists() ) {
1782 $this->moveOverExistingRedirect( $nt, $reason );
1783 $pageCountChange = 0;
1784 } else { # Target didn't exist, do normal move.
1785 $this->moveToNewTitle( $nt, $reason );
1786 $pageCountChange = 1;
1788 $redirid = $this->getArticleID();
1790 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1791 $dbw =& wfGetDB( DB_MASTER
);
1792 $categorylinks = $dbw->tableName( 'categorylinks' );
1793 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1794 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1795 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1796 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1800 $oldnamespace = $this->getNamespace() & ~
1;
1801 $newnamespace = $nt->getNamespace() & ~
1;
1802 $oldtitle = $this->getDBkey();
1803 $newtitle = $nt->getDBkey();
1805 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1806 WatchedItem
::duplicateEntries( $this, $nt );
1809 # Update search engine
1810 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1812 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1816 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1817 # Moved out of main namespace
1818 # not viewed, edited, removing
1819 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1820 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1821 # Moved into main namespace
1822 # not viewed, edited, adding
1823 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1824 } elseif ( $pageCountChange ) {
1826 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1835 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1840 * Move page to a title which is at present a redirect to the
1843 * @param Title &$nt the page to move to, which should currently
1847 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1848 global $wgUseSquid, $wgMwRedir;
1849 $fname = 'Title::moveOverExistingRedirect';
1850 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1853 $comment .= ": $reason";
1856 $now = wfTimestampNow();
1858 $newid = $nt->getArticleID();
1859 $oldid = $this->getArticleID();
1860 $dbw =& wfGetDB( DB_MASTER
);
1861 $linkCache =& LinkCache
::singleton();
1863 # Delete the old redirect. We don't save it to history since
1864 # by definition if we've got here it's rather uninteresting.
1865 # We have to remove it so that the next step doesn't trigger
1866 # a conflict on the unique namespace+title index...
1867 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1869 # Save a null revision in the page's history notifying of the move
1870 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1871 $nullRevId = $nullRevision->insertOn( $dbw );
1873 # Change the name of the target page:
1874 $dbw->update( 'page',
1876 'page_touched' => $dbw->timestamp($now),
1877 'page_namespace' => $nt->getNamespace(),
1878 'page_title' => $nt->getDBkey(),
1879 'page_latest' => $nullRevId,
1881 /* WHERE */ array( 'page_id' => $oldid ),
1884 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1886 # Recreate the redirect, this time in the other direction.
1887 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1888 $redirectArticle = new Article( $this );
1889 $newid = $redirectArticle->insertOn( $dbw );
1890 $redirectRevision = new Revision( array(
1892 'comment' => $comment,
1893 'text' => $redirectText ) );
1894 $revid = $redirectRevision->insertOn( $dbw );
1895 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1896 $linkCache->clearLink( $this->getPrefixedDBkey() );
1899 $log = new LogPage( 'move' );
1900 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1902 # Now, we record the link from the redirect to the new title.
1903 # It should have no other outgoing links...
1904 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1905 $dbw->insert( 'pagelinks',
1907 'pl_from' => $newid,
1908 'pl_namespace' => $nt->getNamespace(),
1909 'pl_title' => $nt->getDbKey() ),
1913 if ( $wgUseSquid ) {
1914 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1915 $u = new SquidUpdate( $urls );
1921 * Move page to non-existing title.
1922 * @param Title &$nt the new Title
1925 function moveToNewTitle( &$nt, $reason = '' ) {
1928 $fname = 'MovePageForm::moveToNewTitle';
1929 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1931 $comment .= ": $reason";
1934 $newid = $nt->getArticleID();
1935 $oldid = $this->getArticleID();
1936 $dbw =& wfGetDB( DB_MASTER
);
1937 $now = $dbw->timestamp();
1939 $linkCache =& LinkCache
::singleton();
1941 # Save a null revision in the page's history notifying of the move
1942 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1943 $nullRevId = $nullRevision->insertOn( $dbw );
1946 $dbw->update( 'page',
1948 'page_touched' => $now,
1949 'page_namespace' => $nt->getNamespace(),
1950 'page_title' => $nt->getDBkey(),
1951 'page_latest' => $nullRevId,
1953 /* WHERE */ array( 'page_id' => $oldid ),
1957 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1960 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1961 $redirectArticle = new Article( $this );
1962 $newid = $redirectArticle->insertOn( $dbw );
1963 $redirectRevision = new Revision( array(
1965 'comment' => $comment,
1966 'text' => $redirectText ) );
1967 $revid = $redirectRevision->insertOn( $dbw );
1968 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1969 $linkCache->clearLink( $this->getPrefixedDBkey() );
1972 $log = new LogPage( 'move' );
1973 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1975 # Purge caches as per article creation
1976 Article
::onArticleCreate( $nt );
1978 # Record the just-created redirect's linking to the page
1979 $dbw->insert( 'pagelinks',
1981 'pl_from' => $newid,
1982 'pl_namespace' => $nt->getNamespace(),
1983 'pl_title' => $nt->getDBkey() ),
1986 # Purge old title from squid
1987 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1988 $this->purgeSquid();
1992 * Checks if $this can be moved to a given Title
1993 * - Selects for update, so don't call it unless you mean business
1995 * @param Title &$nt the new title to check
1998 function isValidMoveTarget( $nt ) {
2000 $fname = 'Title::isValidMoveTarget';
2001 $dbw =& wfGetDB( DB_MASTER
);
2004 $id = $nt->getArticleID();
2005 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2006 array( 'page_is_redirect','old_text','old_flags' ),
2007 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2008 $fname, 'FOR UPDATE' );
2010 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2012 wfDebug( __METHOD__
. ": not a redirect\n" );
2015 $text = Revision
::getRevisionText( $obj );
2017 # Does the redirect point to the source?
2018 # Or is it a broken self-redirect, usually caused by namespace collisions?
2019 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2020 $redirTitle = Title
::newFromText( $m[1] );
2021 if( !is_object( $redirTitle ) ||
2022 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2023 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2024 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2029 wfDebug( __METHOD__
. ": failsafe\n" );
2033 # Does the article have a history?
2034 $row = $dbw->selectRow( array( 'page', 'revision'),
2036 array( 'page_namespace' => $nt->getNamespace(),
2037 'page_title' => $nt->getDBkey(),
2038 'page_id=rev_page AND page_latest != rev_id'
2039 ), $fname, 'FOR UPDATE'
2042 # Return true if there was no history
2043 return $row === false;
2047 * Create a redirect; fails if the title already exists; does
2050 * @param Title $dest the destination of the redirect
2051 * @param string $comment the comment string describing the move
2052 * @return bool true on success
2055 function createRedirect( $dest, $comment ) {
2056 if ( $this->getArticleID() ) {
2060 $fname = 'Title::createRedirect';
2061 $dbw =& wfGetDB( DB_MASTER
);
2063 $article = new Article( $this );
2064 $newid = $article->insertOn( $dbw );
2065 $revision = new Revision( array(
2067 'comment' => $comment,
2068 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2070 $revisionId = $revision->insertOn( $dbw );
2071 $article->updateRevisionOn( $dbw, $revision, 0 );
2074 $dbw->insert( 'pagelinks',
2076 'pl_from' => $newid,
2077 'pl_namespace' => $dest->getNamespace(),
2078 'pl_title' => $dest->getDbKey()
2082 Article
::onArticleCreate( $this );
2087 * Get categories to which this Title belongs and return an array of
2088 * categories' names.
2090 * @return array an array of parents in the form:
2091 * $parent => $currentarticle
2094 function getParentCategories() {
2097 $titlekey = $this->getArticleId();
2098 $dbr =& wfGetDB( DB_SLAVE
);
2099 $categorylinks = $dbr->tableName( 'categorylinks' );
2102 $sql = "SELECT * FROM $categorylinks"
2103 ." WHERE cl_from='$titlekey'"
2104 ." AND cl_from <> '0'"
2105 ." ORDER BY cl_sortkey";
2107 $res = $dbr->query ( $sql ) ;
2109 if($dbr->numRows($res) > 0) {
2110 while ( $x = $dbr->fetchObject ( $res ) )
2111 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2112 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2113 $dbr->freeResult ( $res ) ;
2121 * Get a tree of parent categories
2122 * @param array $children an array with the children in the keys, to check for circular refs
2126 function getParentCategoryTree( $children = array() ) {
2127 $parents = $this->getParentCategories();
2129 if($parents != '') {
2130 foreach($parents as $parent => $current) {
2131 if ( array_key_exists( $parent, $children ) ) {
2132 # Circular reference
2133 $stack[$parent] = array();
2135 $nt = Title
::newFromText($parent);
2136 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2147 * Get an associative array for selecting this title from
2153 function pageCond() {
2154 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2158 * Get the revision ID of the previous revision
2160 * @param integer $revision Revision ID. Get the revision that was before this one.
2161 * @return interger $oldrevision|false
2163 function getPreviousRevisionID( $revision ) {
2164 $dbr =& wfGetDB( DB_SLAVE
);
2165 return $dbr->selectField( 'revision', 'rev_id',
2166 'rev_page=' . intval( $this->getArticleId() ) .
2167 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2171 * Get the revision ID of the next revision
2173 * @param integer $revision Revision ID. Get the revision that was after this one.
2174 * @return interger $oldrevision|false
2176 function getNextRevisionID( $revision ) {
2177 $dbr =& wfGetDB( DB_SLAVE
);
2178 return $dbr->selectField( 'revision', 'rev_id',
2179 'rev_page=' . intval( $this->getArticleId() ) .
2180 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2184 * Compare with another title.
2186 * @param Title $title
2189 function equals( $title ) {
2190 // Note: === is necessary for proper matching of number-like titles.
2191 return $this->getInterwiki() === $title->getInterwiki()
2192 && $this->getNamespace() == $title->getNamespace()
2193 && $this->getDbkey() === $title->getDbkey();
2197 * Check if page exists
2201 return $this->getArticleId() != 0;
2205 * Should a link should be displayed as a known link, just based on its title?
2207 * Currently, a self-link with a fragment and special pages are in
2208 * this category. Special pages never exist in the database.
2210 function isAlwaysKnown() {
2211 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2212 || NS_SPECIAL
== $this->mNamespace
;
2216 * Update page_touched timestamps and send squid purge messages for
2217 * pages linking to this title. May be sent to the job queue depending
2218 * on the number of links. Typically called on create and delete.
2220 function touchLinks() {
2221 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2224 if ( $this->getNamespace() == NS_CATEGORY
) {
2225 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2230 function trackbackURL() {
2231 global $wgTitle, $wgScriptPath, $wgServer;
2233 return "$wgServer$wgScriptPath/trackback.php?article="
2234 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2237 function trackbackRDF() {
2238 $url = htmlspecialchars($this->getFullURL());
2239 $title = htmlspecialchars($this->getText());
2240 $tburl = $this->trackbackURL();
2243 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2244 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2245 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2248 dc:identifier=\"$url\"
2250 trackback:ping=\"$tburl\" />
2255 * Generate strings used for xml 'id' names in monobook tabs
2258 function getNamespaceKey() {
2259 switch ($this->getNamespace()) {
2262 return 'nstab-main';
2265 return 'nstab-user';
2267 return 'nstab-media';
2269 return 'nstab-special';
2271 case NS_PROJECT_TALK
:
2272 return 'nstab-project';
2275 return 'nstab-image';
2277 case NS_MEDIAWIKI_TALK
:
2278 return 'nstab-mediawiki';
2280 case NS_TEMPLATE_TALK
:
2281 return 'nstab-template';
2284 return 'nstab-help';
2286 case NS_CATEGORY_TALK
:
2287 return 'nstab-category';
2289 return 'nstab-' . strtolower( $this->getSubjectNsText() );