8 if ( !class_exists( 'UtfNormal' ) ) {
9 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
12 define ( 'GAID_FOR_UPDATE', 1 );
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
19 define( 'MW_TITLECACHE_MAX', 1000 );
21 # Constants for pr_cascade bitfield
22 define( 'CASCADE', 1 );
26 * - Represents a title, which may contain an interwiki designation or namespace
27 * - 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 $mUserCaseDBKey; # DB key with the initial letter in the case specified by the user
51 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki; # Interwiki prefix (or null string)
53 var $mFragment; # Title fragment (i.e. the bit after the #)
54 var $mArticleID; # Article ID, fetched from the link cache on demand
55 var $mLatestID; # ID of most recent revision
56 var $mRestrictions; # Array of groups allowed to edit this article
57 var $mCascadeRestriction; # Cascade restrictions on this page to included templates and images?
58 var $mRestrictionsExpiry; # When do the restrictions on this page expire?
59 var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page?
60 var $mCascadeRestrictionSources;# Where are the cascading restrictions coming from on this page?
61 var $mRestrictionsLoaded; # Boolean for initialisation on demand
62 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
63 var $mDefaultNamespace; # Namespace index when there is no namespace
64 # Zero except in {{transclusion}} tags
65 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
73 /* private */ function __construct() {
74 $this->mInterwiki
= $this->mUrlform
=
75 $this->mTextform
= $this->mDbkeyform
= '';
76 $this->mArticleID
= -1;
77 $this->mNamespace
= NS_MAIN
;
78 $this->mRestrictionsLoaded
= false;
79 $this->mRestrictions
= array();
80 # Dont change the following, NS_MAIN is hardcoded in several place
82 $this->mDefaultNamespace
= NS_MAIN
;
83 $this->mWatched
= NULL;
84 $this->mLatestID
= false;
85 $this->mOldRestrictions
= false;
89 * Create a new Title from a prefixed DB key
90 * @param string $key The database key, which has underscores
91 * instead of spaces, possibly including namespace and
93 * @return Title the new object, or NULL on an error
95 public static function newFromDBkey( $key ) {
97 $t->mDbkeyform
= $key;
98 if( $t->secureAndSplit() )
105 * Create a new Title from text, such as what one would
106 * find in a link. Decodes any HTML entities in the text.
108 * @param string $text the link text; spaces, prefixes,
109 * and an initial ':' indicating the main namespace
111 * @param int $defaultNamespace the namespace to use if
112 * none is specified by a prefix
113 * @return Title the new object, or NULL on an error
115 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
116 if( is_object( $text ) ) {
117 throw new MWException( 'Title::newFromText given an object' );
121 * Wiki pages often contain multiple links to the same page.
122 * Title normalization and parsing can become expensive on
123 * pages with many links, so we can save a little time by
126 * In theory these are value objects and won't get changed...
128 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
129 return Title
::$titleCache[$text];
133 * Convert things like é ā or 〗 into real text...
135 $filteredText = Sanitizer
::decodeCharReferences( $text );
138 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
139 $t->mDefaultNamespace
= $defaultNamespace;
141 static $cachedcount = 0 ;
142 if( $t->secureAndSplit() ) {
143 if( $defaultNamespace == NS_MAIN
) {
144 if( $cachedcount >= MW_TITLECACHE_MAX
) {
145 # Avoid memory leaks on mass operations...
146 Title
::$titleCache = array();
150 Title
::$titleCache[$text] =& $t;
160 * Create a new Title from URL-encoded text. Ensures that
161 * the given title's length does not exceed the maximum.
162 * @param string $url the title, as might be taken from a URL
163 * @return Title the new object, or NULL on an error
165 public static function newFromURL( $url ) {
166 global $wgLegalTitleChars;
169 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
170 # but some URLs used it as a space replacement and they still come
171 # from some external search tools.
172 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
173 $url = str_replace( '+', ' ', $url );
176 $t->mDbkeyform
= str_replace( ' ', '_', $url );
177 if( $t->secureAndSplit() ) {
185 * Create a new Title from an article ID
187 * @todo This is inefficiently implemented, the page row is requested
188 * but not used for anything else
190 * @param int $id the page_id corresponding to the Title to create
191 * @return Title the new object, or NULL on an error
193 public static 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 * Make an array of titles from an array of IDs
209 public static function newFromIDs( $ids ) {
210 $dbr = wfGetDB( DB_SLAVE
);
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
232 public static function &makeTitle( $ns, $title ) {
236 $t->mNamespace
= $ns = intval( $ns );
237 $t->mDbkeyform
= str_replace( ' ', '_', $title );
238 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
239 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
240 $t->mTextform
= str_replace( '_', ' ', $title );
245 * Create a new Title from a namespace index and a DB key.
246 * The parameters will be checked for validity, which is a bit slower
247 * than makeTitle() but safer for user-provided data.
249 * @param int $ns the namespace of the article
250 * @param string $title the database key form
251 * @return Title the new object, or NULL on an error
253 public static function makeTitleSafe( $ns, $title ) {
255 $t->mDbkeyform
= Title
::makeName( $ns, $title );
256 if( $t->secureAndSplit() ) {
264 * Create a new Title for the Main Page
265 * @return Title the new object
267 public static function newMainPage() {
268 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
272 * Extract a redirect destination from a string and return the
273 * Title, or null if the text doesn't contain a valid redirect
275 * @param string $text Text with possible redirect
278 public static function newFromRedirect( $text ) {
279 $redir = MagicWord
::get( 'redirect' );
280 if( $redir->matchStart( $text ) ) {
281 // Extract the first link and see if it's usable
282 if( preg_match( '!\[{2}(.*?)(?:\||\]{2})!', $text, $m ) ) {
283 // Strip preceding colon used to "escape" categories, etc.
284 // and URL-decode links
285 $m[1] = urldecode( ltrim( $m[1], ':' ) );
286 $title = Title
::newFromText( $m[1] );
287 // Redirects to Special:Userlogout are not permitted
288 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
295 #----------------------------------------------------------------------------
297 #----------------------------------------------------------------------------
300 * Get the prefixed DB key associated with an ID
301 * @param int $id the page_id of the article
302 * @return Title an object representing the article, or NULL
303 * if no such article was found
307 function nameOf( $id ) {
308 $fname = 'Title::nameOf';
309 $dbr = wfGetDB( DB_SLAVE
);
311 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
312 if ( $s === false ) { return NULL; }
314 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
319 * Get a regex character class describing the legal characters in a link
320 * @return string the list of characters, not delimited
322 public static 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 public static function indexTitle( $ns, $title ) {
339 $lc = SearchEngine
::legalSearchChars() . '&#;';
340 $t = $wgContLang->stripForSearch( $title );
341 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
342 $t = $wgContLang->lc( $t );
345 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
346 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
348 $t = preg_replace( "/\\s+/", ' ', $t );
350 if ( $ns == NS_IMAGE
) {
351 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
357 * Make a prefixed DB key from a DB key and a namespace index
358 * @param int $ns numerical representation of the namespace
359 * @param string $title the DB key form the title
360 * @return string the prefixed form of the title
362 public static function makeName( $ns, $title ) {
365 $n = $wgContLang->getNsText( $ns );
366 return $n == '' ?
$title : "$n:$title";
370 * Returns the URL associated with an interwiki prefix
371 * @param string $key the interwiki prefix (e.g. "MeatBall")
372 * @return the associated URL, containing "$1", which should be
373 * replaced by an article title
376 public function getInterwikiLink( $key ) {
377 global $wgMemc, $wgInterwikiExpiry;
378 global $wgInterwikiCache, $wgContLang;
379 $fname = 'Title::getInterwikiLink';
381 $key = $wgContLang->lc( $key );
383 $k = wfMemcKey( 'interwiki', $key );
384 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
385 return Title
::$interwikiCache[$k]->iw_url
;
388 if ($wgInterwikiCache) {
389 return Title
::getInterwikiCached( $key );
392 $s = $wgMemc->get( $k );
393 # Ignore old keys with no iw_local
394 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
395 Title
::$interwikiCache[$k] = $s;
399 $dbr = wfGetDB( DB_SLAVE
);
400 $res = $dbr->select( 'interwiki',
401 array( 'iw_url', 'iw_local', 'iw_trans' ),
402 array( 'iw_prefix' => $key ), $fname );
407 $s = $dbr->fetchObject( $res );
409 # Cache non-existence: create a blank object and save it to memcached
415 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
416 Title
::$interwikiCache[$k] = $s;
422 * Fetch interwiki prefix data from local cache in constant database
424 * More logic is explained in DefaultSettings
426 * @return string URL of interwiki site
428 public static function getInterwikiCached( $key ) {
429 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
433 $db=dba_open($wgInterwikiCache,'r','cdb');
434 /* Resolve site name */
435 if ($wgInterwikiScopes>=3 and !$site) {
436 $site = dba_fetch('__sites:' . wfWikiID(), $db);
438 $site = $wgInterwikiFallbackSite;
440 $value = dba_fetch( wfMemcKey( $key ), $db);
441 if ($value=='' and $wgInterwikiScopes>=3) {
443 $value = dba_fetch("_{$site}:{$key}", $db);
445 if ($value=='' and $wgInterwikiScopes>=2) {
447 $value = dba_fetch("__global:{$key}", $db);
456 list($local,$url)=explode(' ',$value,2);
458 $s->iw_local
=(int)$local;
460 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
464 * Determine whether the object refers to a page within
467 * @return bool TRUE if this is an in-project interwiki link
468 * or a wikilink, FALSE otherwise
470 public function isLocal() {
471 if ( $this->mInterwiki
!= '' ) {
472 # Make sure key is loaded into cache
473 $this->getInterwikiLink( $this->mInterwiki
);
474 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
475 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
482 * Determine whether the object refers to a page within
483 * this project and is transcludable.
485 * @return bool TRUE if this is transcludable
487 public function isTrans() {
488 if ($this->mInterwiki
== '')
490 # Make sure key is loaded into cache
491 $this->getInterwikiLink( $this->mInterwiki
);
492 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
493 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
497 * Escape a text fragment, say from a link, for a URL
499 static function escapeFragmentForURL( $fragment ) {
500 $fragment = str_replace( ' ', '_', $fragment );
501 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
502 $replaceArray = array(
506 return strtr( $fragment, $replaceArray );
509 #----------------------------------------------------------------------------
511 #----------------------------------------------------------------------------
513 /** Simple accessors */
515 * Get the text form (spaces not underscores) of the main part
518 public function getText() { return $this->mTextform
; }
520 * Get the URL-encoded form of the main part
523 public function getPartialURL() { return $this->mUrlform
; }
525 * Get the main part with underscores
528 public function getDBkey() { return $this->mDbkeyform
; }
530 * Get the namespace index, i.e. one of the NS_xxxx constants
533 public function getNamespace() { return $this->mNamespace
; }
535 * Get the namespace text
538 public function getNsText() {
539 global $wgContLang, $wgCanonicalNamespaceNames;
541 if ( '' != $this->mInterwiki
) {
542 // This probably shouldn't even happen. ohh man, oh yuck.
543 // But for interwiki transclusion it sometimes does.
544 // Shit. Shit shit shit.
546 // Use the canonical namespaces if possible to try to
547 // resolve a foreign namespace.
548 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
549 return $wgCanonicalNamespaceNames[$this->mNamespace
];
552 return $wgContLang->getNsText( $this->mNamespace
);
555 * Get the DB key with the initial letter case as specified by the user
557 function getUserCaseDBKey() {
558 return $this->mUserCaseDBKey
;
561 * Get the namespace text of the subject (rather than talk) page
564 public function getSubjectNsText() {
566 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
570 * Get the namespace text of the talk page
573 public function getTalkNsText() {
575 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
579 * Could this title have a corresponding talk page?
582 public function canTalk() {
583 return( Namespace::canTalk( $this->mNamespace
) );
587 * Get the interwiki prefix (or null string)
590 public function getInterwiki() { return $this->mInterwiki
; }
592 * Get the Title fragment (i.e. the bit after the #) in text form
595 public function getFragment() { return $this->mFragment
; }
597 * Get the fragment in URL form, including the "#" character if there is one
600 public function getFragmentForURL() {
601 if ( $this->mFragment
== '' ) {
604 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
608 * Get the default namespace index, for when there is no namespace
611 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
614 * Get title for search index
615 * @return string a stripped-down title string ready for the
618 public function getIndexTitle() {
619 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
623 * Get the prefixed database key form
624 * @return string the prefixed title, with underscores and
625 * any interwiki and namespace prefixes
627 public function getPrefixedDBkey() {
628 $s = $this->prefix( $this->mDbkeyform
);
629 $s = str_replace( ' ', '_', $s );
634 * Get the prefixed title with spaces.
635 * This is the form usually used for display
636 * @return string the prefixed title, with spaces
638 public function getPrefixedText() {
639 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
640 $s = $this->prefix( $this->mTextform
);
641 $s = str_replace( '_', ' ', $s );
642 $this->mPrefixedText
= $s;
644 return $this->mPrefixedText
;
648 * Get the prefixed title with spaces, plus any fragment
649 * (part beginning with '#')
650 * @return string the prefixed title, with spaces and
651 * the fragment, including '#'
653 public function getFullText() {
654 $text = $this->getPrefixedText();
655 if( '' != $this->mFragment
) {
656 $text .= '#' . $this->mFragment
;
662 * Get the base name, i.e. the leftmost parts before the /
663 * @return string Base name
665 public function getBaseText() {
666 global $wgNamespacesWithSubpages;
667 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
668 $parts = explode( '/', $this->getText() );
669 # Don't discard the real title if there's no subpage involved
670 if( count( $parts ) > 1 )
671 unset( $parts[ count( $parts ) - 1 ] );
672 return implode( '/', $parts );
674 return $this->getText();
679 * Get the lowest-level subpage name, i.e. the rightmost part after /
680 * @return string Subpage name
682 public function getSubpageText() {
683 global $wgNamespacesWithSubpages;
684 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
685 $parts = explode( '/', $this->mTextform
);
686 return( $parts[ count( $parts ) - 1 ] );
688 return( $this->mTextform
);
693 * Get a URL-encoded form of the subpage text
694 * @return string URL-encoded subpage name
696 public function getSubpageUrlForm() {
697 $text = $this->getSubpageText();
698 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
699 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
704 * Get a URL-encoded title (not an actual URL) including interwiki
705 * @return string the URL-encoded form
707 public function getPrefixedURL() {
708 $s = $this->prefix( $this->mDbkeyform
);
709 $s = str_replace( ' ', '_', $s );
711 $s = wfUrlencode ( $s ) ;
713 # Cleaning up URL to make it look nice -- is this safe?
714 $s = str_replace( '%28', '(', $s );
715 $s = str_replace( '%29', ')', $s );
721 * Get a real URL referring to this title, with interwiki link and
724 * @param string $query an optional query string, not used
725 * for interwiki links
726 * @param string $variant language variant of url (for sr, zh..)
727 * @return string the URL
729 public function getFullURL( $query = '', $variant = false ) {
730 global $wgContLang, $wgServer, $wgRequest;
732 if ( '' == $this->mInterwiki
) {
733 $url = $this->getLocalUrl( $query, $variant );
735 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
736 // Correct fix would be to move the prepending elsewhere.
737 if ($wgRequest->getVal('action') != 'render') {
738 $url = $wgServer . $url;
741 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
743 $namespace = wfUrlencode( $this->getNsText() );
744 if ( '' != $namespace ) {
745 # Can this actually happen? Interwikis shouldn't be parsed.
746 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
749 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
750 $url = wfAppendQuery( $url, $query );
753 # Finally, add the fragment.
754 $url .= $this->getFragmentForURL();
756 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
761 * Get a URL with no fragment or server name. If this page is generated
762 * with action=render, $wgServer is prepended.
763 * @param string $query an optional query string; if not specified,
764 * $wgArticlePath will be used.
765 * @param string $variant language variant of url (for sr, zh..)
766 * @return string the URL
768 public function getLocalURL( $query = '', $variant = false ) {
769 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
770 global $wgVariantArticlePath, $wgContLang, $wgUser;
772 // internal links should point to same variant as current page (only anonymous users)
773 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
774 $pref = $wgContLang->getPreferredVariant(false);
775 if($pref != $wgContLang->getCode())
779 if ( $this->isExternal() ) {
780 $url = $this->getFullURL();
782 // This is currently only used for edit section links in the
783 // context of interwiki transclusion. In theory we should
784 // append the query to the end of any existing query string,
785 // but interwiki transclusion is already broken in that case.
789 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
790 if ( $query == '' ) {
791 if($variant!=false && $wgContLang->hasVariants()){
792 if($wgVariantArticlePath==false) {
793 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
795 $variantArticlePath = $wgVariantArticlePath;
797 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
798 $url = str_replace( '$1', $dbkey, $url );
801 $url = str_replace( '$1', $dbkey, $wgArticlePath );
804 global $wgActionPaths;
807 if( !empty( $wgActionPaths ) &&
808 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
810 $action = urldecode( $matches[2] );
811 if( isset( $wgActionPaths[$action] ) ) {
812 $query = $matches[1];
813 if( isset( $matches[4] ) ) $query .= $matches[4];
814 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
815 if( $query != '' ) $url .= '?' . $query;
818 if ( $url === false ) {
819 if ( $query == '-' ) {
822 $url = "{$wgScript}?title={$dbkey}&{$query}";
826 // FIXME: this causes breakage in various places when we
827 // actually expected a local URL and end up with dupe prefixes.
828 if ($wgRequest->getVal('action') == 'render') {
829 $url = $wgServer . $url;
832 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
837 * Get an HTML-escaped version of the URL form, suitable for
838 * using in a link, without a server name or fragment
839 * @param string $query an optional query string
840 * @return string the URL
842 public function escapeLocalURL( $query = '' ) {
843 return htmlspecialchars( $this->getLocalURL( $query ) );
847 * Get an HTML-escaped version of the URL form, suitable for
848 * using in a link, including the server name and fragment
850 * @return string the URL
851 * @param string $query an optional query string
853 public function escapeFullURL( $query = '' ) {
854 return htmlspecialchars( $this->getFullURL( $query ) );
858 * Get the URL form for an internal link.
859 * - Used in various Squid-related code, in case we have a different
860 * internal hostname for the server from the exposed one.
862 * @param string $query an optional query string
863 * @param string $variant language variant of url (for sr, zh..)
864 * @return string the URL
866 public function getInternalURL( $query = '', $variant = false ) {
867 global $wgInternalServer;
868 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
869 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
874 * Get the edit URL for this Title
875 * @return string the URL, or a null string if this is an
878 public function getEditURL() {
879 if ( '' != $this->mInterwiki
) { return ''; }
880 $s = $this->getLocalURL( 'action=edit' );
886 * Get the HTML-escaped displayable text form.
887 * Used for the title field in <a> tags.
888 * @return string the text, including any prefixes
890 public function getEscapedText() {
891 return htmlspecialchars( $this->getPrefixedText() );
895 * Is this Title interwiki?
898 public function isExternal() { return ( '' != $this->mInterwiki
); }
901 * Is this page "semi-protected" - the *only* protection is autoconfirm?
903 * @param string Action to check (default: edit)
906 public function isSemiProtected( $action = 'edit' ) {
907 if( $this->exists() ) {
908 $restrictions = $this->getRestrictions( $action );
909 if( count( $restrictions ) > 0 ) {
910 foreach( $restrictions as $restriction ) {
911 if( strtolower( $restriction ) != 'autoconfirmed' )
920 # If it doesn't exist, it can't be protected
926 * Does the title correspond to a protected article?
927 * @param string $what the action the page is protected from,
928 * by default checks move and edit
931 public function isProtected( $action = '' ) {
932 global $wgRestrictionLevels;
934 # Special pages have inherent protection
935 if( $this->getNamespace() == NS_SPECIAL
)
938 # Check regular protection levels
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?
964 public function userIsWatching() {
967 if ( is_null( $this->mWatched
) ) {
968 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
969 $this->mWatched
= false;
971 $this->mWatched
= $wgUser->isWatched( $this );
974 return $this->mWatched
;
978 * Can $wgUser perform $action on this page?
979 * This skips potentially expensive cascading permission checks.
981 * Suitable for use for nonessential UI controls in common cases, but
982 * _not_ for functional access control.
984 * May provide false positives, but should never provide a false negative.
986 * @param string $action action that permission needs to be checked for
989 public function quickUserCan( $action ) {
990 return $this->userCan( $action, false );
994 * Determines if $wgUser is unable to edit this page because it has been protected
995 * by $wgNamespaceProtection.
999 public function isNamespaceProtected() {
1000 global $wgNamespaceProtection, $wgUser;
1001 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1002 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1003 if( $right != '' && !$wgUser->isAllowed( $right ) )
1011 * Can $wgUser perform $action on this page?
1012 * @param string $action action that permission needs to be checked for
1013 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1016 public function userCan( $action, $doExpensiveQueries = true ) {
1018 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1022 * Can $user perform $action on this page?
1023 * @param string $action action that permission needs to be checked for
1024 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1025 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1027 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1028 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1033 if ( wfReadOnly() && $action != 'read' ) {
1034 $errors[] = array( 'readonlytext' );
1037 if ( $user->isBlockedFrom( $this ) ) {
1038 $block = $user->mBlock
;
1040 // This is from OutputPage::blockedPage
1041 // Copied at r23888 by werdna
1043 $id = $user->blockedBy();
1044 $reason = $user->blockedFor();
1047 if ( is_numeric( $id ) ) {
1048 $name = User
::whoIs( $id );
1053 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1054 $blockid = $block->mId
;
1055 $blockExpiry = $user->mBlock
->mExpiry
;
1057 if ( $blockExpiry == 'infinity' ) {
1058 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1059 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1061 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1062 if ( strpos( $option, ':' ) == false )
1065 list ($show, $value) = explode( ":", $option );
1067 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1068 $blockExpiry = $show;
1073 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1076 $intended = $user->mBlock
->mAddress
;
1078 $errors[] = array ( ($block->mAuto ?
'autoblockedtext-concise' : 'blockedtext-concise'), $link, $reason, $ip, name
, $blockid, $blockExpiry, $intended );
1085 * Can $user perform $action on this page?
1086 * This is an internal function, which checks ONLY that previously checked by userCan (i.e. it leaves out checks on wfReadOnly() and blocks)
1087 * @param string $action action that permission needs to be checked for
1088 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1089 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1091 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1092 $fname = 'Title::userCan';
1093 wfProfileIn( $fname );
1097 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1098 return $result ?
array() : array( array( 'badaccess-group0' ) );
1101 if( NS_SPECIAL
== $this->mNamespace
) {
1102 $errors[] = array('ns-specialprotected');
1105 if ( $this->isNamespaceProtected() ) {
1106 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace ?
array('protectedinterface') : array( 'namespaceprotected', $wgContLang->getNSText( $this->mNamespace
) ) );
1109 if( $this->mDbkeyform
== '_' ) {
1110 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1111 $errors[] = array('badaccess-group0');
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 && !$user->isAllowed('editinterface')
1119 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1120 $errors[] = array('customcssjsprotected');
1123 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1124 # We /could/ use the protection level on the source page, but it's fairly ugly
1125 # as we have to establish a precedence hierarchy for pages included by multiple
1126 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1127 # as they could remove the protection anyway.
1128 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1129 # Cascading protection depends on more than this page...
1130 # Several cascading protected pages may include this page...
1131 # Check each cascading level
1132 # This is only for protection restrictions, not for all actions
1133 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1134 foreach( $restrictions[$action] as $right ) {
1135 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1136 if( '' != $right && !$user->isAllowed( $right ) ) {
1138 foreach( $cascadeSources as $id => $page )
1139 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1140 $errors[] = array( 'cascadeprotected', array_len( $cascadingSources ), $pages );
1146 foreach( $this->getRestrictions($action) as $right ) {
1147 // Backwards compatibility, rewrite sysop -> protect
1148 if ( $right == 'sysop' ) {
1151 if( '' != $right && !$user->isAllowed( $right ) ) {
1152 $errors[] = array( 'protectedpagetext' );
1156 if( $action == 'create' ) {
1157 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1158 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1159 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1161 } elseif( $action == 'move' &&
1162 !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1163 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1164 } else if ( !$user->isAllowed( $action ) ) {
1167 global $wgGroupPermissions;
1168 foreach( $wgGroupPermissions as $key => $value ) {
1169 if( isset( $value[$action] ) && $value[$action] == true ) {
1170 $groupName = User
::getGroupName( $key );
1171 $groupPage = User
::getGroupPage( $key );
1173 $skin = $user->getSkin();
1174 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1176 $groups[] = $groupName;
1180 $n = count( $groups );
1181 $groups = implode( ', ', $groups );
1186 $return = array( "badaccess-group$n", $groups );
1189 $return = array( 'badaccess-groups', $groups );
1191 $errors[] = $return;
1194 wfProfileOut( $fname );
1199 * Can $wgUser edit this page?
1201 * @deprecated use userCan('edit')
1203 public function userCanEdit( $doExpensiveQueries = true ) {
1204 return $this->userCan( 'edit', $doExpensiveQueries );
1208 * Can $wgUser create this page?
1210 * @deprecated use userCan('create')
1212 public function userCanCreate( $doExpensiveQueries = true ) {
1213 return $this->userCan( 'create', $doExpensiveQueries );
1217 * Can $wgUser move this page?
1219 * @deprecated use userCan('move')
1221 public function userCanMove( $doExpensiveQueries = true ) {
1222 return $this->userCan( 'move', $doExpensiveQueries );
1226 * Would anybody with sufficient privileges be able to move this page?
1227 * Some pages just aren't movable.
1231 public function isMovable() {
1232 return Namespace::isMovable( $this->getNamespace() )
1233 && $this->getInterwiki() == '';
1237 * Can $wgUser read this page?
1239 * @todo fold these checks into userCan()
1241 public function userCanRead() {
1245 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1246 if ( $result !== null ) {
1250 if( $wgUser->isAllowed( 'read' ) ) {
1253 global $wgWhitelistRead;
1256 * Always grant access to the login page.
1257 * Even anons need to be able to log in.
1259 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1264 * Check for explicit whitelisting
1266 $name = $this->getPrefixedText();
1267 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead, true ) )
1271 * Old settings might have the title prefixed with
1272 * a colon for main-namespace pages
1274 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1275 if( in_array( ':' . $name, $wgWhitelistRead ) )
1280 * If it's a special page, ditch the subpage bit
1283 if( $this->getNamespace() == NS_SPECIAL
) {
1284 $name = $this->getText();
1285 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $name );
1286 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1287 if( in_array( $pure, $wgWhitelistRead, true ) )
1296 * Is this a talk page of some sort?
1299 public function isTalkPage() {
1300 return Namespace::isTalk( $this->getNamespace() );
1304 * Is this a subpage?
1307 public function isSubpage() {
1308 global $wgNamespacesWithSubpages;
1310 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1311 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1318 * Could this page contain custom CSS or JavaScript, based
1323 public function isCssOrJsPage() {
1324 return $this->mNamespace
== NS_MEDIAWIKI
1325 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1329 * Is this a .css or .js subpage of a user page?
1332 public function isCssJsSubpage() {
1333 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1336 * Is this a *valid* .css or .js subpage of a user page?
1337 * Check that the corresponding skin exists
1339 public function isValidCssJsSubpage() {
1340 if ( $this->isCssJsSubpage() ) {
1341 $skinNames = Skin
::getSkinNames();
1342 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1348 * Trim down a .css or .js subpage title to get the corresponding skin name
1350 public function getSkinFromCssJsSubpage() {
1351 $subpage = explode( '/', $this->mTextform
);
1352 $subpage = $subpage[ count( $subpage ) - 1 ];
1353 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1356 * Is this a .css subpage of a user page?
1359 public function isCssSubpage() {
1360 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1363 * Is this a .js subpage of a user page?
1366 public function isJsSubpage() {
1367 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1370 * Protect css/js subpages of user pages: can $wgUser edit
1374 * @todo XXX: this might be better using restrictions
1376 public function userCanEditCssJsSubpage() {
1378 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1382 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1384 * @return bool If the page is subject to cascading restrictions.
1386 public function isCascadeProtected() {
1387 list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false );
1388 return ( $sources > 0 );
1392 * Cascading protection: Get the source of any cascading restrictions on this page.
1394 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1395 * @return array( mixed title array, restriction array)
1396 * Array of the Title objects of the pages from which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1397 * The restriction array is an array of each type, each of which contains an array of unique groups
1399 public function getCascadeProtectionSources( $get_pages = true ) {
1400 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1402 # Define our dimension of restrictions types
1403 $pagerestrictions = array();
1404 foreach( $wgRestrictionTypes as $action )
1405 $pagerestrictions[$action] = array();
1407 if (!$wgEnableCascadingProtection)
1408 return array( false, $pagerestrictions );
1410 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1411 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1412 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1413 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1416 wfProfileIn( __METHOD__
);
1418 $dbr = wfGetDb( DB_SLAVE
);
1420 if ( $this->getNamespace() == NS_IMAGE
) {
1421 $tables = array ('imagelinks', 'page_restrictions');
1422 $where_clauses = array(
1423 'il_to' => $this->getDBkey(),
1425 'pr_cascade' => 1 );
1427 $tables = array ('templatelinks', 'page_restrictions');
1428 $where_clauses = array(
1429 'tl_namespace' => $this->getNamespace(),
1430 'tl_title' => $this->getDBkey(),
1432 'pr_cascade' => 1 );
1436 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1437 $where_clauses[] = 'page_id=pr_page';
1440 $cols = array( 'pr_expiry' );
1443 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1445 $sources = $get_pages ?
array() : false;
1446 $now = wfTimestampNow();
1447 $purgeExpired = false;
1449 while( $row = $dbr->fetchObject( $res ) ) {
1450 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1451 if( $expiry > $now ) {
1453 $page_id = $row->pr_page
;
1454 $page_ns = $row->page_namespace
;
1455 $page_title = $row->page_title
;
1456 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1457 # Add groups needed for each restriction type if its not already there
1458 # Make sure this restriction type still exists
1459 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1460 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1466 // Trigger lazy purge of expired restrictions from the db
1467 $purgeExpired = true;
1470 if( $purgeExpired ) {
1471 Title
::purgeExpiredRestrictions();
1474 wfProfileOut( __METHOD__
);
1477 $this->mCascadeSources
= $sources;
1478 $this->mCascadingRestrictions
= $pagerestrictions;
1480 $this->mHasCascadingRestrictions
= $sources;
1483 return array( $sources, $pagerestrictions );
1486 function areRestrictionsCascading() {
1487 if (!$this->mRestrictionsLoaded
) {
1488 $this->loadRestrictions();
1491 return $this->mCascadeRestriction
;
1495 * Loads a string into mRestrictions array
1496 * @param resource $res restrictions as an SQL result.
1498 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1499 $dbr = wfGetDb( DB_SLAVE
);
1501 $this->mRestrictions
['edit'] = array();
1502 $this->mRestrictions
['move'] = array();
1504 # Backwards-compatibility: also load the restrictions from the page record (old format).
1506 if ( $oldFashionedRestrictions == NULL ) {
1507 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1510 if ($oldFashionedRestrictions != '') {
1512 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1513 $temp = explode( '=', trim( $restrict ) );
1514 if(count($temp) == 1) {
1515 // old old format should be treated as edit/move restriction
1516 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1517 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1519 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1523 $this->mOldRestrictions
= true;
1524 $this->mCascadeRestriction
= false;
1525 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1529 if( $dbr->numRows( $res ) ) {
1530 # Current system - load second to make them override.
1531 $now = wfTimestampNow();
1532 $purgeExpired = false;
1534 while ($row = $dbr->fetchObject( $res ) ) {
1535 # Cycle through all the restrictions.
1537 // This code should be refactored, now that it's being used more generally,
1538 // But I don't really see any harm in leaving it in Block for now -werdna
1539 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1541 // Only apply the restrictions if they haven't expired!
1542 if ( !$expiry ||
$expiry > $now ) {
1543 $this->mRestrictionsExpiry
= $expiry;
1544 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1546 $this->mCascadeRestriction |
= $row->pr_cascade
;
1548 // Trigger a lazy purge of expired restrictions
1549 $purgeExpired = true;
1553 if( $purgeExpired ) {
1554 Title
::purgeExpiredRestrictions();
1558 $this->mRestrictionsLoaded
= true;
1561 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1562 if( !$this->mRestrictionsLoaded
) {
1563 $dbr = wfGetDB( DB_SLAVE
);
1565 $res = $dbr->select( 'page_restrictions', '*',
1566 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1568 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1573 * Purge expired restrictions from the page_restrictions table
1575 static function purgeExpiredRestrictions() {
1576 $dbw = wfGetDB( DB_MASTER
);
1577 $dbw->delete( 'page_restrictions',
1578 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1583 * Accessor/initialisation for mRestrictions
1585 * @param string $action action that permission needs to be checked for
1586 * @return array the array of groups allowed to edit this article
1588 public function getRestrictions( $action ) {
1589 if( $this->exists() ) {
1590 if( !$this->mRestrictionsLoaded
) {
1591 $this->loadRestrictions();
1593 return isset( $this->mRestrictions
[$action] )
1594 ?
$this->mRestrictions
[$action]
1602 * Is there a version of this page in the deletion archive?
1603 * @return int the number of archived revisions
1605 public function isDeleted() {
1606 $fname = 'Title::isDeleted';
1607 if ( $this->getNamespace() < 0 ) {
1610 $dbr = wfGetDB( DB_SLAVE
);
1611 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1612 'ar_title' => $this->getDBkey() ), $fname );
1613 if( $this->getNamespace() == NS_IMAGE
) {
1614 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1615 array( 'fa_name' => $this->getDBkey() ), $fname );
1622 * Get the article ID for this Title from the link cache,
1623 * adding it if necessary
1624 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1626 * @return int the ID
1628 public function getArticleID( $flags = 0 ) {
1629 $linkCache =& LinkCache
::singleton();
1630 if ( $flags & GAID_FOR_UPDATE
) {
1631 $oldUpdate = $linkCache->forUpdate( true );
1632 $this->mArticleID
= $linkCache->addLinkObj( $this );
1633 $linkCache->forUpdate( $oldUpdate );
1635 if ( -1 == $this->mArticleID
) {
1636 $this->mArticleID
= $linkCache->addLinkObj( $this );
1639 return $this->mArticleID
;
1642 public function getLatestRevID() {
1643 if ($this->mLatestID
!== false)
1644 return $this->mLatestID
;
1646 $db = wfGetDB(DB_SLAVE
);
1647 return $this->mLatestID
= $db->selectField( 'revision',
1649 array('rev_page' => $this->getArticleID()),
1650 'Title::getLatestRevID' );
1654 * This clears some fields in this object, and clears any associated
1655 * keys in the "bad links" section of the link cache.
1657 * - This is called from Article::insertNewArticle() to allow
1658 * loading of the new page_id. It's also called from
1659 * Article::doDeleteArticle()
1661 * @param int $newid the new Article ID
1663 public function resetArticleID( $newid ) {
1664 $linkCache =& LinkCache
::singleton();
1665 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1667 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1668 else { $this->mArticleID
= $newid; }
1669 $this->mRestrictionsLoaded
= false;
1670 $this->mRestrictions
= array();
1674 * Updates page_touched for this page; called from LinksUpdate.php
1675 * @return bool true if the update succeded
1677 public function invalidateCache() {
1678 global $wgUseFileCache;
1680 if ( wfReadOnly() ) {
1684 $dbw = wfGetDB( DB_MASTER
);
1685 $success = $dbw->update( 'page',
1687 'page_touched' => $dbw->timestamp()
1688 ), array( /* WHERE */
1689 'page_namespace' => $this->getNamespace() ,
1690 'page_title' => $this->getDBkey()
1691 ), 'Title::invalidateCache'
1694 if ($wgUseFileCache) {
1695 $cache = new HTMLFileCache($this);
1696 @unlink
($cache->fileCacheName());
1703 * Prefix some arbitrary text with the namespace or interwiki prefix
1706 * @param string $name the text
1707 * @return string the prefixed text
1710 /* private */ function prefix( $name ) {
1712 if ( '' != $this->mInterwiki
) {
1713 $p = $this->mInterwiki
. ':';
1715 if ( 0 != $this->mNamespace
) {
1716 $p .= $this->getNsText() . ':';
1722 * Secure and split - main initialisation function for this object
1724 * Assumes that mDbkeyform has been set, and is urldecoded
1725 * and uses underscores, but not otherwise munged. This function
1726 * removes illegal characters, splits off the interwiki and
1727 * namespace prefixes, sets the other forms, and canonicalizes
1729 * @return bool true on success
1731 private function secureAndSplit() {
1732 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1735 static $rxTc = false;
1737 # % is needed as well
1738 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1741 $this->mInterwiki
= $this->mFragment
= '';
1742 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1744 $dbkey = $this->mDbkeyform
;
1746 # Strip Unicode bidi override characters.
1747 # Sometimes they slip into cut-n-pasted page titles, where the
1748 # override chars get included in list displays.
1749 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1750 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1752 # Clean up whitespace
1754 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1755 $dbkey = trim( $dbkey, '_' );
1757 if ( '' == $dbkey ) {
1761 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1762 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1766 $this->mDbkeyform
= $dbkey;
1768 # Initial colon indicates main namespace rather than specified default
1769 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1770 if ( ':' == $dbkey{0} ) {
1771 $this->mNamespace
= NS_MAIN
;
1772 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1773 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1776 # Namespace or interwiki prefix
1780 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1782 if ( $ns = $wgContLang->getNsIndex( $p )) {
1783 # Ordinary namespace
1785 $this->mNamespace
= $ns;
1786 } elseif( $this->getInterwikiLink( $p ) ) {
1788 # Can't make a local interwiki link to an interwiki link.
1789 # That's just crazy!
1795 $this->mInterwiki
= $wgContLang->lc( $p );
1797 # Redundant interwiki prefix to the local wiki
1798 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1799 if( $dbkey == '' ) {
1800 # Can't have an empty self-link
1803 $this->mInterwiki
= '';
1805 # Do another namespace split...
1809 # If there's an initial colon after the interwiki, that also
1810 # resets the default namespace
1811 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1812 $this->mNamespace
= NS_MAIN
;
1813 $dbkey = substr( $dbkey, 1 );
1816 # If there's no recognized interwiki or namespace,
1817 # then let the colon expression be part of the title.
1822 # We already know that some pages won't be in the database!
1824 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1825 $this->mArticleID
= 0;
1827 $fragment = strstr( $dbkey, '#' );
1828 if ( false !== $fragment ) {
1829 $this->setFragment( $fragment );
1830 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1831 # remove whitespace again: prevents "Foo_bar_#"
1832 # becoming "Foo_bar_"
1833 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1836 # Reject illegal characters.
1838 if( preg_match( $rxTc, $dbkey ) ) {
1843 * Pages with "/./" or "/../" appearing in the URLs will
1844 * often be unreachable due to the way web browsers deal
1845 * with 'relative' URLs. Forbid them explicitly.
1847 if ( strpos( $dbkey, '.' ) !== false &&
1848 ( $dbkey === '.' ||
$dbkey === '..' ||
1849 strpos( $dbkey, './' ) === 0 ||
1850 strpos( $dbkey, '../' ) === 0 ||
1851 strpos( $dbkey, '/./' ) !== false ||
1852 strpos( $dbkey, '/../' ) !== false ) )
1858 * Magic tilde sequences? Nu-uh!
1860 if( strpos( $dbkey, '~~~' ) !== false ) {
1865 * Limit the size of titles to 255 bytes.
1866 * This is typically the size of the underlying database field.
1867 * We make an exception for special pages, which don't need to be stored
1868 * in the database, and may edge over 255 bytes due to subpage syntax
1869 * for long titles, e.g. [[Special:Block/Long name]]
1871 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1872 strlen( $dbkey ) > 512 )
1878 * Normally, all wiki links are forced to have
1879 * an initial capital letter so [[foo]] and [[Foo]]
1880 * point to the same place.
1882 * Don't force it for interwikis, since the other
1883 * site might be case-sensitive.
1885 $this->mUserCaseDBKey
= $dbkey;
1886 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1887 $dbkey = $wgContLang->ucfirst( $dbkey );
1891 * Can't make a link to a namespace alone...
1892 * "empty" local links can only be self-links
1893 * with a fragment identifier.
1896 $this->mInterwiki
== '' &&
1897 $this->mNamespace
!= NS_MAIN
) {
1901 // Any remaining initial :s are illegal.
1902 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1907 $this->mDbkeyform
= $dbkey;
1908 $this->mUrlform
= wfUrlencode( $dbkey );
1910 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1916 * Set the fragment for this title
1917 * This is kind of bad, since except for this rarely-used function, Title objects
1918 * are immutable. The reason this is here is because it's better than setting the
1919 * members directly, which is what Linker::formatComment was doing previously.
1921 * @param string $fragment text
1922 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1924 public function setFragment( $fragment ) {
1925 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1929 * Get a Title object associated with the talk page of this article
1930 * @return Title the object for the talk page
1932 public function getTalkPage() {
1933 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1937 * Get a title object associated with the subject page of this
1940 * @return Title the object for the subject page
1942 public function getSubjectPage() {
1943 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1947 * Get an array of Title objects linking to this Title
1948 * Also stores the IDs in the link cache.
1950 * WARNING: do not use this function on arbitrary user-supplied titles!
1951 * On heavily-used templates it will max out the memory.
1953 * @param string $options may be FOR UPDATE
1954 * @return array the Title objects linking here
1956 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1957 $linkCache =& LinkCache
::singleton();
1960 $db = wfGetDB( DB_MASTER
);
1962 $db = wfGetDB( DB_SLAVE
);
1965 $res = $db->select( array( 'page', $table ),
1966 array( 'page_namespace', 'page_title', 'page_id' ),
1968 "{$prefix}_from=page_id",
1969 "{$prefix}_namespace" => $this->getNamespace(),
1970 "{$prefix}_title" => $this->getDbKey() ),
1971 'Title::getLinksTo',
1975 if ( $db->numRows( $res ) ) {
1976 while ( $row = $db->fetchObject( $res ) ) {
1977 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1978 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1979 $retVal[] = $titleObj;
1983 $db->freeResult( $res );
1988 * Get an array of Title objects using this Title as a template
1989 * Also stores the IDs in the link cache.
1991 * WARNING: do not use this function on arbitrary user-supplied titles!
1992 * On heavily-used templates it will max out the memory.
1994 * @param string $options may be FOR UPDATE
1995 * @return array the Title objects linking here
1997 public function getTemplateLinksTo( $options = '' ) {
1998 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2002 * Get an array of Title objects referring to non-existent articles linked from this page
2004 * @param string $options may be FOR UPDATE
2005 * @return array the Title objects
2007 public function getBrokenLinksFrom( $options = '' ) {
2009 $db = wfGetDB( DB_MASTER
);
2011 $db = wfGetDB( DB_SLAVE
);
2014 $res = $db->safeQuery(
2015 "SELECT pl_namespace, pl_title
2018 ON pl_namespace=page_namespace
2019 AND pl_title=page_title
2021 AND page_namespace IS NULL
2023 $db->tableName( 'pagelinks' ),
2024 $db->tableName( 'page' ),
2025 $this->getArticleId(),
2029 if ( $db->numRows( $res ) ) {
2030 while ( $row = $db->fetchObject( $res ) ) {
2031 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2034 $db->freeResult( $res );
2040 * Get a list of URLs to purge from the Squid cache when this
2043 * @return array the URLs
2045 public function getSquidURLs() {
2049 $this->getInternalURL(),
2050 $this->getInternalURL( 'action=history' )
2053 // purge variant urls as well
2054 if($wgContLang->hasVariants()){
2055 $variants = $wgContLang->getVariants();
2056 foreach($variants as $vCode){
2057 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2058 $urls[] = $this->getInternalURL('',$vCode);
2065 public function purgeSquid() {
2067 if ( $wgUseSquid ) {
2068 $urls = $this->getSquidURLs();
2069 $u = new SquidUpdate( $urls );
2075 * Move this page without authentication
2076 * @param Title &$nt the new page Title
2078 public function moveNoAuth( &$nt ) {
2079 return $this->moveTo( $nt, false );
2083 * Check whether a given move operation would be valid.
2084 * Returns true if ok, or a message key string for an error message
2085 * if invalid. (Scarrrrry ugly interface this.)
2086 * @param Title &$nt the new title
2087 * @param bool $auth indicates whether $wgUser's permissions
2089 * @return mixed true on success, message name on failure
2091 public function isValidMoveOperation( &$nt, $auth = true ) {
2092 if( !$this or !$nt ) {
2093 return 'badtitletext';
2095 if( $this->equals( $nt ) ) {
2098 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2099 return 'immobile_namespace';
2102 $oldid = $this->getArticleID();
2103 $newid = $nt->getArticleID();
2105 if ( strlen( $nt->getDBkey() ) < 1 ) {
2106 return 'articleexists';
2108 if ( ( '' == $this->getDBkey() ) ||
2110 ( '' == $nt->getDBkey() ) ) {
2111 return 'badarticleerror';
2115 !$this->userCan( 'edit' ) ||
!$nt->userCan( 'edit' ) ||
2116 !$this->userCan( 'move' ) ||
!$nt->userCan( 'move' ) ) ) {
2117 return 'protectedpage';
2120 # The move is allowed only if (1) the target doesn't exist, or
2121 # (2) the target is a redirect to the source, and has no history
2122 # (so we can undo bad moves right after they're done).
2124 if ( 0 != $newid ) { # Target exists; check for validity
2125 if ( ! $this->isValidMoveTarget( $nt ) ) {
2126 return 'articleexists';
2133 * Move a title to a new location
2134 * @param Title &$nt the new title
2135 * @param bool $auth indicates whether $wgUser's permissions
2137 * @return mixed true on success, message name on failure
2139 public function moveTo( &$nt, $auth = true, $reason = '' ) {
2140 $err = $this->isValidMoveOperation( $nt, $auth );
2141 if( is_string( $err ) ) {
2145 $pageid = $this->getArticleID();
2146 if( $nt->exists() ) {
2147 $this->moveOverExistingRedirect( $nt, $reason );
2148 $pageCountChange = 0;
2149 } else { # Target didn't exist, do normal move.
2150 $this->moveToNewTitle( $nt, $reason );
2151 $pageCountChange = 1;
2153 $redirid = $this->getArticleID();
2155 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2156 $dbw = wfGetDB( DB_MASTER
);
2157 $categorylinks = $dbw->tableName( 'categorylinks' );
2158 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2159 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2160 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2161 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2165 $oldnamespace = $this->getNamespace() & ~
1;
2166 $newnamespace = $nt->getNamespace() & ~
1;
2167 $oldtitle = $this->getDBkey();
2168 $newtitle = $nt->getDBkey();
2170 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2171 WatchedItem
::duplicateEntries( $this, $nt );
2174 # Update search engine
2175 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2177 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2181 if( $this->isContentPage() && !$nt->isContentPage() ) {
2182 # No longer a content page
2183 # Not viewed, edited, removing
2184 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2185 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2186 # Now a content page
2187 # Not viewed, edited, adding
2188 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2189 } elseif( $pageCountChange ) {
2191 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2200 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2205 * Move page to a title which is at present a redirect to the
2208 * @param Title &$nt the page to move to, which should currently
2211 private function moveOverExistingRedirect( &$nt, $reason = '' ) {
2213 $fname = 'Title::moveOverExistingRedirect';
2214 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2217 $comment .= ": $reason";
2220 $now = wfTimestampNow();
2221 $newid = $nt->getArticleID();
2222 $oldid = $this->getArticleID();
2223 $dbw = wfGetDB( DB_MASTER
);
2224 $linkCache =& LinkCache
::singleton();
2226 # Delete the old redirect. We don't save it to history since
2227 # by definition if we've got here it's rather uninteresting.
2228 # We have to remove it so that the next step doesn't trigger
2229 # a conflict on the unique namespace+title index...
2230 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2232 # Save a null revision in the page's history notifying of the move
2233 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2234 $nullRevId = $nullRevision->insertOn( $dbw );
2236 # Change the name of the target page:
2237 $dbw->update( 'page',
2239 'page_touched' => $dbw->timestamp($now),
2240 'page_namespace' => $nt->getNamespace(),
2241 'page_title' => $nt->getDBkey(),
2242 'page_latest' => $nullRevId,
2244 /* WHERE */ array( 'page_id' => $oldid ),
2247 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2249 # Recreate the redirect, this time in the other direction.
2250 $mwRedir = MagicWord
::get( 'redirect' );
2251 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2252 $redirectArticle = new Article( $this );
2253 $newid = $redirectArticle->insertOn( $dbw );
2254 $redirectRevision = new Revision( array(
2256 'comment' => $comment,
2257 'text' => $redirectText ) );
2258 $redirectRevision->insertOn( $dbw );
2259 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2260 $linkCache->clearLink( $this->getPrefixedDBkey() );
2263 $log = new LogPage( 'move' );
2264 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2266 # Now, we record the link from the redirect to the new title.
2267 # It should have no other outgoing links...
2268 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2269 $dbw->insert( 'pagelinks',
2271 'pl_from' => $newid,
2272 'pl_namespace' => $nt->getNamespace(),
2273 'pl_title' => $nt->getDbKey() ),
2277 if ( $wgUseSquid ) {
2278 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2279 $u = new SquidUpdate( $urls );
2285 * Move page to non-existing title.
2286 * @param Title &$nt the new Title
2288 private function moveToNewTitle( &$nt, $reason = '' ) {
2290 $fname = 'MovePageForm::moveToNewTitle';
2291 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2293 $comment .= ": $reason";
2296 $newid = $nt->getArticleID();
2297 $oldid = $this->getArticleID();
2298 $dbw = wfGetDB( DB_MASTER
);
2299 $now = $dbw->timestamp();
2300 $linkCache =& LinkCache
::singleton();
2302 # Save a null revision in the page's history notifying of the move
2303 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2304 $nullRevId = $nullRevision->insertOn( $dbw );
2307 $dbw->update( 'page',
2309 'page_touched' => $now,
2310 'page_namespace' => $nt->getNamespace(),
2311 'page_title' => $nt->getDBkey(),
2312 'page_latest' => $nullRevId,
2314 /* WHERE */ array( 'page_id' => $oldid ),
2318 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2321 $mwRedir = MagicWord
::get( 'redirect' );
2322 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2323 $redirectArticle = new Article( $this );
2324 $newid = $redirectArticle->insertOn( $dbw );
2325 $redirectRevision = new Revision( array(
2327 'comment' => $comment,
2328 'text' => $redirectText ) );
2329 $redirectRevision->insertOn( $dbw );
2330 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2331 $linkCache->clearLink( $this->getPrefixedDBkey() );
2334 $log = new LogPage( 'move' );
2335 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2337 # Purge caches as per article creation
2338 Article
::onArticleCreate( $nt );
2340 # Record the just-created redirect's linking to the page
2341 $dbw->insert( 'pagelinks',
2343 'pl_from' => $newid,
2344 'pl_namespace' => $nt->getNamespace(),
2345 'pl_title' => $nt->getDBkey() ),
2348 # Purge old title from squid
2349 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2350 $this->purgeSquid();
2354 * Checks if $this can be moved to a given Title
2355 * - Selects for update, so don't call it unless you mean business
2357 * @param Title &$nt the new title to check
2359 public function isValidMoveTarget( $nt ) {
2361 $fname = 'Title::isValidMoveTarget';
2362 $dbw = wfGetDB( DB_MASTER
);
2365 $id = $nt->getArticleID();
2366 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2367 array( 'page_is_redirect','old_text','old_flags' ),
2368 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2369 $fname, 'FOR UPDATE' );
2371 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2373 wfDebug( __METHOD__
. ": not a redirect\n" );
2376 $text = Revision
::getRevisionText( $obj );
2378 # Does the redirect point to the source?
2379 # Or is it a broken self-redirect, usually caused by namespace collisions?
2381 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2382 $redirTitle = Title
::newFromText( $m[1] );
2383 if( !is_object( $redirTitle ) ||
2384 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2385 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2386 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2391 wfDebug( __METHOD__
. ": failsafe\n" );
2395 # Does the article have a history?
2396 $row = $dbw->selectRow( array( 'page', 'revision'),
2398 array( 'page_namespace' => $nt->getNamespace(),
2399 'page_title' => $nt->getDBkey(),
2400 'page_id=rev_page AND page_latest != rev_id'
2401 ), $fname, 'FOR UPDATE'
2404 # Return true if there was no history
2405 return $row === false;
2409 * Can this title be added to a user's watchlist?
2413 public function isWatchable() {
2414 return !$this->isExternal()
2415 && Namespace::isWatchable( $this->getNamespace() );
2419 * Get categories to which this Title belongs and return an array of
2420 * categories' names.
2422 * @return array an array of parents in the form:
2423 * $parent => $currentarticle
2425 public function getParentCategories() {
2428 $titlekey = $this->getArticleId();
2429 $dbr = wfGetDB( DB_SLAVE
);
2430 $categorylinks = $dbr->tableName( 'categorylinks' );
2433 $sql = "SELECT * FROM $categorylinks"
2434 ." WHERE cl_from='$titlekey'"
2435 ." AND cl_from <> '0'"
2436 ." ORDER BY cl_sortkey";
2438 $res = $dbr->query ( $sql ) ;
2440 if($dbr->numRows($res) > 0) {
2441 while ( $x = $dbr->fetchObject ( $res ) )
2442 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2443 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2444 $dbr->freeResult ( $res ) ;
2452 * Get a tree of parent categories
2453 * @param array $children an array with the children in the keys, to check for circular refs
2456 public function getParentCategoryTree( $children = array() ) {
2457 $parents = $this->getParentCategories();
2459 if($parents != '') {
2460 foreach($parents as $parent => $current) {
2461 if ( array_key_exists( $parent, $children ) ) {
2462 # Circular reference
2463 $stack[$parent] = array();
2465 $nt = Title
::newFromText($parent);
2467 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2479 * Get an associative array for selecting this title from
2484 public function pageCond() {
2485 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2489 * Get the revision ID of the previous revision
2491 * @param integer $revision Revision ID. Get the revision that was before this one.
2492 * @return integer $oldrevision|false
2494 public function getPreviousRevisionID( $revision ) {
2495 $dbr = wfGetDB( DB_SLAVE
);
2496 return $dbr->selectField( 'revision', 'rev_id',
2497 'rev_page=' . intval( $this->getArticleId() ) .
2498 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2502 * Get the revision ID of the next revision
2504 * @param integer $revision Revision ID. Get the revision that was after this one.
2505 * @return integer $oldrevision|false
2507 public function getNextRevisionID( $revision ) {
2508 $dbr = wfGetDB( DB_SLAVE
);
2509 return $dbr->selectField( 'revision', 'rev_id',
2510 'rev_page=' . intval( $this->getArticleId() ) .
2511 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2515 * Get the number of revisions between the given revision IDs.
2517 * @param integer $old Revision ID.
2518 * @param integer $new Revision ID.
2519 * @return integer Number of revisions between these IDs.
2521 public function countRevisionsBetween( $old, $new ) {
2522 $dbr = wfGetDB( DB_SLAVE
);
2523 return $dbr->selectField( 'revision', 'count(*)',
2524 'rev_page = ' . intval( $this->getArticleId() ) .
2525 ' AND rev_id > ' . intval( $old ) .
2526 ' AND rev_id < ' . intval( $new ) );
2530 * Compare with another title.
2532 * @param Title $title
2535 public function equals( $title ) {
2536 // Note: === is necessary for proper matching of number-like titles.
2537 return $this->getInterwiki() === $title->getInterwiki()
2538 && $this->getNamespace() == $title->getNamespace()
2539 && $this->getDbkey() === $title->getDbkey();
2543 * Return a string representation of this title
2547 public function __toString() {
2548 return $this->getPrefixedText();
2552 * Check if page exists
2555 public function exists() {
2556 return $this->getArticleId() != 0;
2560 * Do we know that this title definitely exists, or should we otherwise
2561 * consider that it exists?
2565 public function isAlwaysKnown() {
2566 return $this->isExternal()
2567 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2568 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $this->mDbkeyform
) );
2572 * Update page_touched timestamps and send squid purge messages for
2573 * pages linking to this title. May be sent to the job queue depending
2574 * on the number of links. Typically called on create and delete.
2576 public function touchLinks() {
2577 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2580 if ( $this->getNamespace() == NS_CATEGORY
) {
2581 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2587 * Get the last touched timestamp
2589 public function getTouched() {
2590 $dbr = wfGetDB( DB_SLAVE
);
2591 $touched = $dbr->selectField( 'page', 'page_touched',
2593 'page_namespace' => $this->getNamespace(),
2594 'page_title' => $this->getDBkey()
2600 public function trackbackURL() {
2601 global $wgTitle, $wgScriptPath, $wgServer;
2603 return "$wgServer$wgScriptPath/trackback.php?article="
2604 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2607 public function trackbackRDF() {
2608 $url = htmlspecialchars($this->getFullURL());
2609 $title = htmlspecialchars($this->getText());
2610 $tburl = $this->trackbackURL();
2613 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2614 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2615 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2618 dc:identifier=\"$url\"
2620 trackback:ping=\"$tburl\" />
2625 * Generate strings used for xml 'id' names in monobook tabs
2628 public function getNamespaceKey() {
2630 switch ($this->getNamespace()) {
2633 return 'nstab-main';
2636 return 'nstab-user';
2638 return 'nstab-media';
2640 return 'nstab-special';
2642 case NS_PROJECT_TALK
:
2643 return 'nstab-project';
2646 return 'nstab-image';
2648 case NS_MEDIAWIKI_TALK
:
2649 return 'nstab-mediawiki';
2651 case NS_TEMPLATE_TALK
:
2652 return 'nstab-template';
2655 return 'nstab-help';
2657 case NS_CATEGORY_TALK
:
2658 return 'nstab-category';
2660 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2665 * Returns true if this title resolves to the named special page
2666 * @param string $name The special page name
2668 public function isSpecial( $name ) {
2669 if ( $this->getNamespace() == NS_SPECIAL
) {
2670 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2671 if ( $name == $thisName ) {
2679 * If the Title refers to a special page alias which is not the local default,
2680 * returns a new Title which points to the local default. Otherwise, returns $this.
2682 public function fixSpecialName() {
2683 if ( $this->getNamespace() == NS_SPECIAL
) {
2684 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2685 if ( $canonicalName ) {
2686 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2687 if ( $localName != $this->mDbkeyform
) {
2688 return Title
::makeTitle( NS_SPECIAL
, $localName );
2696 * Is this Title in a namespace which contains content?
2697 * In other words, is this a content page, for the purposes of calculating
2702 public function isContentPage() {
2703 return Namespace::isContent( $this->getNamespace() );