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 private $mTextform; # Text form (spaces not underscores) of the main part
41 private $mUrlform; # URL-encoded form of the main part
42 private $mDbkeyform; # Main part with underscores
43 private $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 private $mInterwiki; # Interwiki prefix (or null string)
45 private $mFragment; # Title fragment (i.e. the bit after the #)
46 private $mLatestID; # ID of most recent revision
47 private $mRestrictions; # Array of groups allowed to edit this article
48 # Only null or "sysop" are supported
49 private $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
50 private $mDefaultNamespace; # Namespace index when there is no namespace
51 # Zero except in {{transclusion}} tags
52 private $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
55 /** @todo FIXME should those be public ? */
56 public $mArticleID; # Article ID, fetched from the link cache on demand
57 public $mRestrictionsLoaded; # Boolean for initialisation on demand
63 /* private */ function Title() {
64 $this->mInterwiki
= $this->mUrlform
=
65 $this->mTextform
= $this->mDbkeyform
= '';
66 $this->mArticleID
= -1;
67 $this->mNamespace
= NS_MAIN
;
68 $this->mRestrictionsLoaded
= false;
69 $this->mRestrictions
= array();
70 # Dont change the following, NS_MAIN is hardcoded in several place
72 $this->mDefaultNamespace
= NS_MAIN
;
73 $this->mWatched
= NULL;
74 $this->mLatestID
= false;
78 * Create a new Title from a prefixed DB key
79 * @param string $key The database key, which has underscores
80 * instead of spaces, possibly including namespace and
82 * @return Title the new object, or NULL on an error
86 /* static */ function newFromDBkey( $key ) {
88 $t->mDbkeyform
= $key;
89 if( $t->secureAndSplit() )
96 * Create a new Title from text, such as what one would
97 * find in a link. Decodes any HTML entities in the text.
99 * @param string $text the link text; spaces, prefixes,
100 * and an initial ':' indicating the main namespace
102 * @param int $defaultNamespace the namespace to use if
103 * none is specified by a prefix
104 * @return Title the new object, or NULL on an error
108 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
109 global $wgTitleCache;
110 $fname = 'Title::newFromText';
112 if( is_object( $text ) ) {
113 wfDebugDieBacktrace( 'Title::newFromText given an object' );
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
122 * In theory these are value objects and won't get changed...
124 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
125 return $wgTitleCache[$text];
129 * Convert things like é ā or 〗 into real text...
131 $filteredText = Sanitizer
::decodeCharReferences( $text );
134 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace
= $defaultNamespace;
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN
) {
140 if( $cachedcount >= MW_TITLECACHE_MAX
) {
141 # Avoid memory leaks on mass operations...
142 $wgTitleCache = array();
146 $wgTitleCache[$text] =& $t;
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
163 function newFromURL( $url ) {
164 global $wgLegalTitleChars;
167 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
168 # but some URLs used it as a space replacement and they still come
169 # from some external search tools.
170 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
171 $url = str_replace( '+', ' ', $url );
174 $t->mDbkeyform
= str_replace( ' ', '_', $url );
175 if( $t->secureAndSplit() ) {
183 * Create a new Title from an article ID
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
193 function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE
);
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
207 * Create a new Title from a namespace index and a DB key.
208 * It's assumed that $ns and $title are *valid*, for instance when
209 * they came directly from the database or a special page name.
210 * For convenience, spaces are converted to underscores so that
211 * eg user_text fields can be used directly.
213 * @param int $ns the namespace of the article
214 * @param string $title the unprefixed database key form
215 * @return Title the new object
219 public static function &makeTitle( $ns, $title ) {
223 $t->mNamespace
= intval( $ns );
224 $t->mDbkeyform
= str_replace( ' ', '_', $title );
225 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
226 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
227 $t->mTextform
= str_replace( '_', ' ', $title );
232 * Create a new Title frrom a namespace index and a DB key.
233 * The parameters will be checked for validity, which is a bit slower
234 * than makeTitle() but safer for user-provided data.
236 * @param int $ns the namespace of the article
237 * @param string $title the database key form
238 * @return Title the new object, or NULL on an error
242 public static function makeTitleSafe( $ns, $title ) {
244 $t->mDbkeyform
= Title
::makeName( $ns, $title );
245 if( $t->secureAndSplit() ) {
253 * Create a new Title for the Main Page
256 * @return Title the new object
259 function newMainPage() {
260 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
264 * Create a new Title for a redirect
265 * @param string $text the redirect title text
266 * @return Title the new object, or NULL if the text is not a
271 function newFromRedirect( $text ) {
274 if ( $wgMwRedir->matchStart( $text ) ) {
275 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
276 # categories are escaped using : for example one can enter:
277 # #REDIRECT [[:Category:Music]]. Need to remove it.
278 if ( substr($m[1],0,1) == ':') {
279 # We don't want to keep the ':'
280 $m[1] = substr( $m[1], 1 );
283 $rt = Title
::newFromText( $m[1] );
284 # Disallow redirects to Special:Userlogout
285 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
293 #----------------------------------------------------------------------------
295 #----------------------------------------------------------------------------
298 * Get the prefixed DB key associated with an ID
299 * @param int $id the page_id of the article
300 * @return Title an object representing the article, or NULL
301 * if no such article was found
305 function nameOf( $id ) {
306 $fname = 'Title::nameOf';
307 $dbr =& wfGetDB( DB_SLAVE
);
309 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
310 if ( $s === false ) { return NULL; }
312 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
317 * Get a regex character class describing the legal characters in a link
318 * @return string the list of characters, not delimited
322 function legalChars() {
323 global $wgLegalTitleChars;
324 return $wgLegalTitleChars;
328 * Get a string representation of a title suitable for
329 * including in a search index
331 * @param int $ns a namespace index
332 * @param string $title text-form main part
333 * @return string a stripped-down title string ready for the
336 /* static */ function indexTitle( $ns, $title ) {
338 require_once( 'SearchEngine.php' );
340 $lc = SearchEngine
::legalSearchChars() . '&#;';
341 $t = $wgContLang->stripForSearch( $title );
342 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
343 $t = strtolower( $t );
346 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
347 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
349 $t = preg_replace( "/\\s+/", ' ', $t );
351 if ( $ns == NS_IMAGE
) {
352 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
358 * Make a prefixed DB key from a DB key and a namespace index
359 * @param int $ns numerical representation of the namespace
360 * @param string $title the DB key form the title
361 * @return string the prefixed form of the title
363 public static function makeName( $ns, $title ) {
366 $n = $wgContLang->getNsText( $ns );
367 return $n == '' ?
$title : "$n:$title";
371 * Returns the URL associated with an interwiki prefix
372 * @param string $key the interwiki prefix (e.g. "MeatBall")
373 * @return the associated URL, containing "$1", which should be
374 * replaced by an article title
378 function getInterwikiLink( $key ) {
379 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
380 global $wgInterwikiCache;
381 $fname = 'Title::getInterwikiLink';
383 $key = strtolower( $key );
385 $k = $wgDBname.':interwiki:'.$key;
386 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
387 return $wgTitleInterwikiCache[$k]->iw_url
;
390 if ($wgInterwikiCache) {
391 return Title
::getInterwikiCached( $key );
394 $s = $wgMemc->get( $k );
395 # Ignore old keys with no iw_local
396 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
397 $wgTitleInterwikiCache[$k] = $s;
401 $dbr =& wfGetDB( DB_SLAVE
);
402 $res = $dbr->select( 'interwiki',
403 array( 'iw_url', 'iw_local', 'iw_trans' ),
404 array( 'iw_prefix' => $key ), $fname );
409 $s = $dbr->fetchObject( $res );
411 # Cache non-existence: create a blank object and save it to memcached
417 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
418 $wgTitleInterwikiCache[$k] = $s;
424 * Fetch interwiki prefix data from local cache in constant database
426 * More logic is explained in DefaultSettings
428 * @return string URL of interwiki site
431 function getInterwikiCached( $key ) {
432 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
433 global $wgTitleInterwikiCache;
437 $db=dba_open($wgInterwikiCache,'r','cdb');
438 /* Resolve site name */
439 if ($wgInterwikiScopes>=3 and !$site) {
440 $site = dba_fetch("__sites:{$wgDBname}", $db);
442 $site = $wgInterwikiFallbackSite;
444 $value = dba_fetch("{$wgDBname}:{$key}", $db);
445 if ($value=='' and $wgInterwikiScopes>=3) {
447 $value = dba_fetch("_{$site}:{$key}", $db);
449 if ($value=='' and $wgInterwikiScopes>=2) {
451 $value = dba_fetch("__global:{$key}", $db);
460 list($local,$url)=explode(' ',$value,2);
462 $s->iw_local
=(int)$local;
464 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
468 * Determine whether the object refers to a page within
471 * @return bool TRUE if this is an in-project interwiki link
472 * or a wikilink, FALSE otherwise
476 global $wgTitleInterwikiCache, $wgDBname;
478 if ( $this->mInterwiki
!= '' ) {
479 # Make sure key is loaded into cache
480 $this->getInterwikiLink( $this->mInterwiki
);
481 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
482 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
489 * Determine whether the object refers to a page within
490 * this project and is transcludable.
492 * @return bool TRUE if this is transcludable
496 global $wgTitleInterwikiCache, $wgDBname;
498 if ($this->mInterwiki
== '')
500 # Make sure key is loaded into cache
501 $this->getInterwikiLink( $this->mInterwiki
);
502 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
503 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
507 * Update the page_touched field for an array of title objects
508 * @todo Inefficient unless the IDs are already loaded into the
510 * @param array $titles an array of Title objects to be touched
511 * @param string $timestamp the timestamp to use instead of the
512 * default current time
516 function touchArray( $titles, $timestamp = '' ) {
518 if ( count( $titles ) == 0 ) {
521 $dbw =& wfGetDB( DB_MASTER
);
522 if ( $timestamp == '' ) {
523 $timestamp = $dbw->timestamp();
526 $page = $dbw->tableName( 'page' );
527 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
530 foreach ( $titles as $title ) {
531 if ( $wgUseFileCache ) {
532 $cm = new CacheManager($title);
533 @unlink($cm->fileCacheName());
540 $sql .= $title->getArticleID();
544 $dbw->query( $sql, 'Title::touchArray' );
547 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
548 // do them in small chunks:
549 $fname = 'Title::touchArray';
550 foreach( $titles as $title ) {
551 $dbw->update( 'page',
552 array( 'page_touched' => $timestamp ),
554 'page_namespace' => $title->getNamespace(),
555 'page_title' => $title->getDBkey() ),
560 #----------------------------------------------------------------------------
562 #----------------------------------------------------------------------------
564 /** Simple accessors */
566 * Get the text form (spaces not underscores) of the main part
570 function getText() { return $this->mTextform
; }
572 * Get the URL-encoded form of the main part
576 function getPartialURL() { return $this->mUrlform
; }
578 * Get the main part with underscores
582 function getDBkey() { return $this->mDbkeyform
; }
584 * Get the namespace index, i.e. one of the NS_xxxx constants
588 function getNamespace() { return $this->mNamespace
; }
590 * Get the namespace text
594 function getNsText() {
596 return $wgContLang->getNsText( $this->mNamespace
);
599 * Get the namespace text of the subject (rather than talk) page
603 function getSubjectNsText() {
605 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
609 * Get the namespace text of the talk page
612 function getTalkNsText() {
614 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
618 * Could this title have a corresponding talk page?
622 return( Namespace::canTalk( $this->mNamespace
) );
626 * Get the interwiki prefix (or null string)
630 function getInterwiki() { return $this->mInterwiki
; }
632 * Get the Title fragment (i.e. the bit after the #)
636 function getFragment() { return $this->mFragment
; }
638 * Get the default namespace index, for when there is no namespace
642 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
645 * Get title for search index
646 * @return string a stripped-down title string ready for the
649 function getIndexTitle() {
650 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
654 * Get the prefixed database key form
655 * @return string the prefixed title, with underscores and
656 * any interwiki and namespace prefixes
659 function getPrefixedDBkey() {
660 $s = $this->prefix( $this->mDbkeyform
);
661 $s = str_replace( ' ', '_', $s );
666 * Get the prefixed title with spaces.
667 * This is the form usually used for display
668 * @return string the prefixed title, with spaces
671 function getPrefixedText() {
672 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
673 $s = $this->prefix( $this->mTextform
);
674 $s = str_replace( '_', ' ', $s );
675 $this->mPrefixedText
= $s;
677 return $this->mPrefixedText
;
681 * Get the prefixed title with spaces, plus any fragment
682 * (part beginning with '#')
683 * @return string the prefixed title, with spaces and
684 * the fragment, including '#'
687 function getFullText() {
688 $text = $this->getPrefixedText();
689 if( '' != $this->mFragment
) {
690 $text .= '#' . $this->mFragment
;
696 * Get the lowest-level subpage name, i.e. the rightmost part after /
697 * @return string Subpage name
699 function getSubpageText() {
700 global $wgNamespacesWithSubpages;
701 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
702 $parts = explode( '/', $this->mTextform
);
703 return( $parts[ count( $parts ) - 1 ] );
705 return( $this->mTextform
);
710 * Get a URL-encoded form of the subpage text
711 * @return string URL-encoded subpage name
713 function getSubpageUrlForm() {
714 $text = $this->getSubpageText();
715 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
716 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
721 * Get a URL-encoded title (not an actual URL) including interwiki
722 * @return string the URL-encoded form
725 function getPrefixedURL() {
726 $s = $this->prefix( $this->mDbkeyform
);
727 $s = str_replace( ' ', '_', $s );
729 $s = wfUrlencode ( $s ) ;
731 # Cleaning up URL to make it look nice -- is this safe?
732 $s = str_replace( '%28', '(', $s );
733 $s = str_replace( '%29', ')', $s );
739 * Get a real URL referring to this title, with interwiki link and
742 * @param string $query an optional query string, not used
743 * for interwiki links
744 * @return string the URL
747 function getFullURL( $query = '' ) {
748 global $wgContLang, $wgServer, $wgRequest;
750 if ( '' == $this->mInterwiki
) {
751 $url = $this->getLocalUrl( $query );
753 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
754 // Correct fix would be to move the prepending elsewhere.
755 if ($wgRequest->getVal('action') != 'render') {
756 $url = $wgServer . $url;
759 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
761 $namespace = $wgContLang->getNsText( $this->mNamespace
);
762 if ( '' != $namespace ) {
763 # Can this actually happen? Interwikis shouldn't be parsed.
766 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
768 if( false === strpos( $url, '?' ) ) {
777 # Finally, add the fragment.
778 if ( '' != $this->mFragment
) {
779 $url .= '#' . $this->mFragment
;
782 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
787 * Get a URL with no fragment or server name. If this page is generated
788 * with action=render, $wgServer is prepended.
789 * @param string $query an optional query string; if not specified,
790 * $wgArticlePath will be used.
791 * @return string the URL
794 function getLocalURL( $query = '' ) {
795 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
797 if ( $this->isExternal() ) {
798 $url = $this->getFullURL();
800 // This is currently only used for edit section links in the
801 // context of interwiki transclusion. In theory we should
802 // append the query to the end of any existing query string,
803 // but interwiki transclusion is already broken in that case.
807 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
808 if ( $query == '' ) {
809 $url = str_replace( '$1', $dbkey, $wgArticlePath );
811 global $wgActionPaths;
813 if( !empty( $wgActionPaths ) &&
814 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
816 $action = urldecode( $matches[2] );
817 if( isset( $wgActionPaths[$action] ) ) {
818 $query = $matches[1];
819 if( isset( $matches[4] ) ) $query .= $matches[4];
820 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
821 if( $query != '' ) $url .= '?' . $query;
824 if ( $url === false ) {
825 if ( $query == '-' ) {
828 $url = "{$wgScript}?title={$dbkey}&{$query}";
832 // FIXME: this causes breakage in various places when we
833 // actually expected a local URL and end up with dupe prefixes.
834 if ($wgRequest->getVal('action') == 'render') {
835 $url = $wgServer . $url;
838 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
843 * Get an HTML-escaped version of the URL form, suitable for
844 * using in a link, without a server name or fragment
845 * @param string $query an optional query string
846 * @return string the URL
849 function escapeLocalURL( $query = '' ) {
850 return htmlspecialchars( $this->getLocalURL( $query ) );
854 * Get an HTML-escaped version of the URL form, suitable for
855 * using in a link, including the server name and fragment
857 * @return string the URL
858 * @param string $query an optional query string
861 function escapeFullURL( $query = '' ) {
862 return htmlspecialchars( $this->getFullURL( $query ) );
866 * Get the URL form for an internal link.
867 * - Used in various Squid-related code, in case we have a different
868 * internal hostname for the server from the exposed one.
870 * @param string $query an optional query string
871 * @return string the URL
874 function getInternalURL( $query = '' ) {
875 global $wgInternalServer;
876 $url = $wgInternalServer . $this->getLocalURL( $query );
877 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
882 * Get the edit URL for this Title
883 * @return string the URL, or a null string if this is an
887 function getEditURL() {
888 if ( '' != $this->mInterwiki
) { return ''; }
889 $s = $this->getLocalURL( 'action=edit' );
895 * Get the HTML-escaped displayable text form.
896 * Used for the title field in <a> tags.
897 * @return string the text, including any prefixes
900 function getEscapedText() {
901 return htmlspecialchars( $this->getPrefixedText() );
905 * Is this Title interwiki?
909 function isExternal() { return ( '' != $this->mInterwiki
); }
912 * Is this page "semi-protected" - the *only* protection is autoconfirm?
914 * @param string Action to check (default: edit)
917 function isSemiProtected( $action = 'edit' ) {
918 $restrictions = $this->getRestrictions( $action );
919 # We do a full compare because this could be an array
920 foreach( $restrictions as $restriction ) {
921 if( strtolower( $restriction ) != 'autoconfirmed' ) {
929 * Does the title correspond to a protected article?
930 * @param string $what the action the page is protected from,
931 * by default checks move and edit
935 function isProtected( $action = '' ) {
936 global $wgRestrictionLevels;
937 if ( -1 == $this->mNamespace
) { return true; }
939 if( $action == 'edit' ||
$action == '' ) {
940 $r = $this->getRestrictions( 'edit' );
941 foreach( $wgRestrictionLevels as $level ) {
942 if( in_array( $level, $r ) && $level != '' ) {
948 if( $action == 'move' ||
$action == '' ) {
949 $r = $this->getRestrictions( 'move' );
950 foreach( $wgRestrictionLevels as $level ) {
951 if( in_array( $level, $r ) && $level != '' ) {
961 * Is $wgUser is watching this page?
965 function userIsWatching() {
968 if ( is_null( $this->mWatched
) ) {
969 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
970 $this->mWatched
= false;
972 $this->mWatched
= $wgUser->isWatched( $this );
975 return $this->mWatched
;
979 * Can $wgUser perform $action this page?
980 * @param string $action action that permission needs to be checked for
984 function userCan($action) {
985 $fname = 'Title::userCan';
986 wfProfileIn( $fname );
991 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
992 if ( $result !== null ) {
993 wfProfileOut( $fname );
997 if( NS_SPECIAL
== $this->mNamespace
) {
998 wfProfileOut( $fname );
1001 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1002 // from taking effect -ævar
1003 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1004 !$wgUser->isAllowed('editinterface') ) {
1005 wfProfileOut( $fname );
1009 if( $this->mDbkeyform
== '_' ) {
1010 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1011 wfProfileOut( $fname );
1015 # protect css/js subpages of user pages
1016 # XXX: this might be better using restrictions
1017 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1018 if( NS_USER
== $this->mNamespace
1019 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1020 && !$wgUser->isAllowed('editinterface')
1021 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1022 wfProfileOut( $fname );
1026 foreach( $this->getRestrictions($action) as $right ) {
1027 // Backwards compatibility, rewrite sysop -> protect
1028 if ( $right == 'sysop' ) {
1031 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1032 wfProfileOut( $fname );
1037 if( $action == 'move' &&
1038 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1039 wfProfileOut( $fname );
1043 if( $action == 'create' ) {
1044 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1045 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1050 wfProfileOut( $fname );
1055 * Can $wgUser edit this page?
1059 function userCanEdit() {
1060 return $this->userCan('edit');
1064 * Can $wgUser move this page?
1068 function userCanMove() {
1069 return $this->userCan('move');
1073 * Would anybody with sufficient privileges be able to move this page?
1074 * Some pages just aren't movable.
1079 function isMovable() {
1080 return Namespace::isMovable( $this->getNamespace() )
1081 && $this->getInterwiki() == '';
1085 * Can $wgUser read this page?
1089 function userCanRead() {
1093 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1094 if ( $result !== null ) {
1098 if( $wgUser->isAllowed('read') ) {
1101 global $wgWhitelistRead;
1103 /** If anon users can create an account,
1104 they need to reach the login page first! */
1105 if( $wgUser->isAllowed( 'createaccount' )
1106 && $this->getNamespace() == NS_SPECIAL
1107 && $this->getText() == 'Userlogin' ) {
1111 /** some pages are explicitly allowed */
1112 $name = $this->getPrefixedText();
1113 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1117 # Compatibility with old settings
1118 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1119 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1128 * Is this a talk page of some sort?
1132 function isTalkPage() {
1133 return Namespace::isTalk( $this->getNamespace() );
1137 * Is this a .css or .js subpage of a user page?
1141 function isCssJsSubpage() {
1142 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1145 * Is this a *valid* .css or .js subpage of a user page?
1146 * Check that the corresponding skin exists
1148 function isValidCssJsSubpage() {
1149 global $wgValidSkinNames;
1150 return( $this->isCssJsSubpage() && array_key_exists( $this->getSkinFromCssJsSubpage(), $wgValidSkinNames ) );
1153 * Trim down a .css or .js subpage title to get the corresponding skin name
1155 function getSkinFromCssJsSubpage() {
1156 $subpage = explode( '/', $this->mTextform
);
1157 $subpage = $subpage[ count( $subpage ) - 1 ];
1158 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1161 * Is this a .css subpage of a user page?
1165 function isCssSubpage() {
1166 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1169 * Is this a .js subpage of a user page?
1173 function isJsSubpage() {
1174 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1177 * Protect css/js subpages of user pages: can $wgUser edit
1181 * @todo XXX: this might be better using restrictions
1184 function userCanEditCssJsSubpage() {
1186 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1190 * Loads a string into mRestrictions array
1191 * @param string $res restrictions in string format
1194 function loadRestrictions( $res ) {
1195 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1196 $temp = explode( '=', trim( $restrict ) );
1197 if(count($temp) == 1) {
1198 // old format should be treated as edit/move restriction
1199 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1200 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1202 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1205 $this->mRestrictionsLoaded
= true;
1209 * Accessor/initialisation for mRestrictions
1210 * @param string $action action that permission needs to be checked for
1211 * @return array the array of groups allowed to edit this article
1214 function getRestrictions($action) {
1215 $id = $this->getArticleID();
1216 if ( 0 == $id ) { return array(); }
1218 if ( ! $this->mRestrictionsLoaded
) {
1219 $dbr =& wfGetDB( DB_SLAVE
);
1220 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1221 $this->loadRestrictions( $res );
1223 if( isset( $this->mRestrictions
[$action] ) ) {
1224 return $this->mRestrictions
[$action];
1230 * Is there a version of this page in the deletion archive?
1231 * @return int the number of archived revisions
1234 function isDeleted() {
1235 $fname = 'Title::isDeleted';
1236 if ( $this->getNamespace() < 0 ) {
1239 $dbr =& wfGetDB( DB_SLAVE
);
1240 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1241 'ar_title' => $this->getDBkey() ), $fname );
1247 * Used to grab from the logging facility the date at wich the
1248 * article got deleted. For special pages and article that never
1249 * got deleted, return 0.
1250 * @return date when the title got deleted
1252 function getDeletedDate() {
1253 $fname = 'Title::getLastDelete';
1254 if( $this->getNamespace() < 0 or !$this->isDeleted() ) {
1257 $dbr =& wfGetDB( DB_SLAVE
);
1258 $n = $dbr->selectField( 'logging', 'MAX(log_timestamp)', array( 'log_namespace' => $this->getNamespace(),
1259 'log_title' => $this->getDBkey() ), $fname );
1264 * Get the article ID for this Title from the link cache,
1265 * adding it if necessary
1266 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1268 * @return int the ID
1271 function getArticleID( $flags = 0 ) {
1272 $linkCache =& LinkCache
::singleton();
1273 if ( $flags & GAID_FOR_UPDATE
) {
1274 $oldUpdate = $linkCache->forUpdate( true );
1275 $this->mArticleID
= $linkCache->addLinkObj( $this );
1276 $linkCache->forUpdate( $oldUpdate );
1278 if ( -1 == $this->mArticleID
) {
1279 $this->mArticleID
= $linkCache->addLinkObj( $this );
1282 return $this->mArticleID
;
1285 function getLatestRevID() {
1286 if ($this->mLatestID
!== false)
1287 return $this->mLatestID
;
1289 $db =& wfGetDB(DB_SLAVE
);
1290 return $this->mLatestID
= $db->selectField( 'revision',
1292 array('rev_page' => $this->getArticleID()),
1293 'Title::getLatestRevID' );
1297 * This clears some fields in this object, and clears any associated
1298 * keys in the "bad links" section of the link cache.
1300 * - This is called from Article::insertNewArticle() to allow
1301 * loading of the new page_id. It's also called from
1302 * Article::doDeleteArticle()
1304 * @param int $newid the new Article ID
1307 function resetArticleID( $newid ) {
1308 $linkCache =& LinkCache
::singleton();
1309 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1311 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1312 else { $this->mArticleID
= $newid; }
1313 $this->mRestrictionsLoaded
= false;
1314 $this->mRestrictions
= array();
1318 * Updates page_touched for this page; called from LinksUpdate.php
1319 * @return bool true if the update succeded
1322 function invalidateCache() {
1323 global $wgUseFileCache;
1325 if ( wfReadOnly() ) {
1329 $dbw =& wfGetDB( DB_MASTER
);
1330 $success = $dbw->update( 'page',
1332 'page_touched' => $dbw->timestamp()
1333 ), array( /* WHERE */
1334 'page_namespace' => $this->getNamespace() ,
1335 'page_title' => $this->getDBkey()
1336 ), 'Title::invalidateCache'
1339 if ($wgUseFileCache) {
1340 $cache = new CacheManager($this);
1341 @unlink
($cache->fileCacheName());
1348 * Prefix some arbitrary text with the namespace or interwiki prefix
1351 * @param string $name the text
1352 * @return string the prefixed text
1355 /* private */ function prefix( $name ) {
1359 if ( '' != $this->mInterwiki
) {
1360 $p = $this->mInterwiki
. ':';
1362 if ( 0 != $this->mNamespace
) {
1363 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1369 * Secure and split - main initialisation function for this object
1371 * Assumes that mDbkeyform has been set, and is urldecoded
1372 * and uses underscores, but not otherwise munged. This function
1373 * removes illegal characters, splits off the interwiki and
1374 * namespace prefixes, sets the other forms, and canonicalizes
1376 * @return bool true on success
1379 /* private */ function secureAndSplit() {
1380 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1381 $fname = 'Title::secureAndSplit';
1384 static $rxTc = false;
1386 # % is needed as well
1387 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1390 $this->mInterwiki
= $this->mFragment
= '';
1391 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1393 # Clean up whitespace
1395 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1396 $t = trim( $t, '_' );
1402 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1403 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1407 $this->mDbkeyform
= $t;
1409 # Initial colon indicates main namespace rather than specified default
1410 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1411 if ( ':' == $t{0} ) {
1412 $this->mNamespace
= NS_MAIN
;
1413 $t = substr( $t, 1 ); # remove the colon but continue processing
1416 # Namespace or interwiki prefix
1419 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1421 $lowerNs = strtolower( $p );
1422 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1423 # Canonical namespace
1425 $this->mNamespace
= $ns;
1426 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1427 # Ordinary namespace
1429 $this->mNamespace
= $ns;
1430 } elseif( $this->getInterwikiLink( $p ) ) {
1432 # Can't make a local interwiki link to an interwiki link.
1433 # That's just crazy!
1439 $this->mInterwiki
= strtolower( $p );
1441 # Redundant interwiki prefix to the local wiki
1442 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1444 # Can't have an empty self-link
1447 $this->mInterwiki
= '';
1449 # Do another namespace split...
1453 # If there's an initial colon after the interwiki, that also
1454 # resets the default namespace
1455 if ( $t !== '' && $t[0] == ':' ) {
1456 $this->mNamespace
= NS_MAIN
;
1457 $t = substr( $t, 1 );
1460 # If there's no recognized interwiki or namespace,
1461 # then let the colon expression be part of the title.
1467 # We already know that some pages won't be in the database!
1469 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1470 $this->mArticleID
= 0;
1472 $f = strstr( $r, '#' );
1473 if ( false !== $f ) {
1474 $this->mFragment
= substr( $f, 1 );
1475 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1476 # remove whitespace again: prevents "Foo_bar_#"
1477 # becoming "Foo_bar_"
1478 $r = preg_replace( '/_*$/', '', $r );
1481 # Reject illegal characters.
1483 if( preg_match( $rxTc, $r ) ) {
1488 * Pages with "/./" or "/../" appearing in the URLs will
1489 * often be unreachable due to the way web browsers deal
1490 * with 'relative' URLs. Forbid them explicitly.
1492 if ( strpos( $r, '.' ) !== false &&
1493 ( $r === '.' ||
$r === '..' ||
1494 strpos( $r, './' ) === 0 ||
1495 strpos( $r, '../' ) === 0 ||
1496 strpos( $r, '/./' ) !== false ||
1497 strpos( $r, '/../' ) !== false ) )
1502 # We shouldn't need to query the DB for the size.
1503 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1504 if ( strlen( $r ) > 255 ) {
1509 * Normally, all wiki links are forced to have
1510 * an initial capital letter so [[foo]] and [[Foo]]
1511 * point to the same place.
1513 * Don't force it for interwikis, since the other
1514 * site might be case-sensitive.
1516 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1517 $t = $wgContLang->ucfirst( $r );
1523 * Can't make a link to a namespace alone...
1524 * "empty" local links can only be self-links
1525 * with a fragment identifier.
1528 $this->mInterwiki
== '' &&
1529 $this->mNamespace
!= NS_MAIN
) {
1533 // Any remaining initial :s are illegal.
1534 if ( $t !== '' && ':' == $t{0} ) {
1539 $this->mDbkeyform
= $t;
1540 $this->mUrlform
= wfUrlencode( $t );
1542 $this->mTextform
= str_replace( '_', ' ', $t );
1548 * Get a Title object associated with the talk page of this article
1549 * @return Title the object for the talk page
1552 function getTalkPage() {
1553 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1557 * Get a title object associated with the subject page of this
1560 * @return Title the object for the subject page
1563 function getSubjectPage() {
1564 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1568 * Get an array of Title objects linking to this Title
1569 * Also stores the IDs in the link cache.
1571 * @param string $options may be FOR UPDATE
1572 * @return array the Title objects linking here
1575 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1576 $linkCache =& LinkCache
::singleton();
1577 $id = $this->getArticleID();
1580 $db =& wfGetDB( DB_MASTER
);
1582 $db =& wfGetDB( DB_SLAVE
);
1585 $res = $db->select( array( 'page', $table ),
1586 array( 'page_namespace', 'page_title', 'page_id' ),
1588 "{$prefix}_from=page_id",
1589 "{$prefix}_namespace" => $this->getNamespace(),
1590 "{$prefix}_title" => $this->getDbKey() ),
1591 'Title::getLinksTo',
1595 if ( $db->numRows( $res ) ) {
1596 while ( $row = $db->fetchObject( $res ) ) {
1597 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1598 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1599 $retVal[] = $titleObj;
1603 $db->freeResult( $res );
1608 * Get an array of Title objects using this Title as a template
1609 * Also stores the IDs in the link cache.
1611 * @param string $options may be FOR UPDATE
1612 * @return array the Title objects linking here
1615 function getTemplateLinksTo( $options = '' ) {
1616 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1620 * Get an array of Title objects referring to non-existent articles linked from this page
1622 * @param string $options may be FOR UPDATE
1623 * @return array the Title objects
1626 function getBrokenLinksFrom( $options = '' ) {
1628 $db =& wfGetDB( DB_MASTER
);
1630 $db =& wfGetDB( DB_SLAVE
);
1633 $res = $db->safeQuery(
1634 "SELECT pl_namespace, pl_title
1637 ON pl_namespace=page_namespace
1638 AND pl_title=page_title
1640 AND page_namespace IS NULL
1642 $db->tableName( 'pagelinks' ),
1643 $db->tableName( 'page' ),
1644 $this->getArticleId(),
1648 if ( $db->numRows( $res ) ) {
1649 while ( $row = $db->fetchObject( $res ) ) {
1650 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1653 $db->freeResult( $res );
1659 * Get a list of URLs to purge from the Squid cache when this
1662 * @return array the URLs
1665 function getSquidURLs() {
1667 $this->getInternalURL(),
1668 $this->getInternalURL( 'action=history' )
1673 * Move this page without authentication
1674 * @param Title &$nt the new page Title
1677 function moveNoAuth( &$nt ) {
1678 return $this->moveTo( $nt, false );
1682 * Check whether a given move operation would be valid.
1683 * Returns true if ok, or a message key string for an error message
1684 * if invalid. (Scarrrrry ugly interface this.)
1685 * @param Title &$nt the new title
1686 * @param bool $auth indicates whether $wgUser's permissions
1688 * @return mixed true on success, message name on failure
1691 function isValidMoveOperation( &$nt, $auth = true ) {
1692 if( !$this or !$nt ) {
1693 return 'badtitletext';
1695 if( $this->equals( $nt ) ) {
1698 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1699 return 'immobile_namespace';
1702 $oldid = $this->getArticleID();
1703 $newid = $nt->getArticleID();
1705 if ( strlen( $nt->getDBkey() ) < 1 ) {
1706 return 'articleexists';
1708 if ( ( '' == $this->getDBkey() ) ||
1710 ( '' == $nt->getDBkey() ) ) {
1711 return 'badarticleerror';
1715 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1716 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1717 return 'protectedpage';
1720 # The move is allowed only if (1) the target doesn't exist, or
1721 # (2) the target is a redirect to the source, and has no history
1722 # (so we can undo bad moves right after they're done).
1724 if ( 0 != $newid ) { # Target exists; check for validity
1725 if ( ! $this->isValidMoveTarget( $nt ) ) {
1726 return 'articleexists';
1733 * Move a title to a new location
1734 * @param Title &$nt the new title
1735 * @param bool $auth indicates whether $wgUser's permissions
1737 * @return mixed true on success, message name on failure
1740 function moveTo( &$nt, $auth = true, $reason = '' ) {
1741 $err = $this->isValidMoveOperation( $nt, $auth );
1742 if( is_string( $err ) ) {
1746 $pageid = $this->getArticleID();
1747 if( $nt->exists() ) {
1748 $this->moveOverExistingRedirect( $nt, $reason );
1749 $pageCountChange = 0;
1750 } else { # Target didn't exist, do normal move.
1751 $this->moveToNewTitle( $nt, $reason );
1752 $pageCountChange = 1;
1754 $redirid = $this->getArticleID();
1756 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1757 $dbw =& wfGetDB( DB_MASTER
);
1758 $categorylinks = $dbw->tableName( 'categorylinks' );
1759 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1760 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1761 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1762 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1766 $oldnamespace = $this->getNamespace() & ~
1;
1767 $newnamespace = $nt->getNamespace() & ~
1;
1768 $oldtitle = $this->getDBkey();
1769 $newtitle = $nt->getDBkey();
1771 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1772 WatchedItem
::duplicateEntries( $this, $nt );
1775 # Update search engine
1776 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1778 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1782 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1783 # Moved out of main namespace
1784 # not viewed, edited, removing
1785 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1786 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1787 # Moved into main namespace
1788 # not viewed, edited, adding
1789 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1790 } elseif ( $pageCountChange ) {
1792 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1801 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1806 * Move page to a title which is at present a redirect to the
1809 * @param Title &$nt the page to move to, which should currently
1813 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1814 global $wgUseSquid, $wgMwRedir;
1815 $fname = 'Title::moveOverExistingRedirect';
1816 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1819 $comment .= ": $reason";
1822 $now = wfTimestampNow();
1824 $newid = $nt->getArticleID();
1825 $oldid = $this->getArticleID();
1826 $dbw =& wfGetDB( DB_MASTER
);
1827 $linkCache =& LinkCache
::singleton();
1829 # Delete the old redirect. We don't save it to history since
1830 # by definition if we've got here it's rather uninteresting.
1831 # We have to remove it so that the next step doesn't trigger
1832 # a conflict on the unique namespace+title index...
1833 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1835 # Save a null revision in the page's history notifying of the move
1836 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1837 $nullRevId = $nullRevision->insertOn( $dbw );
1839 # Change the name of the target page:
1840 $dbw->update( 'page',
1842 'page_touched' => $dbw->timestamp($now),
1843 'page_namespace' => $nt->getNamespace(),
1844 'page_title' => $nt->getDBkey(),
1845 'page_latest' => $nullRevId,
1847 /* WHERE */ array( 'page_id' => $oldid ),
1850 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1852 # Recreate the redirect, this time in the other direction.
1853 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1854 $redirectArticle = new Article( $this );
1855 $newid = $redirectArticle->insertOn( $dbw );
1856 $redirectRevision = new Revision( array(
1858 'comment' => $comment,
1859 'text' => $redirectText ) );
1860 $revid = $redirectRevision->insertOn( $dbw );
1861 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1862 $linkCache->clearLink( $this->getPrefixedDBkey() );
1865 $log = new LogPage( 'move' );
1866 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1868 # Now, we record the link from the redirect to the new title.
1869 # It should have no other outgoing links...
1870 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1871 $dbw->insert( 'pagelinks',
1873 'pl_from' => $newid,
1874 'pl_namespace' => $nt->getNamespace(),
1875 'pl_title' => $nt->getDbKey() ),
1879 if ( $wgUseSquid ) {
1880 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1881 $u = new SquidUpdate( $urls );
1887 * Move page to non-existing title.
1888 * @param Title &$nt the new Title
1891 function moveToNewTitle( &$nt, $reason = '' ) {
1894 $fname = 'MovePageForm::moveToNewTitle';
1895 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1897 $comment .= ": $reason";
1900 $newid = $nt->getArticleID();
1901 $oldid = $this->getArticleID();
1902 $dbw =& wfGetDB( DB_MASTER
);
1903 $now = $dbw->timestamp();
1905 $linkCache =& LinkCache
::singleton();
1907 # Save a null revision in the page's history notifying of the move
1908 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1909 $nullRevId = $nullRevision->insertOn( $dbw );
1912 $dbw->update( 'page',
1914 'page_touched' => $now,
1915 'page_namespace' => $nt->getNamespace(),
1916 'page_title' => $nt->getDBkey(),
1917 'page_latest' => $nullRevId,
1919 /* WHERE */ array( 'page_id' => $oldid ),
1923 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1926 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1927 $redirectArticle = new Article( $this );
1928 $newid = $redirectArticle->insertOn( $dbw );
1929 $redirectRevision = new Revision( array(
1931 'comment' => $comment,
1932 'text' => $redirectText ) );
1933 $revid = $redirectRevision->insertOn( $dbw );
1934 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1935 $linkCache->clearLink( $this->getPrefixedDBkey() );
1938 $log = new LogPage( 'move' );
1939 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1941 # Purge caches as per article creation
1942 Article
::onArticleCreate( $nt );
1944 # Record the just-created redirect's linking to the page
1945 $dbw->insert( 'pagelinks',
1947 'pl_from' => $newid,
1948 'pl_namespace' => $nt->getNamespace(),
1949 'pl_title' => $nt->getDBkey() ),
1952 # Non-existent target may have had broken links to it; these must
1953 # now be touched to update link coloring.
1956 # Purge old title from squid
1957 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1958 $titles = $nt->getLinksTo();
1959 if ( $wgUseSquid ) {
1960 $urls = $this->getSquidURLs();
1961 foreach ( $titles as $linkTitle ) {
1962 $urls[] = $linkTitle->getInternalURL();
1964 $u = new SquidUpdate( $urls );
1970 * Checks if $this can be moved to a given Title
1971 * - Selects for update, so don't call it unless you mean business
1973 * @param Title &$nt the new title to check
1976 function isValidMoveTarget( $nt ) {
1978 $fname = 'Title::isValidMoveTarget';
1979 $dbw =& wfGetDB( DB_MASTER
);
1982 $id = $nt->getArticleID();
1983 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1984 array( 'page_is_redirect','old_text','old_flags' ),
1985 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1986 $fname, 'FOR UPDATE' );
1988 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1992 $text = Revision
::getRevisionText( $obj );
1994 # Does the redirect point to the source?
1995 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1996 $redirTitle = Title
::newFromText( $m[1] );
1997 if( !is_object( $redirTitle ) ||
1998 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
2006 # Does the article have a history?
2007 $row = $dbw->selectRow( array( 'page', 'revision'),
2009 array( 'page_namespace' => $nt->getNamespace(),
2010 'page_title' => $nt->getDBkey(),
2011 'page_id=rev_page AND page_latest != rev_id'
2012 ), $fname, 'FOR UPDATE'
2015 # Return true if there was no history
2016 return $row === false;
2020 * Create a redirect; fails if the title already exists; does
2023 * @param Title $dest the destination of the redirect
2024 * @param string $comment the comment string describing the move
2025 * @return bool true on success
2028 function createRedirect( $dest, $comment ) {
2029 if ( $this->getArticleID() ) {
2033 $fname = 'Title::createRedirect';
2034 $dbw =& wfGetDB( DB_MASTER
);
2036 $article = new Article( $this );
2037 $newid = $article->insertOn( $dbw );
2038 $revision = new Revision( array(
2040 'comment' => $comment,
2041 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2043 $revisionId = $revision->insertOn( $dbw );
2044 $article->updateRevisionOn( $dbw, $revision, 0 );
2047 $dbw->insert( 'pagelinks',
2049 'pl_from' => $newid,
2050 'pl_namespace' => $dest->getNamespace(),
2051 'pl_title' => $dest->getDbKey()
2055 Article
::onArticleCreate( $this );
2060 * Get categories to which this Title belongs and return an array of
2061 * categories' names.
2063 * @return array an array of parents in the form:
2064 * $parent => $currentarticle
2067 function getParentCategories() {
2070 $titlekey = $this->getArticleId();
2071 $dbr =& wfGetDB( DB_SLAVE
);
2072 $categorylinks = $dbr->tableName( 'categorylinks' );
2075 $sql = "SELECT * FROM $categorylinks"
2076 ." WHERE cl_from='$titlekey'"
2077 ." AND cl_from <> '0'"
2078 ." ORDER BY cl_sortkey";
2080 $res = $dbr->query ( $sql ) ;
2082 if($dbr->numRows($res) > 0) {
2083 while ( $x = $dbr->fetchObject ( $res ) )
2084 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2085 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2086 $dbr->freeResult ( $res ) ;
2094 * Get a tree of parent categories
2095 * @param array $children an array with the children in the keys, to check for circular refs
2099 function getParentCategoryTree( $children = array() ) {
2100 $parents = $this->getParentCategories();
2102 if($parents != '') {
2103 foreach($parents as $parent => $current) {
2104 if ( array_key_exists( $parent, $children ) ) {
2105 # Circular reference
2106 $stack[$parent] = array();
2108 $nt = Title
::newFromText($parent);
2109 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2120 * Get an associative array for selecting this title from
2126 function pageCond() {
2127 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2131 * Get the revision ID of the previous revision
2133 * @param integer $revision Revision ID. Get the revision that was before this one.
2134 * @return interger $oldrevision|false
2136 function getPreviousRevisionID( $revision ) {
2137 $dbr =& wfGetDB( DB_SLAVE
);
2138 return $dbr->selectField( 'revision', 'rev_id',
2139 'rev_page=' . intval( $this->getArticleId() ) .
2140 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2144 * Get the revision ID of the next revision
2146 * @param integer $revision Revision ID. Get the revision that was after this one.
2147 * @return interger $oldrevision|false
2149 function getNextRevisionID( $revision ) {
2150 $dbr =& wfGetDB( DB_SLAVE
);
2151 return $dbr->selectField( 'revision', 'rev_id',
2152 'rev_page=' . intval( $this->getArticleId() ) .
2153 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2157 * Compare with another title.
2159 * @param Title $title
2162 function equals( $title ) {
2163 // Note: === is necessary for proper matching of number-like titles.
2164 return $this->getInterwiki() === $title->getInterwiki()
2165 && $this->getNamespace() == $title->getNamespace()
2166 && $this->getDbkey() === $title->getDbkey();
2170 * Check if page exists
2174 return $this->getArticleId() != 0;
2178 * Should a link should be displayed as a known link, just based on its title?
2180 * Currently, a self-link with a fragment and special pages are in
2181 * this category. Special pages never exist in the database.
2183 function isAlwaysKnown() {
2184 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2185 || NS_SPECIAL
== $this->mNamespace
;
2189 * Update page_touched timestamps on pages linking to this title.
2190 * In principal, this could be backgrounded and could also do squid
2193 function touchLinks() {
2194 $fname = 'Title::touchLinks';
2196 $dbw =& wfGetDB( DB_MASTER
);
2198 $res = $dbw->select( 'pagelinks',
2201 'pl_namespace' => $this->getNamespace(),
2202 'pl_title' => $this->getDbKey() ),
2205 $toucharr = array();
2206 while( $row = $dbw->fetchObject( $res ) ) {
2207 $toucharr[] = $row->pl_from
;
2209 $dbw->freeResult( $res );
2211 if( $this->getNamespace() == NS_CATEGORY
) {
2212 // Categories show up in a separate set of links as well
2213 $res = $dbw->select( 'categorylinks',
2215 array( 'cl_to' => $this->getDbKey() ),
2217 while( $row = $dbw->fetchObject( $res ) ) {
2218 $toucharr[] = $row->cl_from
;
2220 $dbw->freeResult( $res );
2223 if (!count($toucharr))
2225 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2226 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2229 function trackbackURL() {
2230 global $wgTitle, $wgScriptPath, $wgServer;
2232 return "$wgServer$wgScriptPath/trackback.php?article="
2233 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2236 function trackbackRDF() {
2237 $url = htmlspecialchars($this->getFullURL());
2238 $title = htmlspecialchars($this->getText());
2239 $tburl = $this->trackbackURL();
2242 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2243 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2244 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2247 dc:identifier=\"$url\"
2249 trackback:ping=\"$tburl\" />
2254 * Generate strings used for xml 'id' names in monobook tabs
2257 function getNamespaceKey() {
2258 switch ($this->getNamespace()) {
2261 return 'nstab-main';
2264 return 'nstab-user';
2266 return 'nstab-media';
2268 return 'nstab-special';
2270 case NS_PROJECT_TALK
:
2274 return 'nstab-image';
2276 case NS_MEDIAWIKI_TALK
:
2277 return 'nstab-mediawiki';
2279 case NS_TEMPLATE_TALK
:
2280 return 'nstab-template';
2283 return 'nstab-help';
2285 case NS_CATEGORY_TALK
:
2286 return 'nstab-category';
2288 return 'nstab-' . strtolower( $this->getSubjectNsText() );