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 );
20 # Constants for pr_cascade bitfield
21 define( 'CASCADE', 1 );
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 * Static cache variables
34 static private $titleCache=array();
35 static private $interwikiCache=array();
39 * All member variables should be considered private
40 * Please use the accessor functions
47 var $mTextform; # Text form (spaces not underscores) of the main part
48 var $mUrlform; # URL-encoded form of the main part
49 var $mDbkeyform; # Main part with underscores
50 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
51 var $mInterwiki; # Interwiki prefix (or null string)
52 var $mFragment; # Title fragment (i.e. the bit after the #)
53 var $mArticleID; # Article ID, fetched from the link cache on demand
54 var $mLatestID; # ID of most recent revision
55 var $mRestrictions; # Array of groups allowed to edit this article
56 var $mCascadeRestriction;
57 var $mRestrictionsLoaded; # Boolean for initialisation on demand
58 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
59 var $mDefaultNamespace; # Namespace index when there is no namespace
60 # Zero except in {{transclusion}} tags
61 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
69 /* private */ function Title() {
70 $this->mInterwiki
= $this->mUrlform
=
71 $this->mTextform
= $this->mDbkeyform
= '';
72 $this->mArticleID
= -1;
73 $this->mNamespace
= NS_MAIN
;
74 $this->mRestrictionsLoaded
= false;
75 $this->mRestrictions
= array();
76 # Dont change the following, NS_MAIN is hardcoded in several place
78 $this->mDefaultNamespace
= NS_MAIN
;
79 $this->mWatched
= NULL;
80 $this->mLatestID
= false;
84 * Create a new Title from a prefixed DB key
85 * @param string $key The database key, which has underscores
86 * instead of spaces, possibly including namespace and
88 * @return Title the new object, or NULL on an error
92 /* static */ function newFromDBkey( $key ) {
94 $t->mDbkeyform
= $key;
95 if( $t->secureAndSplit() )
102 * Create a new Title from text, such as what one would
103 * find in a link. Decodes any HTML entities in the text.
105 * @param string $text the link text; spaces, prefixes,
106 * and an initial ':' indicating the main namespace
108 * @param int $defaultNamespace the namespace to use if
109 * none is specified by a prefix
110 * @return Title the new object, or NULL on an error
114 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
115 if( is_object( $text ) ) {
116 throw new MWException( 'Title::newFromText given an object' );
120 * Wiki pages often contain multiple links to the same page.
121 * Title normalization and parsing can become expensive on
122 * pages with many links, so we can save a little time by
125 * In theory these are value objects and won't get changed...
127 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
128 return Title
::$titleCache[$text];
132 * Convert things like é ā or 〗 into real text...
134 $filteredText = Sanitizer
::decodeCharReferences( $text );
137 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
138 $t->mDefaultNamespace
= $defaultNamespace;
140 static $cachedcount = 0 ;
141 if( $t->secureAndSplit() ) {
142 if( $defaultNamespace == NS_MAIN
) {
143 if( $cachedcount >= MW_TITLECACHE_MAX
) {
144 # Avoid memory leaks on mass operations...
145 Title
::$titleCache = array();
149 Title
::$titleCache[$text] =& $t;
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
166 public static function newFromURL( $url ) {
167 global $wgLegalTitleChars;
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
177 $t->mDbkeyform
= str_replace( ' ', '_', $url );
178 if( $t->secureAndSplit() ) {
186 * Create a new Title from an article ID
188 * @todo This is inefficiently implemented, the page row is requested
189 * but not used for anything else
191 * @param int $id the page_id corresponding to the Title to create
192 * @return Title the new object, or NULL on an error
196 public static function newFromID( $id ) {
197 $fname = 'Title::newFromID';
198 $dbr =& wfGetDB( DB_SLAVE
);
199 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
200 array( 'page_id' => $id ), $fname );
201 if ( $row !== false ) {
202 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
210 * Make an array of titles from an array of IDs
212 function newFromIDs( $ids ) {
213 $dbr =& wfGetDB( DB_SLAVE
);
214 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
215 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
218 while ( $row = $dbr->fetchObject( $res ) ) {
219 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
225 * Create a new Title from a namespace index and a DB key.
226 * It's assumed that $ns and $title are *valid*, for instance when
227 * they came directly from the database or a special page name.
228 * For convenience, spaces are converted to underscores so that
229 * eg user_text fields can be used directly.
231 * @param int $ns the namespace of the article
232 * @param string $title the unprefixed database key form
233 * @return Title the new object
237 public static function &makeTitle( $ns, $title ) {
241 $t->mNamespace
= intval( $ns );
242 $t->mDbkeyform
= str_replace( ' ', '_', $title );
243 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
244 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
245 $t->mTextform
= str_replace( '_', ' ', $title );
250 * Create a new Title from a namespace index and a DB key.
251 * The parameters will be checked for validity, which is a bit slower
252 * than makeTitle() but safer for user-provided data.
254 * @param int $ns the namespace of the article
255 * @param string $title the database key form
256 * @return Title the new object, or NULL on an error
260 public static function makeTitleSafe( $ns, $title ) {
262 $t->mDbkeyform
= Title
::makeName( $ns, $title );
263 if( $t->secureAndSplit() ) {
271 * Create a new Title for the Main Page
274 * @return Title the new object
277 public static function newMainPage() {
278 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
282 * Create a new Title for a redirect
283 * @param string $text the redirect title text
284 * @return Title the new object, or NULL if the text is not a
287 public static function newFromRedirect( $text ) {
288 $mwRedir = MagicWord
::get( 'redirect' );
290 if ( $mwRedir->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->isSpecial( 'Userlogout' ) ) {
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 public static 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 public static function indexTitle( $ns, $title ) {
356 $lc = SearchEngine
::legalSearchChars() . '&#;';
357 $t = $wgContLang->stripForSearch( $title );
358 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
359 $t = $wgContLang->lc( $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 public 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, $wgInterwikiExpiry;
396 global $wgInterwikiCache, $wgContLang;
397 $fname = 'Title::getInterwikiLink';
399 $key = $wgContLang->lc( $key );
401 $k = wfMemcKey( '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 $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:' . wfWikiID(), $db);
457 $site = $wgInterwikiFallbackSite;
459 $value = dba_fetch( wfMemcKey( $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[wfMemcKey( '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
491 if ( $this->mInterwiki
!= '' ) {
492 # Make sure key is loaded into cache
493 $this->getInterwikiLink( $this->mInterwiki
);
494 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
495 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
502 * Determine whether the object refers to a page within
503 * this project and is transcludable.
505 * @return bool TRUE if this is transcludable
509 if ($this->mInterwiki
== '')
511 # Make sure key is loaded into cache
512 $this->getInterwikiLink( $this->mInterwiki
);
513 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
514 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
518 * Update the page_touched field for an array of title objects
519 * @todo Inefficient unless the IDs are already loaded into the
521 * @param array $titles an array of Title objects to be touched
522 * @param string $timestamp the timestamp to use instead of the
523 * default current time
527 function touchArray( $titles, $timestamp = '' ) {
529 if ( count( $titles ) == 0 ) {
532 $dbw =& wfGetDB( DB_MASTER
);
533 if ( $timestamp == '' ) {
534 $timestamp = $dbw->timestamp();
537 $page = $dbw->tableName( 'page' );
538 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
541 foreach ( $titles as $title ) {
542 if ( $wgUseFileCache ) {
543 $cm = new HTMLFileCache($title);
544 @unlink($cm->fileCacheName());
551 $sql .= $title->getArticleID();
555 $dbw->query( $sql, 'Title::touchArray' );
558 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
559 // do them in small chunks:
560 $fname = 'Title::touchArray';
561 foreach( $titles as $title ) {
562 $dbw->update( 'page',
563 array( 'page_touched' => $timestamp ),
565 'page_namespace' => $title->getNamespace(),
566 'page_title' => $title->getDBkey() ),
572 * Escape a text fragment, say from a link, for a URL
574 static function escapeFragmentForURL( $fragment ) {
575 $fragment = str_replace( ' ', '_', $fragment );
576 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
577 $replaceArray = array(
581 return strtr( $fragment, $replaceArray );
584 #----------------------------------------------------------------------------
586 #----------------------------------------------------------------------------
588 /** Simple accessors */
590 * Get the text form (spaces not underscores) of the main part
594 function getText() { return $this->mTextform
; }
596 * Get the URL-encoded form of the main part
600 function getPartialURL() { return $this->mUrlform
; }
602 * Get the main part with underscores
606 function getDBkey() { return $this->mDbkeyform
; }
608 * Get the namespace index, i.e. one of the NS_xxxx constants
612 function getNamespace() { return $this->mNamespace
; }
614 * Get the namespace text
618 function getNsText() {
619 global $wgContLang, $wgCanonicalNamespaceNames;
621 if ( '' != $this->mInterwiki
) {
622 // This probably shouldn't even happen. ohh man, oh yuck.
623 // But for interwiki transclusion it sometimes does.
624 // Shit. Shit shit shit.
626 // Use the canonical namespaces if possible to try to
627 // resolve a foreign namespace.
628 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
629 return $wgCanonicalNamespaceNames[$this->mNamespace
];
632 return $wgContLang->getNsText( $this->mNamespace
);
635 * Get the namespace text of the subject (rather than talk) page
639 function getSubjectNsText() {
641 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
645 * Get the namespace text of the talk page
648 function getTalkNsText() {
650 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
654 * Could this title have a corresponding talk page?
658 return( Namespace::canTalk( $this->mNamespace
) );
662 * Get the interwiki prefix (or null string)
666 function getInterwiki() { return $this->mInterwiki
; }
668 * Get the Title fragment (i.e. the bit after the #) in text form
672 function getFragment() { return $this->mFragment
; }
674 * Get the fragment in URL form, including the "#" character if there is one
679 function getFragmentForURL() {
680 if ( $this->mFragment
== '' ) {
683 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
687 * Get the default namespace index, for when there is no namespace
691 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
694 * Get title for search index
695 * @return string a stripped-down title string ready for the
698 function getIndexTitle() {
699 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
703 * Get the prefixed database key form
704 * @return string the prefixed title, with underscores and
705 * any interwiki and namespace prefixes
708 function getPrefixedDBkey() {
709 $s = $this->prefix( $this->mDbkeyform
);
710 $s = str_replace( ' ', '_', $s );
715 * Get the prefixed title with spaces.
716 * This is the form usually used for display
717 * @return string the prefixed title, with spaces
720 function getPrefixedText() {
721 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
722 $s = $this->prefix( $this->mTextform
);
723 $s = str_replace( '_', ' ', $s );
724 $this->mPrefixedText
= $s;
726 return $this->mPrefixedText
;
730 * Get the prefixed title with spaces, plus any fragment
731 * (part beginning with '#')
732 * @return string the prefixed title, with spaces and
733 * the fragment, including '#'
736 function getFullText() {
737 $text = $this->getPrefixedText();
738 if( '' != $this->mFragment
) {
739 $text .= '#' . $this->mFragment
;
745 * Get the base name, i.e. the leftmost parts before the /
746 * @return string Base name
748 function getBaseText() {
749 global $wgNamespacesWithSubpages;
750 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
751 $parts = explode( '/', $this->getText() );
752 # Don't discard the real title if there's no subpage involved
753 if( count( $parts ) > 1 )
754 unset( $parts[ count( $parts ) - 1 ] );
755 return implode( '/', $parts );
757 return $this->getText();
762 * Get the lowest-level subpage name, i.e. the rightmost part after /
763 * @return string Subpage name
765 function getSubpageText() {
766 global $wgNamespacesWithSubpages;
767 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
768 $parts = explode( '/', $this->mTextform
);
769 return( $parts[ count( $parts ) - 1 ] );
771 return( $this->mTextform
);
776 * Get a URL-encoded form of the subpage text
777 * @return string URL-encoded subpage name
779 function getSubpageUrlForm() {
780 $text = $this->getSubpageText();
781 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
782 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
787 * Get a URL-encoded title (not an actual URL) including interwiki
788 * @return string the URL-encoded form
791 function getPrefixedURL() {
792 $s = $this->prefix( $this->mDbkeyform
);
793 $s = str_replace( ' ', '_', $s );
795 $s = wfUrlencode ( $s ) ;
797 # Cleaning up URL to make it look nice -- is this safe?
798 $s = str_replace( '%28', '(', $s );
799 $s = str_replace( '%29', ')', $s );
805 * Get a real URL referring to this title, with interwiki link and
808 * @param string $query an optional query string, not used
809 * for interwiki links
810 * @param string $variant language variant of url (for sr, zh..)
811 * @return string the URL
814 function getFullURL( $query = '', $variant = false ) {
815 global $wgContLang, $wgServer, $wgRequest;
817 if ( '' == $this->mInterwiki
) {
818 $url = $this->getLocalUrl( $query, $variant );
820 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
821 // Correct fix would be to move the prepending elsewhere.
822 if ($wgRequest->getVal('action') != 'render') {
823 $url = $wgServer . $url;
826 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
828 $namespace = wfUrlencode( $this->getNsText() );
829 if ( '' != $namespace ) {
830 # Can this actually happen? Interwikis shouldn't be parsed.
831 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
834 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
836 if( false === strpos( $url, '?' ) ) {
845 # Finally, add the fragment.
846 $url .= $this->getFragmentForURL();
848 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
853 * Get a URL with no fragment or server name. If this page is generated
854 * with action=render, $wgServer is prepended.
855 * @param string $query an optional query string; if not specified,
856 * $wgArticlePath will be used.
857 * @param string $variant language variant of url (for sr, zh..)
858 * @return string the URL
861 function getLocalURL( $query = '', $variant = false ) {
862 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
863 global $wgVariantArticlePath, $wgContLang, $wgUser;
865 // internal links should point to same variant as current page (only anonymous users)
866 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
867 $pref = $wgContLang->getPreferredVariant(false);
868 if($pref != $wgContLang->getCode())
872 if ( $this->isExternal() ) {
873 $url = $this->getFullURL();
875 // This is currently only used for edit section links in the
876 // context of interwiki transclusion. In theory we should
877 // append the query to the end of any existing query string,
878 // but interwiki transclusion is already broken in that case.
882 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
883 if ( $query == '' ) {
884 if($variant!=false && $wgContLang->hasVariants()){
885 if($wgVariantArticlePath==false)
886 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
888 $variantArticlePath = $wgVariantArticlePath;
890 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
891 $url = str_replace( '$1', $dbkey, $url );
895 $url = str_replace( '$1', $dbkey, $wgArticlePath );
897 global $wgActionPaths;
900 if( !empty( $wgActionPaths ) &&
901 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
903 $action = urldecode( $matches[2] );
904 if( isset( $wgActionPaths[$action] ) ) {
905 $query = $matches[1];
906 if( isset( $matches[4] ) ) $query .= $matches[4];
907 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
908 if( $query != '' ) $url .= '?' . $query;
911 if ( $url === false ) {
912 if ( $query == '-' ) {
915 $url = "{$wgScript}?title={$dbkey}&{$query}";
919 // FIXME: this causes breakage in various places when we
920 // actually expected a local URL and end up with dupe prefixes.
921 if ($wgRequest->getVal('action') == 'render') {
922 $url = $wgServer . $url;
925 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
930 * Get an HTML-escaped version of the URL form, suitable for
931 * using in a link, without a server name or fragment
932 * @param string $query an optional query string
933 * @return string the URL
936 function escapeLocalURL( $query = '' ) {
937 return htmlspecialchars( $this->getLocalURL( $query ) );
941 * Get an HTML-escaped version of the URL form, suitable for
942 * using in a link, including the server name and fragment
944 * @return string the URL
945 * @param string $query an optional query string
948 function escapeFullURL( $query = '' ) {
949 return htmlspecialchars( $this->getFullURL( $query ) );
953 * Get the URL form for an internal link.
954 * - Used in various Squid-related code, in case we have a different
955 * internal hostname for the server from the exposed one.
957 * @param string $query an optional query string
958 * @param string $variant language variant of url (for sr, zh..)
959 * @return string the URL
962 function getInternalURL( $query = '', $variant = false ) {
963 global $wgInternalServer;
964 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
965 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
970 * Get the edit URL for this Title
971 * @return string the URL, or a null string if this is an
975 function getEditURL() {
976 if ( '' != $this->mInterwiki
) { return ''; }
977 $s = $this->getLocalURL( 'action=edit' );
983 * Get the HTML-escaped displayable text form.
984 * Used for the title field in <a> tags.
985 * @return string the text, including any prefixes
988 function getEscapedText() {
989 return htmlspecialchars( $this->getPrefixedText() );
993 * Is this Title interwiki?
997 function isExternal() { return ( '' != $this->mInterwiki
); }
1000 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1002 * @param string Action to check (default: edit)
1005 function isSemiProtected( $action = 'edit' ) {
1006 if( $this->exists() ) {
1007 $restrictions = $this->getRestrictions( $action );
1008 if( count( $restrictions ) > 0 ) {
1009 foreach( $restrictions as $restriction ) {
1010 if( strtolower( $restriction ) != 'autoconfirmed' )
1019 # If it doesn't exist, it can't be protected
1025 * Does the title correspond to a protected article?
1026 * @param string $what the action the page is protected from,
1027 * by default checks move and edit
1031 function isProtected( $action = '' ) {
1032 global $wgRestrictionLevels;
1033 if ( NS_SPECIAL
== $this->mNamespace
) { return true; }
1035 if( $action == 'edit' ||
$action == '' ) {
1036 $r = $this->getRestrictions( 'edit' );
1037 foreach( $wgRestrictionLevels as $level ) {
1038 if( in_array( $level, $r ) && $level != '' ) {
1044 if( $action == 'move' ||
$action == '' ) {
1045 $r = $this->getRestrictions( 'move' );
1046 foreach( $wgRestrictionLevels as $level ) {
1047 if( in_array( $level, $r ) && $level != '' ) {
1057 * Is $wgUser is watching this page?
1061 function userIsWatching() {
1064 if ( is_null( $this->mWatched
) ) {
1065 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1066 $this->mWatched
= false;
1068 $this->mWatched
= $wgUser->isWatched( $this );
1071 return $this->mWatched
;
1075 * Can $wgUser perform $action this page?
1076 * @param string $action action that permission needs to be checked for
1080 function userCan($action) {
1081 $fname = 'Title::userCan';
1082 wfProfileIn( $fname );
1084 global $wgUser, $wgNamespaceProtection;
1087 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1088 if ( $result !== null ) {
1089 wfProfileOut( $fname );
1093 if( NS_SPECIAL
== $this->mNamespace
) {
1094 wfProfileOut( $fname );
1097 if ( array_key_exists( $this->mNamespace
, $wgNamespaceProtection ) ) {
1098 $nsProt = $wgNamespaceProtection[ $this->mNamespace
];
1099 if ( !is_array($nsProt) ) $nsProt = array($nsProt);
1100 foreach( $nsProt as $right ) {
1101 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1102 wfProfileOut( $fname );
1108 if( $this->mDbkeyform
== '_' ) {
1109 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1110 wfProfileOut( $fname );
1114 # protect css/js subpages of user pages
1115 # XXX: this might be better using restrictions
1116 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1117 if( $this->isCssJsSubpage()
1118 && !$wgUser->isAllowed('editinterface')
1119 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1120 wfProfileOut( $fname );
1124 if ( ( $this->isCascadeProtectedPage() ) ||
1125 ($this->getNamespace() == NS_IMAGE
&& $this->isCascadeProtectedImage() ) ) {
1126 # We /could/ use the protection level on the source page, but it's fairly ugly
1127 # as we have to establish a precedence hierarchy for pages included by multiple
1128 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1129 # as they could remove the protection anyway.
1130 if ( !$wgUser->isAllowed('protect') ) {
1131 wfProfileOut( $fname );
1136 foreach( $this->getRestrictions($action) as $right ) {
1137 // Backwards compatibility, rewrite sysop -> protect
1138 if ( $right == 'sysop' ) {
1141 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1142 wfProfileOut( $fname );
1147 if( $action == 'move' &&
1148 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1149 wfProfileOut( $fname );
1153 if( $action == 'create' ) {
1154 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1155 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1156 wfProfileOut( $fname );
1161 wfProfileOut( $fname );
1166 * Can $wgUser edit this page?
1170 function userCanEdit() {
1171 return $this->userCan('edit');
1175 * Can $wgUser create this page?
1179 function userCanCreate() {
1180 return $this->userCan('create');
1184 * Can $wgUser move this page?
1188 function userCanMove() {
1189 return $this->userCan('move');
1193 * Would anybody with sufficient privileges be able to move this page?
1194 * Some pages just aren't movable.
1199 function isMovable() {
1200 return Namespace::isMovable( $this->getNamespace() )
1201 && $this->getInterwiki() == '';
1205 * Can $wgUser read this page?
1209 function userCanRead() {
1213 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1214 if ( $result !== null ) {
1218 if( $wgUser->isAllowed('read') ) {
1221 global $wgWhitelistRead;
1224 * Always grant access to the login page.
1225 * Even anons need to be able to log in.
1227 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1231 /** some pages are explicitly allowed */
1232 $name = $this->getPrefixedText();
1233 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1237 # Compatibility with old settings
1238 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1239 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1248 * Is this a talk page of some sort?
1252 function isTalkPage() {
1253 return Namespace::isTalk( $this->getNamespace() );
1257 * Is this a subpage?
1261 function isSubpage() {
1262 global $wgNamespacesWithSubpages;
1264 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1265 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1272 * Is this a .css or .js subpage of a user page?
1276 function isCssJsSubpage() {
1277 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform
) );
1280 * Is this a *valid* .css or .js subpage of a user page?
1281 * Check that the corresponding skin exists
1283 function isValidCssJsSubpage() {
1284 if ( $this->isCssJsSubpage() ) {
1285 $skinNames = Skin
::getSkinNames();
1286 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1292 * Trim down a .css or .js subpage title to get the corresponding skin name
1294 function getSkinFromCssJsSubpage() {
1295 $subpage = explode( '/', $this->mTextform
);
1296 $subpage = $subpage[ count( $subpage ) - 1 ];
1297 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1300 * Is this a .css subpage of a user page?
1304 function isCssSubpage() {
1305 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1308 * Is this a .js subpage of a user page?
1312 function isJsSubpage() {
1313 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1316 * Protect css/js subpages of user pages: can $wgUser edit
1320 * @todo XXX: this might be better using restrictions
1323 function userCanEditCssJsSubpage() {
1325 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1329 * Cascading protects: Check if the current image is protected due to a cascading restriction
1331 * @return bool If the current page is protected due to a cascading restriction.
1334 function isCascadeProtectedImage() {
1335 global $wgEnableCascadingProtection;
1336 if (!$wgEnableCascadingProtection)
1339 wfProfileIn(__METHOD__
);
1341 $dbr =& wfGetDb( DB_SLAVE
);
1343 $cols = array( 'il_to' );
1344 $tables = array ('imagelinks', 'page_restrictions');
1345 $where_clauses = array( 'il_to' => $this->getDBkey(), 'il_from=pr_page', 'pr_cascade' => 1 );
1347 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1349 if ($dbr->numRows($res)) {
1350 wfProfileOut(__METHOD__
);
1353 wfProfileOut(__METHOD__
);
1359 * Cascading protects: Check if the current page is protected due to a cascading restriction.
1361 * @return bool if the current page is protected due to a cascading restriction
1364 function isCascadeProtectedPage() {
1365 global $wgEnableCascadingProtection;
1366 if (!$wgEnableCascadingProtection)
1369 wfProfileIn(__METHOD__
);
1371 $dbr =& wfGetDb( DB_SLAVE
);
1373 $cols = array( 'tl_namespace', 'tl_title'/*, 'pr_level', 'pr_type'*/ );
1374 $tables = array ('templatelinks', 'page_restrictions');
1375 $where_clauses = array( 'tl_namespace' => $this->getNamespace(), 'tl_title' => $this->getDBkey(), 'tl_from=pr_page', 'pr_cascade' => 1 );
1377 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1379 if ($dbr->numRows($res)) {
1380 wfProfileOut(__METHOD__
);
1383 wfProfileOut(__METHOD__
);
1388 function areRestrictionsCascading() {
1389 if (!$this->mRestrictionsLoaded
) {
1390 $this->loadRestrictions();
1393 return $this->mCascadeRestriction
;
1397 * Loads a string into mRestrictions array
1398 * @param resource $res restrictions as an SQL result.
1401 function loadRestrictionsFromRow( $res ) {
1402 $dbr =& wfGetDb( DB_SLAVE
);
1404 if (!$dbr->numRows( $res ) ) {
1406 $this->mRestrictionsLoaded
= true;
1410 $this->mRestrictions
['edit'] = array();
1411 $this->mRestrictions
['move'] = array();
1413 while ($row = $dbr->fetchObject( $res ) ) {
1414 # Cycle through all the restrictions.
1416 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1418 $this->mCascadeRestriction |
= $row->pr_cascade
;
1421 $this->mRestrictionsLoaded
= true;
1424 function loadRestrictions() {
1425 if( !$this->mRestrictionsLoaded
) {
1426 $dbr =& wfGetDB( DB_SLAVE
);
1428 $res = $dbr->select( 'page_restrictions', '*',
1429 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1430 $this->loadRestrictionsFromRow( $res );
1435 * Accessor/initialisation for mRestrictions
1438 * @param string $action action that permission needs to be checked for
1439 * @return array the array of groups allowed to edit this article
1441 function getRestrictions( $action ) {
1442 if( $this->exists() ) {
1443 if( !$this->mRestrictionsLoaded
) {
1444 $this->loadRestrictions();
1446 return isset( $this->mRestrictions
[$action] )
1447 ?
$this->mRestrictions
[$action]
1455 * Is there a version of this page in the deletion archive?
1456 * @return int the number of archived revisions
1459 function isDeleted() {
1460 $fname = 'Title::isDeleted';
1461 if ( $this->getNamespace() < 0 ) {
1464 $dbr =& wfGetDB( DB_SLAVE
);
1465 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1466 'ar_title' => $this->getDBkey() ), $fname );
1467 if( $this->getNamespace() == NS_IMAGE
) {
1468 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1469 array( 'fa_name' => $this->getDBkey() ), $fname );
1476 * Get the article ID for this Title from the link cache,
1477 * adding it if necessary
1478 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1480 * @return int the ID
1482 public function getArticleID( $flags = 0 ) {
1483 $linkCache =& LinkCache
::singleton();
1484 if ( $flags & GAID_FOR_UPDATE
) {
1485 $oldUpdate = $linkCache->forUpdate( true );
1486 $this->mArticleID
= $linkCache->addLinkObj( $this );
1487 $linkCache->forUpdate( $oldUpdate );
1489 if ( -1 == $this->mArticleID
) {
1490 $this->mArticleID
= $linkCache->addLinkObj( $this );
1493 return $this->mArticleID
;
1496 function getLatestRevID() {
1497 if ($this->mLatestID
!== false)
1498 return $this->mLatestID
;
1500 $db =& wfGetDB(DB_SLAVE
);
1501 return $this->mLatestID
= $db->selectField( 'revision',
1503 array('rev_page' => $this->getArticleID()),
1504 'Title::getLatestRevID' );
1508 * This clears some fields in this object, and clears any associated
1509 * keys in the "bad links" section of the link cache.
1511 * - This is called from Article::insertNewArticle() to allow
1512 * loading of the new page_id. It's also called from
1513 * Article::doDeleteArticle()
1515 * @param int $newid the new Article ID
1518 function resetArticleID( $newid ) {
1519 $linkCache =& LinkCache
::singleton();
1520 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1522 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1523 else { $this->mArticleID
= $newid; }
1524 $this->mRestrictionsLoaded
= false;
1525 $this->mRestrictions
= array();
1529 * Updates page_touched for this page; called from LinksUpdate.php
1530 * @return bool true if the update succeded
1533 function invalidateCache() {
1534 global $wgUseFileCache;
1536 if ( wfReadOnly() ) {
1540 $dbw =& wfGetDB( DB_MASTER
);
1541 $success = $dbw->update( 'page',
1543 'page_touched' => $dbw->timestamp()
1544 ), array( /* WHERE */
1545 'page_namespace' => $this->getNamespace() ,
1546 'page_title' => $this->getDBkey()
1547 ), 'Title::invalidateCache'
1550 if ($wgUseFileCache) {
1551 $cache = new HTMLFileCache($this);
1552 @unlink
($cache->fileCacheName());
1559 * Prefix some arbitrary text with the namespace or interwiki prefix
1562 * @param string $name the text
1563 * @return string the prefixed text
1566 /* private */ function prefix( $name ) {
1568 if ( '' != $this->mInterwiki
) {
1569 $p = $this->mInterwiki
. ':';
1571 if ( 0 != $this->mNamespace
) {
1572 $p .= $this->getNsText() . ':';
1578 * Secure and split - main initialisation function for this object
1580 * Assumes that mDbkeyform has been set, and is urldecoded
1581 * and uses underscores, but not otherwise munged. This function
1582 * removes illegal characters, splits off the interwiki and
1583 * namespace prefixes, sets the other forms, and canonicalizes
1585 * @return bool true on success
1588 /* private */ function secureAndSplit() {
1589 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1592 static $rxTc = false;
1594 # % is needed as well
1595 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1598 $this->mInterwiki
= $this->mFragment
= '';
1599 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1601 $dbkey = $this->mDbkeyform
;
1603 # Strip Unicode bidi override characters.
1604 # Sometimes they slip into cut-n-pasted page titles, where the
1605 # override chars get included in list displays.
1606 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1607 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1609 # Clean up whitespace
1611 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1612 $dbkey = trim( $dbkey, '_' );
1614 if ( '' == $dbkey ) {
1618 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1619 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1623 $this->mDbkeyform
= $dbkey;
1625 # Initial colon indicates main namespace rather than specified default
1626 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1627 if ( ':' == $dbkey{0} ) {
1628 $this->mNamespace
= NS_MAIN
;
1629 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1632 # Namespace or interwiki prefix
1636 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1638 $lowerNs = $wgContLang->lc( $p );
1639 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1640 # Canonical namespace
1642 $this->mNamespace
= $ns;
1643 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1644 # Ordinary namespace
1646 $this->mNamespace
= $ns;
1647 } elseif( $this->getInterwikiLink( $p ) ) {
1649 # Can't make a local interwiki link to an interwiki link.
1650 # That's just crazy!
1656 $this->mInterwiki
= $wgContLang->lc( $p );
1658 # Redundant interwiki prefix to the local wiki
1659 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1660 if( $dbkey == '' ) {
1661 # Can't have an empty self-link
1664 $this->mInterwiki
= '';
1666 # Do another namespace split...
1670 # If there's an initial colon after the interwiki, that also
1671 # resets the default namespace
1672 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1673 $this->mNamespace
= NS_MAIN
;
1674 $dbkey = substr( $dbkey, 1 );
1677 # If there's no recognized interwiki or namespace,
1678 # then let the colon expression be part of the title.
1683 # We already know that some pages won't be in the database!
1685 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1686 $this->mArticleID
= 0;
1688 $fragment = strstr( $dbkey, '#' );
1689 if ( false !== $fragment ) {
1690 $this->setFragment( $fragment );
1691 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1692 # remove whitespace again: prevents "Foo_bar_#"
1693 # becoming "Foo_bar_"
1694 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1697 # Reject illegal characters.
1699 if( preg_match( $rxTc, $dbkey ) ) {
1704 * Pages with "/./" or "/../" appearing in the URLs will
1705 * often be unreachable due to the way web browsers deal
1706 * with 'relative' URLs. Forbid them explicitly.
1708 if ( strpos( $dbkey, '.' ) !== false &&
1709 ( $dbkey === '.' ||
$dbkey === '..' ||
1710 strpos( $dbkey, './' ) === 0 ||
1711 strpos( $dbkey, '../' ) === 0 ||
1712 strpos( $dbkey, '/./' ) !== false ||
1713 strpos( $dbkey, '/../' ) !== false ) )
1719 * Limit the size of titles to 255 bytes.
1720 * This is typically the size of the underlying database field.
1721 * We make an exception for special pages, which don't need to be stored
1722 * in the database, and may edge over 255 bytes due to subpage syntax
1723 * for long titles, e.g. [[Special:Block/Long name]]
1725 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1726 strlen( $dbkey ) > 512 )
1732 * Normally, all wiki links are forced to have
1733 * an initial capital letter so [[foo]] and [[Foo]]
1734 * point to the same place.
1736 * Don't force it for interwikis, since the other
1737 * site might be case-sensitive.
1739 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1740 $dbkey = $wgContLang->ucfirst( $dbkey );
1744 * Can't make a link to a namespace alone...
1745 * "empty" local links can only be self-links
1746 * with a fragment identifier.
1749 $this->mInterwiki
== '' &&
1750 $this->mNamespace
!= NS_MAIN
) {
1754 // Any remaining initial :s are illegal.
1755 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1760 $this->mDbkeyform
= $dbkey;
1761 $this->mUrlform
= wfUrlencode( $dbkey );
1763 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1769 * Set the fragment for this title
1770 * This is kind of bad, since except for this rarely-used function, Title objects
1771 * are immutable. The reason this is here is because it's better than setting the
1772 * members directly, which is what Linker::formatComment was doing previously.
1774 * @param string $fragment text
1775 * @access kind of public
1777 function setFragment( $fragment ) {
1778 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1782 * Get a Title object associated with the talk page of this article
1783 * @return Title the object for the talk page
1786 function getTalkPage() {
1787 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1791 * Get a title object associated with the subject page of this
1794 * @return Title the object for the subject page
1797 function getSubjectPage() {
1798 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1802 * Get an array of Title objects linking to this Title
1803 * Also stores the IDs in the link cache.
1805 * WARNING: do not use this function on arbitrary user-supplied titles!
1806 * On heavily-used templates it will max out the memory.
1808 * @param string $options may be FOR UPDATE
1809 * @return array the Title objects linking here
1812 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1813 $linkCache =& LinkCache
::singleton();
1816 $db =& wfGetDB( DB_MASTER
);
1818 $db =& wfGetDB( DB_SLAVE
);
1821 $res = $db->select( array( 'page', $table ),
1822 array( 'page_namespace', 'page_title', 'page_id' ),
1824 "{$prefix}_from=page_id",
1825 "{$prefix}_namespace" => $this->getNamespace(),
1826 "{$prefix}_title" => $this->getDbKey() ),
1827 'Title::getLinksTo',
1831 if ( $db->numRows( $res ) ) {
1832 while ( $row = $db->fetchObject( $res ) ) {
1833 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1834 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1835 $retVal[] = $titleObj;
1839 $db->freeResult( $res );
1844 * Get an array of Title objects using this Title as a template
1845 * Also stores the IDs in the link cache.
1847 * WARNING: do not use this function on arbitrary user-supplied titles!
1848 * On heavily-used templates it will max out the memory.
1850 * @param string $options may be FOR UPDATE
1851 * @return array the Title objects linking here
1854 function getTemplateLinksTo( $options = '' ) {
1855 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1859 * Get an array of Title objects referring to non-existent articles linked from this page
1861 * @param string $options may be FOR UPDATE
1862 * @return array the Title objects
1865 function getBrokenLinksFrom( $options = '' ) {
1867 $db =& wfGetDB( DB_MASTER
);
1869 $db =& wfGetDB( DB_SLAVE
);
1872 $res = $db->safeQuery(
1873 "SELECT pl_namespace, pl_title
1876 ON pl_namespace=page_namespace
1877 AND pl_title=page_title
1879 AND page_namespace IS NULL
1881 $db->tableName( 'pagelinks' ),
1882 $db->tableName( 'page' ),
1883 $this->getArticleId(),
1887 if ( $db->numRows( $res ) ) {
1888 while ( $row = $db->fetchObject( $res ) ) {
1889 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1892 $db->freeResult( $res );
1898 * Get a list of URLs to purge from the Squid cache when this
1901 * @return array the URLs
1904 function getSquidURLs() {
1908 $this->getInternalURL(),
1909 $this->getInternalURL( 'action=history' )
1912 // purge variant urls as well
1913 if($wgContLang->hasVariants()){
1914 $variants = $wgContLang->getVariants();
1915 foreach($variants as $vCode){
1916 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1917 $urls[] = $this->getInternalURL('',$vCode);
1924 function purgeSquid() {
1926 if ( $wgUseSquid ) {
1927 $urls = $this->getSquidURLs();
1928 $u = new SquidUpdate( $urls );
1934 * Move this page without authentication
1935 * @param Title &$nt the new page Title
1938 function moveNoAuth( &$nt ) {
1939 return $this->moveTo( $nt, false );
1943 * Check whether a given move operation would be valid.
1944 * Returns true if ok, or a message key string for an error message
1945 * if invalid. (Scarrrrry ugly interface this.)
1946 * @param Title &$nt the new title
1947 * @param bool $auth indicates whether $wgUser's permissions
1949 * @return mixed true on success, message name on failure
1952 function isValidMoveOperation( &$nt, $auth = true ) {
1953 if( !$this or !$nt ) {
1954 return 'badtitletext';
1956 if( $this->equals( $nt ) ) {
1959 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1960 return 'immobile_namespace';
1963 $oldid = $this->getArticleID();
1964 $newid = $nt->getArticleID();
1966 if ( strlen( $nt->getDBkey() ) < 1 ) {
1967 return 'articleexists';
1969 if ( ( '' == $this->getDBkey() ) ||
1971 ( '' == $nt->getDBkey() ) ) {
1972 return 'badarticleerror';
1976 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1977 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1978 return 'protectedpage';
1981 # The move is allowed only if (1) the target doesn't exist, or
1982 # (2) the target is a redirect to the source, and has no history
1983 # (so we can undo bad moves right after they're done).
1985 if ( 0 != $newid ) { # Target exists; check for validity
1986 if ( ! $this->isValidMoveTarget( $nt ) ) {
1987 return 'articleexists';
1994 * Move a title to a new location
1995 * @param Title &$nt the new title
1996 * @param bool $auth indicates whether $wgUser's permissions
1998 * @return mixed true on success, message name on failure
2001 function moveTo( &$nt, $auth = true, $reason = '' ) {
2002 $err = $this->isValidMoveOperation( $nt, $auth );
2003 if( is_string( $err ) ) {
2007 $pageid = $this->getArticleID();
2008 if( $nt->exists() ) {
2009 $this->moveOverExistingRedirect( $nt, $reason );
2010 $pageCountChange = 0;
2011 } else { # Target didn't exist, do normal move.
2012 $this->moveToNewTitle( $nt, $reason );
2013 $pageCountChange = 1;
2015 $redirid = $this->getArticleID();
2017 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2018 $dbw =& wfGetDB( DB_MASTER
);
2019 $categorylinks = $dbw->tableName( 'categorylinks' );
2020 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2021 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2022 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2023 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2027 $oldnamespace = $this->getNamespace() & ~
1;
2028 $newnamespace = $nt->getNamespace() & ~
1;
2029 $oldtitle = $this->getDBkey();
2030 $newtitle = $nt->getDBkey();
2032 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2033 WatchedItem
::duplicateEntries( $this, $nt );
2036 # Update search engine
2037 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2039 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2043 if( $this->isContentPage() && !$nt->isContentPage() ) {
2044 # No longer a content page
2045 # Not viewed, edited, removing
2046 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2047 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2048 # Now a content page
2049 # Not viewed, edited, adding
2050 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2051 } elseif( $pageCountChange ) {
2053 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2062 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2067 * Move page to a title which is at present a redirect to the
2070 * @param Title &$nt the page to move to, which should currently
2074 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2076 $fname = 'Title::moveOverExistingRedirect';
2077 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2080 $comment .= ": $reason";
2083 $now = wfTimestampNow();
2084 $newid = $nt->getArticleID();
2085 $oldid = $this->getArticleID();
2086 $dbw =& wfGetDB( DB_MASTER
);
2087 $linkCache =& LinkCache
::singleton();
2089 # Delete the old redirect. We don't save it to history since
2090 # by definition if we've got here it's rather uninteresting.
2091 # We have to remove it so that the next step doesn't trigger
2092 # a conflict on the unique namespace+title index...
2093 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2095 # Save a null revision in the page's history notifying of the move
2096 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2097 $nullRevId = $nullRevision->insertOn( $dbw );
2099 # Change the name of the target page:
2100 $dbw->update( 'page',
2102 'page_touched' => $dbw->timestamp($now),
2103 'page_namespace' => $nt->getNamespace(),
2104 'page_title' => $nt->getDBkey(),
2105 'page_latest' => $nullRevId,
2107 /* WHERE */ array( 'page_id' => $oldid ),
2110 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2112 # Recreate the redirect, this time in the other direction.
2113 $mwRedir = MagicWord
::get( 'redirect' );
2114 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2115 $redirectArticle = new Article( $this );
2116 $newid = $redirectArticle->insertOn( $dbw );
2117 $redirectRevision = new Revision( array(
2119 'comment' => $comment,
2120 'text' => $redirectText ) );
2121 $redirectRevision->insertOn( $dbw );
2122 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2123 $linkCache->clearLink( $this->getPrefixedDBkey() );
2126 $log = new LogPage( 'move' );
2127 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2129 # Now, we record the link from the redirect to the new title.
2130 # It should have no other outgoing links...
2131 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2132 $dbw->insert( 'pagelinks',
2134 'pl_from' => $newid,
2135 'pl_namespace' => $nt->getNamespace(),
2136 'pl_title' => $nt->getDbKey() ),
2140 if ( $wgUseSquid ) {
2141 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2142 $u = new SquidUpdate( $urls );
2148 * Move page to non-existing title.
2149 * @param Title &$nt the new Title
2152 function moveToNewTitle( &$nt, $reason = '' ) {
2154 $fname = 'MovePageForm::moveToNewTitle';
2155 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2157 $comment .= ": $reason";
2160 $newid = $nt->getArticleID();
2161 $oldid = $this->getArticleID();
2162 $dbw =& wfGetDB( DB_MASTER
);
2163 $now = $dbw->timestamp();
2164 $linkCache =& LinkCache
::singleton();
2166 # Save a null revision in the page's history notifying of the move
2167 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2168 $nullRevId = $nullRevision->insertOn( $dbw );
2171 $dbw->update( 'page',
2173 'page_touched' => $now,
2174 'page_namespace' => $nt->getNamespace(),
2175 'page_title' => $nt->getDBkey(),
2176 'page_latest' => $nullRevId,
2178 /* WHERE */ array( 'page_id' => $oldid ),
2182 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2185 $mwRedir = MagicWord
::get( 'redirect' );
2186 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2187 $redirectArticle = new Article( $this );
2188 $newid = $redirectArticle->insertOn( $dbw );
2189 $redirectRevision = new Revision( array(
2191 'comment' => $comment,
2192 'text' => $redirectText ) );
2193 $redirectRevision->insertOn( $dbw );
2194 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2195 $linkCache->clearLink( $this->getPrefixedDBkey() );
2198 $log = new LogPage( 'move' );
2199 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2201 # Purge caches as per article creation
2202 Article
::onArticleCreate( $nt );
2204 # Record the just-created redirect's linking to the page
2205 $dbw->insert( 'pagelinks',
2207 'pl_from' => $newid,
2208 'pl_namespace' => $nt->getNamespace(),
2209 'pl_title' => $nt->getDBkey() ),
2212 # Purge old title from squid
2213 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2214 $this->purgeSquid();
2218 * Checks if $this can be moved to a given Title
2219 * - Selects for update, so don't call it unless you mean business
2221 * @param Title &$nt the new title to check
2224 function isValidMoveTarget( $nt ) {
2226 $fname = 'Title::isValidMoveTarget';
2227 $dbw =& wfGetDB( DB_MASTER
);
2230 $id = $nt->getArticleID();
2231 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2232 array( 'page_is_redirect','old_text','old_flags' ),
2233 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2234 $fname, 'FOR UPDATE' );
2236 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2238 wfDebug( __METHOD__
. ": not a redirect\n" );
2241 $text = Revision
::getRevisionText( $obj );
2243 # Does the redirect point to the source?
2244 # Or is it a broken self-redirect, usually caused by namespace collisions?
2246 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2247 $redirTitle = Title
::newFromText( $m[1] );
2248 if( !is_object( $redirTitle ) ||
2249 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2250 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2251 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2256 wfDebug( __METHOD__
. ": failsafe\n" );
2260 # Does the article have a history?
2261 $row = $dbw->selectRow( array( 'page', 'revision'),
2263 array( 'page_namespace' => $nt->getNamespace(),
2264 'page_title' => $nt->getDBkey(),
2265 'page_id=rev_page AND page_latest != rev_id'
2266 ), $fname, 'FOR UPDATE'
2269 # Return true if there was no history
2270 return $row === false;
2274 * Create a redirect; fails if the title already exists; does
2277 * @param Title $dest the destination of the redirect
2278 * @param string $comment the comment string describing the move
2279 * @return bool true on success
2282 function createRedirect( $dest, $comment ) {
2283 if ( $this->getArticleID() ) {
2287 $fname = 'Title::createRedirect';
2288 $dbw =& wfGetDB( DB_MASTER
);
2290 $article = new Article( $this );
2291 $newid = $article->insertOn( $dbw );
2292 $revision = new Revision( array(
2294 'comment' => $comment,
2295 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2297 $revision->insertOn( $dbw );
2298 $article->updateRevisionOn( $dbw, $revision, 0 );
2301 $dbw->insert( 'pagelinks',
2303 'pl_from' => $newid,
2304 'pl_namespace' => $dest->getNamespace(),
2305 'pl_title' => $dest->getDbKey()
2309 Article
::onArticleCreate( $this );
2314 * Get categories to which this Title belongs and return an array of
2315 * categories' names.
2317 * @return array an array of parents in the form:
2318 * $parent => $currentarticle
2321 function getParentCategories() {
2324 $titlekey = $this->getArticleId();
2325 $dbr =& wfGetDB( DB_SLAVE
);
2326 $categorylinks = $dbr->tableName( 'categorylinks' );
2329 $sql = "SELECT * FROM $categorylinks"
2330 ." WHERE cl_from='$titlekey'"
2331 ." AND cl_from <> '0'"
2332 ." ORDER BY cl_sortkey";
2334 $res = $dbr->query ( $sql ) ;
2336 if($dbr->numRows($res) > 0) {
2337 while ( $x = $dbr->fetchObject ( $res ) )
2338 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2339 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2340 $dbr->freeResult ( $res ) ;
2348 * Get a tree of parent categories
2349 * @param array $children an array with the children in the keys, to check for circular refs
2353 function getParentCategoryTree( $children = array() ) {
2354 $parents = $this->getParentCategories();
2356 if($parents != '') {
2357 foreach($parents as $parent => $current) {
2358 if ( array_key_exists( $parent, $children ) ) {
2359 # Circular reference
2360 $stack[$parent] = array();
2362 $nt = Title
::newFromText($parent);
2364 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2376 * Get an associative array for selecting this title from
2382 function pageCond() {
2383 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2387 * Get the revision ID of the previous revision
2389 * @param integer $revision Revision ID. Get the revision that was before this one.
2390 * @return integer $oldrevision|false
2392 function getPreviousRevisionID( $revision ) {
2393 $dbr =& wfGetDB( DB_SLAVE
);
2394 return $dbr->selectField( 'revision', 'rev_id',
2395 'rev_page=' . intval( $this->getArticleId() ) .
2396 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2400 * Get the revision ID of the next revision
2402 * @param integer $revision Revision ID. Get the revision that was after this one.
2403 * @return integer $oldrevision|false
2405 function getNextRevisionID( $revision ) {
2406 $dbr =& wfGetDB( DB_SLAVE
);
2407 return $dbr->selectField( 'revision', 'rev_id',
2408 'rev_page=' . intval( $this->getArticleId() ) .
2409 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2413 * Get the number of revisions between the given revision IDs.
2415 * @param integer $old Revision ID.
2416 * @param integer $new Revision ID.
2417 * @return integer Number of revisions between these IDs.
2419 function countRevisionsBetween( $old, $new ) {
2420 $dbr =& wfGetDB( DB_SLAVE
);
2421 return $dbr->selectField( 'revision', 'count(*)',
2422 'rev_page = ' . intval( $this->getArticleId() ) .
2423 ' AND rev_id > ' . intval( $old ) .
2424 ' AND rev_id < ' . intval( $new ) );
2428 * Compare with another title.
2430 * @param Title $title
2433 function equals( $title ) {
2434 // Note: === is necessary for proper matching of number-like titles.
2435 return $this->getInterwiki() === $title->getInterwiki()
2436 && $this->getNamespace() == $title->getNamespace()
2437 && $this->getDbkey() === $title->getDbkey();
2441 * Check if page exists
2445 return $this->getArticleId() != 0;
2449 * Should a link should be displayed as a known link, just based on its title?
2451 * Currently, a self-link with a fragment and special pages are in
2452 * this category. Special pages never exist in the database.
2454 function isAlwaysKnown() {
2455 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2456 || NS_SPECIAL
== $this->mNamespace
;
2460 * Update page_touched timestamps and send squid purge messages for
2461 * pages linking to this title. May be sent to the job queue depending
2462 * on the number of links. Typically called on create and delete.
2464 function touchLinks() {
2465 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2468 if ( $this->getNamespace() == NS_CATEGORY
) {
2469 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2475 * Get the last touched timestamp
2477 function getTouched() {
2478 $dbr =& wfGetDB( DB_SLAVE
);
2479 $touched = $dbr->selectField( 'page', 'page_touched',
2481 'page_namespace' => $this->getNamespace(),
2482 'page_title' => $this->getDBkey()
2489 * Get a cached value from a global cache that is invalidated when this page changes
2490 * @param string $key the key
2491 * @param callback $callback A callback function which generates the value on cache miss
2493 * @deprecated use DependencyWrapper
2495 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2496 return DependencyWrapper
::getValueFromCache( $memc, $key, $expiry, $callback,
2497 $params, new TitleDependency( $this ) );
2500 function trackbackURL() {
2501 global $wgTitle, $wgScriptPath, $wgServer;
2503 return "$wgServer$wgScriptPath/trackback.php?article="
2504 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2507 function trackbackRDF() {
2508 $url = htmlspecialchars($this->getFullURL());
2509 $title = htmlspecialchars($this->getText());
2510 $tburl = $this->trackbackURL();
2513 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2514 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2515 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2518 dc:identifier=\"$url\"
2520 trackback:ping=\"$tburl\" />
2525 * Generate strings used for xml 'id' names in monobook tabs
2528 function getNamespaceKey() {
2530 switch ($this->getNamespace()) {
2533 return 'nstab-main';
2536 return 'nstab-user';
2538 return 'nstab-media';
2540 return 'nstab-special';
2542 case NS_PROJECT_TALK
:
2543 return 'nstab-project';
2546 return 'nstab-image';
2548 case NS_MEDIAWIKI_TALK
:
2549 return 'nstab-mediawiki';
2551 case NS_TEMPLATE_TALK
:
2552 return 'nstab-template';
2555 return 'nstab-help';
2557 case NS_CATEGORY_TALK
:
2558 return 'nstab-category';
2560 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2565 * Returns true if this title resolves to the named special page
2566 * @param string $name The special page name
2569 function isSpecial( $name ) {
2570 if ( $this->getNamespace() == NS_SPECIAL
) {
2571 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2572 if ( $name == $thisName ) {
2580 * If the Title refers to a special page alias which is not the local default,
2581 * returns a new Title which points to the local default. Otherwise, returns $this.
2583 function fixSpecialName() {
2584 if ( $this->getNamespace() == NS_SPECIAL
) {
2585 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2586 if ( $canonicalName ) {
2587 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2588 if ( $localName != $this->mDbkeyform
) {
2589 return Title
::makeTitle( NS_SPECIAL
, $localName );
2597 * Is this Title in a namespace which contains content?
2598 * In other words, is this a content page, for the purposes of calculating
2603 public function isContentPage() {
2604 return Namespace::isContent( $this->getNamespace() );