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');
1163 if( $action == 'move' &&
1164 !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1165 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1166 } else if ( !$user->isAllowed( $action ) ) {
1169 global $wgGroupPermissions;
1170 foreach( $wgGroupPermissions as $key => $value ) {
1171 if( isset( $value[$permission] ) && $value[$permission] == true ) {
1172 $groupName = User
::getGroupName( $key );
1173 $groupPage = User
::getGroupPage( $key );
1175 $skin = $user->getSkin();
1176 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1178 $groups[] = $groupName;
1182 $n = count( $groups );
1183 $groups = implode( ', ', $groups );
1188 $return = array( "badaccess-group$n", $groups );
1191 $return = array( 'badaccess-groups', $groups );
1193 $errors[] = $return;
1196 wfProfileOut( $fname );
1201 * Can $wgUser edit this page?
1203 * @deprecated use userCan('edit')
1205 public function userCanEdit( $doExpensiveQueries = true ) {
1206 return $this->userCan( 'edit', $doExpensiveQueries );
1210 * Can $wgUser create this page?
1212 * @deprecated use userCan('create')
1214 public function userCanCreate( $doExpensiveQueries = true ) {
1215 return $this->userCan( 'create', $doExpensiveQueries );
1219 * Can $wgUser move this page?
1221 * @deprecated use userCan('move')
1223 public function userCanMove( $doExpensiveQueries = true ) {
1224 return $this->userCan( 'move', $doExpensiveQueries );
1228 * Would anybody with sufficient privileges be able to move this page?
1229 * Some pages just aren't movable.
1233 public function isMovable() {
1234 return Namespace::isMovable( $this->getNamespace() )
1235 && $this->getInterwiki() == '';
1239 * Can $wgUser read this page?
1241 * @todo fold these checks into userCan()
1243 public function userCanRead() {
1247 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1248 if ( $result !== null ) {
1252 if( $wgUser->isAllowed( 'read' ) ) {
1255 global $wgWhitelistRead;
1258 * Always grant access to the login page.
1259 * Even anons need to be able to log in.
1261 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1266 * Check for explicit whitelisting
1268 $name = $this->getPrefixedText();
1269 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead, true ) )
1273 * Old settings might have the title prefixed with
1274 * a colon for main-namespace pages
1276 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1277 if( in_array( ':' . $name, $wgWhitelistRead ) )
1282 * If it's a special page, ditch the subpage bit
1285 if( $this->getNamespace() == NS_SPECIAL
) {
1286 $name = $this->getText();
1287 list( $name, $subpage ) = SpecialPage
::resolveAliasWithSubpage( $name );
1288 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1289 if( in_array( $pure, $wgWhitelistRead, true ) )
1298 * Is this a talk page of some sort?
1301 public function isTalkPage() {
1302 return Namespace::isTalk( $this->getNamespace() );
1306 * Is this a subpage?
1309 public function isSubpage() {
1310 global $wgNamespacesWithSubpages;
1312 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1313 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1320 * Could this page contain custom CSS or JavaScript, based
1325 public function isCssOrJsPage() {
1326 return $this->mNamespace
== NS_MEDIAWIKI
1327 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1331 * Is this a .css or .js subpage of a user page?
1334 public function isCssJsSubpage() {
1335 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1338 * Is this a *valid* .css or .js subpage of a user page?
1339 * Check that the corresponding skin exists
1341 public function isValidCssJsSubpage() {
1342 if ( $this->isCssJsSubpage() ) {
1343 $skinNames = Skin
::getSkinNames();
1344 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1350 * Trim down a .css or .js subpage title to get the corresponding skin name
1352 public function getSkinFromCssJsSubpage() {
1353 $subpage = explode( '/', $this->mTextform
);
1354 $subpage = $subpage[ count( $subpage ) - 1 ];
1355 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1358 * Is this a .css subpage of a user page?
1361 public function isCssSubpage() {
1362 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1365 * Is this a .js subpage of a user page?
1368 public function isJsSubpage() {
1369 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1372 * Protect css/js subpages of user pages: can $wgUser edit
1376 * @todo XXX: this might be better using restrictions
1378 public function userCanEditCssJsSubpage() {
1380 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1384 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1386 * @return bool If the page is subject to cascading restrictions.
1388 public function isCascadeProtected() {
1389 list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false );
1390 return ( $sources > 0 );
1394 * Cascading protection: Get the source of any cascading restrictions on this page.
1396 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1397 * @return array( mixed title array, restriction array)
1398 * 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.
1399 * The restriction array is an array of each type, each of which contains an array of unique groups
1401 public function getCascadeProtectionSources( $get_pages = true ) {
1402 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1404 # Define our dimension of restrictions types
1405 $pagerestrictions = array();
1406 foreach( $wgRestrictionTypes as $action )
1407 $pagerestrictions[$action] = array();
1409 if (!$wgEnableCascadingProtection)
1410 return array( false, $pagerestrictions );
1412 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1413 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1414 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1415 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1418 wfProfileIn( __METHOD__
);
1420 $dbr = wfGetDb( DB_SLAVE
);
1422 if ( $this->getNamespace() == NS_IMAGE
) {
1423 $tables = array ('imagelinks', 'page_restrictions');
1424 $where_clauses = array(
1425 'il_to' => $this->getDBkey(),
1427 'pr_cascade' => 1 );
1429 $tables = array ('templatelinks', 'page_restrictions');
1430 $where_clauses = array(
1431 'tl_namespace' => $this->getNamespace(),
1432 'tl_title' => $this->getDBkey(),
1434 'pr_cascade' => 1 );
1438 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1439 $where_clauses[] = 'page_id=pr_page';
1442 $cols = array( 'pr_expiry' );
1445 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1447 $sources = $get_pages ?
array() : false;
1448 $now = wfTimestampNow();
1449 $purgeExpired = false;
1451 while( $row = $dbr->fetchObject( $res ) ) {
1452 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1453 if( $expiry > $now ) {
1455 $page_id = $row->pr_page
;
1456 $page_ns = $row->page_namespace
;
1457 $page_title = $row->page_title
;
1458 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1459 # Add groups needed for each restriction type if its not already there
1460 # Make sure this restriction type still exists
1461 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1462 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1468 // Trigger lazy purge of expired restrictions from the db
1469 $purgeExpired = true;
1472 if( $purgeExpired ) {
1473 Title
::purgeExpiredRestrictions();
1476 wfProfileOut( __METHOD__
);
1479 $this->mCascadeSources
= $sources;
1480 $this->mCascadingRestrictions
= $pagerestrictions;
1482 $this->mHasCascadingRestrictions
= $sources;
1485 return array( $sources, $pagerestrictions );
1488 function areRestrictionsCascading() {
1489 if (!$this->mRestrictionsLoaded
) {
1490 $this->loadRestrictions();
1493 return $this->mCascadeRestriction
;
1497 * Loads a string into mRestrictions array
1498 * @param resource $res restrictions as an SQL result.
1500 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1501 $dbr = wfGetDb( DB_SLAVE
);
1503 $this->mRestrictions
['edit'] = array();
1504 $this->mRestrictions
['move'] = array();
1506 # Backwards-compatibility: also load the restrictions from the page record (old format).
1508 if ( $oldFashionedRestrictions == NULL ) {
1509 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1512 if ($oldFashionedRestrictions != '') {
1514 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1515 $temp = explode( '=', trim( $restrict ) );
1516 if(count($temp) == 1) {
1517 // old old format should be treated as edit/move restriction
1518 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1519 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1521 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1525 $this->mOldRestrictions
= true;
1526 $this->mCascadeRestriction
= false;
1527 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1531 if( $dbr->numRows( $res ) ) {
1532 # Current system - load second to make them override.
1533 $now = wfTimestampNow();
1534 $purgeExpired = false;
1536 while ($row = $dbr->fetchObject( $res ) ) {
1537 # Cycle through all the restrictions.
1539 // This code should be refactored, now that it's being used more generally,
1540 // But I don't really see any harm in leaving it in Block for now -werdna
1541 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1543 // Only apply the restrictions if they haven't expired!
1544 if ( !$expiry ||
$expiry > $now ) {
1545 $this->mRestrictionsExpiry
= $expiry;
1546 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1548 $this->mCascadeRestriction |
= $row->pr_cascade
;
1550 // Trigger a lazy purge of expired restrictions
1551 $purgeExpired = true;
1555 if( $purgeExpired ) {
1556 Title
::purgeExpiredRestrictions();
1560 $this->mRestrictionsLoaded
= true;
1563 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1564 if( !$this->mRestrictionsLoaded
) {
1565 $dbr = wfGetDB( DB_SLAVE
);
1567 $res = $dbr->select( 'page_restrictions', '*',
1568 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1570 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1575 * Purge expired restrictions from the page_restrictions table
1577 static function purgeExpiredRestrictions() {
1578 $dbw = wfGetDB( DB_MASTER
);
1579 $dbw->delete( 'page_restrictions',
1580 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1585 * Accessor/initialisation for mRestrictions
1587 * @param string $action action that permission needs to be checked for
1588 * @return array the array of groups allowed to edit this article
1590 public function getRestrictions( $action ) {
1591 if( $this->exists() ) {
1592 if( !$this->mRestrictionsLoaded
) {
1593 $this->loadRestrictions();
1595 return isset( $this->mRestrictions
[$action] )
1596 ?
$this->mRestrictions
[$action]
1604 * Is there a version of this page in the deletion archive?
1605 * @return int the number of archived revisions
1607 public function isDeleted() {
1608 $fname = 'Title::isDeleted';
1609 if ( $this->getNamespace() < 0 ) {
1612 $dbr = wfGetDB( DB_SLAVE
);
1613 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1614 'ar_title' => $this->getDBkey() ), $fname );
1615 if( $this->getNamespace() == NS_IMAGE
) {
1616 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1617 array( 'fa_name' => $this->getDBkey() ), $fname );
1624 * Get the article ID for this Title from the link cache,
1625 * adding it if necessary
1626 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1628 * @return int the ID
1630 public function getArticleID( $flags = 0 ) {
1631 $linkCache =& LinkCache
::singleton();
1632 if ( $flags & GAID_FOR_UPDATE
) {
1633 $oldUpdate = $linkCache->forUpdate( true );
1634 $this->mArticleID
= $linkCache->addLinkObj( $this );
1635 $linkCache->forUpdate( $oldUpdate );
1637 if ( -1 == $this->mArticleID
) {
1638 $this->mArticleID
= $linkCache->addLinkObj( $this );
1641 return $this->mArticleID
;
1644 public function getLatestRevID() {
1645 if ($this->mLatestID
!== false)
1646 return $this->mLatestID
;
1648 $db = wfGetDB(DB_SLAVE
);
1649 return $this->mLatestID
= $db->selectField( 'revision',
1651 array('rev_page' => $this->getArticleID()),
1652 'Title::getLatestRevID' );
1656 * This clears some fields in this object, and clears any associated
1657 * keys in the "bad links" section of the link cache.
1659 * - This is called from Article::insertNewArticle() to allow
1660 * loading of the new page_id. It's also called from
1661 * Article::doDeleteArticle()
1663 * @param int $newid the new Article ID
1665 public function resetArticleID( $newid ) {
1666 $linkCache =& LinkCache
::singleton();
1667 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1669 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1670 else { $this->mArticleID
= $newid; }
1671 $this->mRestrictionsLoaded
= false;
1672 $this->mRestrictions
= array();
1676 * Updates page_touched for this page; called from LinksUpdate.php
1677 * @return bool true if the update succeded
1679 public function invalidateCache() {
1680 global $wgUseFileCache;
1682 if ( wfReadOnly() ) {
1686 $dbw = wfGetDB( DB_MASTER
);
1687 $success = $dbw->update( 'page',
1689 'page_touched' => $dbw->timestamp()
1690 ), array( /* WHERE */
1691 'page_namespace' => $this->getNamespace() ,
1692 'page_title' => $this->getDBkey()
1693 ), 'Title::invalidateCache'
1696 if ($wgUseFileCache) {
1697 $cache = new HTMLFileCache($this);
1698 @unlink
($cache->fileCacheName());
1705 * Prefix some arbitrary text with the namespace or interwiki prefix
1708 * @param string $name the text
1709 * @return string the prefixed text
1712 /* private */ function prefix( $name ) {
1714 if ( '' != $this->mInterwiki
) {
1715 $p = $this->mInterwiki
. ':';
1717 if ( 0 != $this->mNamespace
) {
1718 $p .= $this->getNsText() . ':';
1724 * Secure and split - main initialisation function for this object
1726 * Assumes that mDbkeyform has been set, and is urldecoded
1727 * and uses underscores, but not otherwise munged. This function
1728 * removes illegal characters, splits off the interwiki and
1729 * namespace prefixes, sets the other forms, and canonicalizes
1731 * @return bool true on success
1733 private function secureAndSplit() {
1734 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1737 static $rxTc = false;
1739 # % is needed as well
1740 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1743 $this->mInterwiki
= $this->mFragment
= '';
1744 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1746 $dbkey = $this->mDbkeyform
;
1748 # Strip Unicode bidi override characters.
1749 # Sometimes they slip into cut-n-pasted page titles, where the
1750 # override chars get included in list displays.
1751 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1752 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1754 # Clean up whitespace
1756 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1757 $dbkey = trim( $dbkey, '_' );
1759 if ( '' == $dbkey ) {
1763 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1764 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1768 $this->mDbkeyform
= $dbkey;
1770 # Initial colon indicates main namespace rather than specified default
1771 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1772 if ( ':' == $dbkey{0} ) {
1773 $this->mNamespace
= NS_MAIN
;
1774 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1775 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1778 # Namespace or interwiki prefix
1782 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1784 if ( $ns = $wgContLang->getNsIndex( $p )) {
1785 # Ordinary namespace
1787 $this->mNamespace
= $ns;
1788 } elseif( $this->getInterwikiLink( $p ) ) {
1790 # Can't make a local interwiki link to an interwiki link.
1791 # That's just crazy!
1797 $this->mInterwiki
= $wgContLang->lc( $p );
1799 # Redundant interwiki prefix to the local wiki
1800 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1801 if( $dbkey == '' ) {
1802 # Can't have an empty self-link
1805 $this->mInterwiki
= '';
1807 # Do another namespace split...
1811 # If there's an initial colon after the interwiki, that also
1812 # resets the default namespace
1813 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1814 $this->mNamespace
= NS_MAIN
;
1815 $dbkey = substr( $dbkey, 1 );
1818 # If there's no recognized interwiki or namespace,
1819 # then let the colon expression be part of the title.
1824 # We already know that some pages won't be in the database!
1826 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1827 $this->mArticleID
= 0;
1829 $fragment = strstr( $dbkey, '#' );
1830 if ( false !== $fragment ) {
1831 $this->setFragment( $fragment );
1832 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1833 # remove whitespace again: prevents "Foo_bar_#"
1834 # becoming "Foo_bar_"
1835 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1838 # Reject illegal characters.
1840 if( preg_match( $rxTc, $dbkey ) ) {
1845 * Pages with "/./" or "/../" appearing in the URLs will
1846 * often be unreachable due to the way web browsers deal
1847 * with 'relative' URLs. Forbid them explicitly.
1849 if ( strpos( $dbkey, '.' ) !== false &&
1850 ( $dbkey === '.' ||
$dbkey === '..' ||
1851 strpos( $dbkey, './' ) === 0 ||
1852 strpos( $dbkey, '../' ) === 0 ||
1853 strpos( $dbkey, '/./' ) !== false ||
1854 strpos( $dbkey, '/../' ) !== false ) )
1860 * Magic tilde sequences? Nu-uh!
1862 if( strpos( $dbkey, '~~~' ) !== false ) {
1867 * Limit the size of titles to 255 bytes.
1868 * This is typically the size of the underlying database field.
1869 * We make an exception for special pages, which don't need to be stored
1870 * in the database, and may edge over 255 bytes due to subpage syntax
1871 * for long titles, e.g. [[Special:Block/Long name]]
1873 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1874 strlen( $dbkey ) > 512 )
1880 * Normally, all wiki links are forced to have
1881 * an initial capital letter so [[foo]] and [[Foo]]
1882 * point to the same place.
1884 * Don't force it for interwikis, since the other
1885 * site might be case-sensitive.
1887 $this->mUserCaseDBKey
= $dbkey;
1888 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1889 $dbkey = $wgContLang->ucfirst( $dbkey );
1893 * Can't make a link to a namespace alone...
1894 * "empty" local links can only be self-links
1895 * with a fragment identifier.
1898 $this->mInterwiki
== '' &&
1899 $this->mNamespace
!= NS_MAIN
) {
1903 // Any remaining initial :s are illegal.
1904 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1909 $this->mDbkeyform
= $dbkey;
1910 $this->mUrlform
= wfUrlencode( $dbkey );
1912 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1918 * Set the fragment for this title
1919 * This is kind of bad, since except for this rarely-used function, Title objects
1920 * are immutable. The reason this is here is because it's better than setting the
1921 * members directly, which is what Linker::formatComment was doing previously.
1923 * @param string $fragment text
1924 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1926 public function setFragment( $fragment ) {
1927 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1931 * Get a Title object associated with the talk page of this article
1932 * @return Title the object for the talk page
1934 public function getTalkPage() {
1935 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1939 * Get a title object associated with the subject page of this
1942 * @return Title the object for the subject page
1944 public function getSubjectPage() {
1945 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1949 * Get an array of Title objects linking to this Title
1950 * Also stores the IDs in the link cache.
1952 * WARNING: do not use this function on arbitrary user-supplied titles!
1953 * On heavily-used templates it will max out the memory.
1955 * @param string $options may be FOR UPDATE
1956 * @return array the Title objects linking here
1958 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1959 $linkCache =& LinkCache
::singleton();
1962 $db = wfGetDB( DB_MASTER
);
1964 $db = wfGetDB( DB_SLAVE
);
1967 $res = $db->select( array( 'page', $table ),
1968 array( 'page_namespace', 'page_title', 'page_id' ),
1970 "{$prefix}_from=page_id",
1971 "{$prefix}_namespace" => $this->getNamespace(),
1972 "{$prefix}_title" => $this->getDbKey() ),
1973 'Title::getLinksTo',
1977 if ( $db->numRows( $res ) ) {
1978 while ( $row = $db->fetchObject( $res ) ) {
1979 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1980 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1981 $retVal[] = $titleObj;
1985 $db->freeResult( $res );
1990 * Get an array of Title objects using this Title as a template
1991 * Also stores the IDs in the link cache.
1993 * WARNING: do not use this function on arbitrary user-supplied titles!
1994 * On heavily-used templates it will max out the memory.
1996 * @param string $options may be FOR UPDATE
1997 * @return array the Title objects linking here
1999 public function getTemplateLinksTo( $options = '' ) {
2000 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2004 * Get an array of Title objects referring to non-existent articles linked from this page
2006 * @param string $options may be FOR UPDATE
2007 * @return array the Title objects
2009 public function getBrokenLinksFrom( $options = '' ) {
2011 $db = wfGetDB( DB_MASTER
);
2013 $db = wfGetDB( DB_SLAVE
);
2016 $res = $db->safeQuery(
2017 "SELECT pl_namespace, pl_title
2020 ON pl_namespace=page_namespace
2021 AND pl_title=page_title
2023 AND page_namespace IS NULL
2025 $db->tableName( 'pagelinks' ),
2026 $db->tableName( 'page' ),
2027 $this->getArticleId(),
2031 if ( $db->numRows( $res ) ) {
2032 while ( $row = $db->fetchObject( $res ) ) {
2033 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2036 $db->freeResult( $res );
2042 * Get a list of URLs to purge from the Squid cache when this
2045 * @return array the URLs
2047 public function getSquidURLs() {
2051 $this->getInternalURL(),
2052 $this->getInternalURL( 'action=history' )
2055 // purge variant urls as well
2056 if($wgContLang->hasVariants()){
2057 $variants = $wgContLang->getVariants();
2058 foreach($variants as $vCode){
2059 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2060 $urls[] = $this->getInternalURL('',$vCode);
2067 public function purgeSquid() {
2069 if ( $wgUseSquid ) {
2070 $urls = $this->getSquidURLs();
2071 $u = new SquidUpdate( $urls );
2077 * Move this page without authentication
2078 * @param Title &$nt the new page Title
2080 public function moveNoAuth( &$nt ) {
2081 return $this->moveTo( $nt, false );
2085 * Check whether a given move operation would be valid.
2086 * Returns true if ok, or a message key string for an error message
2087 * if invalid. (Scarrrrry ugly interface this.)
2088 * @param Title &$nt the new title
2089 * @param bool $auth indicates whether $wgUser's permissions
2091 * @return mixed true on success, message name on failure
2093 public function isValidMoveOperation( &$nt, $auth = true ) {
2094 if( !$this or !$nt ) {
2095 return 'badtitletext';
2097 if( $this->equals( $nt ) ) {
2100 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2101 return 'immobile_namespace';
2104 $oldid = $this->getArticleID();
2105 $newid = $nt->getArticleID();
2107 if ( strlen( $nt->getDBkey() ) < 1 ) {
2108 return 'articleexists';
2110 if ( ( '' == $this->getDBkey() ) ||
2112 ( '' == $nt->getDBkey() ) ) {
2113 return 'badarticleerror';
2117 !$this->userCan( 'edit' ) ||
!$nt->userCan( 'edit' ) ||
2118 !$this->userCan( 'move' ) ||
!$nt->userCan( 'move' ) ) ) {
2119 return 'protectedpage';
2122 # The move is allowed only if (1) the target doesn't exist, or
2123 # (2) the target is a redirect to the source, and has no history
2124 # (so we can undo bad moves right after they're done).
2126 if ( 0 != $newid ) { # Target exists; check for validity
2127 if ( ! $this->isValidMoveTarget( $nt ) ) {
2128 return 'articleexists';
2135 * Move a title to a new location
2136 * @param Title &$nt the new title
2137 * @param bool $auth indicates whether $wgUser's permissions
2139 * @return mixed true on success, message name on failure
2141 public function moveTo( &$nt, $auth = true, $reason = '' ) {
2142 $err = $this->isValidMoveOperation( $nt, $auth );
2143 if( is_string( $err ) ) {
2147 $pageid = $this->getArticleID();
2148 if( $nt->exists() ) {
2149 $this->moveOverExistingRedirect( $nt, $reason );
2150 $pageCountChange = 0;
2151 } else { # Target didn't exist, do normal move.
2152 $this->moveToNewTitle( $nt, $reason );
2153 $pageCountChange = 1;
2155 $redirid = $this->getArticleID();
2157 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2158 $dbw = wfGetDB( DB_MASTER
);
2159 $categorylinks = $dbw->tableName( 'categorylinks' );
2160 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2161 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2162 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2163 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2167 $oldnamespace = $this->getNamespace() & ~
1;
2168 $newnamespace = $nt->getNamespace() & ~
1;
2169 $oldtitle = $this->getDBkey();
2170 $newtitle = $nt->getDBkey();
2172 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2173 WatchedItem
::duplicateEntries( $this, $nt );
2176 # Update search engine
2177 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2179 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2183 if( $this->isContentPage() && !$nt->isContentPage() ) {
2184 # No longer a content page
2185 # Not viewed, edited, removing
2186 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2187 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2188 # Now a content page
2189 # Not viewed, edited, adding
2190 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2191 } elseif( $pageCountChange ) {
2193 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2202 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2207 * Move page to a title which is at present a redirect to the
2210 * @param Title &$nt the page to move to, which should currently
2213 private function moveOverExistingRedirect( &$nt, $reason = '' ) {
2215 $fname = 'Title::moveOverExistingRedirect';
2216 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2219 $comment .= ": $reason";
2222 $now = wfTimestampNow();
2223 $newid = $nt->getArticleID();
2224 $oldid = $this->getArticleID();
2225 $dbw = wfGetDB( DB_MASTER
);
2226 $linkCache =& LinkCache
::singleton();
2228 # Delete the old redirect. We don't save it to history since
2229 # by definition if we've got here it's rather uninteresting.
2230 # We have to remove it so that the next step doesn't trigger
2231 # a conflict on the unique namespace+title index...
2232 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2234 # Save a null revision in the page's history notifying of the move
2235 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2236 $nullRevId = $nullRevision->insertOn( $dbw );
2238 # Change the name of the target page:
2239 $dbw->update( 'page',
2241 'page_touched' => $dbw->timestamp($now),
2242 'page_namespace' => $nt->getNamespace(),
2243 'page_title' => $nt->getDBkey(),
2244 'page_latest' => $nullRevId,
2246 /* WHERE */ array( 'page_id' => $oldid ),
2249 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2251 # Recreate the redirect, this time in the other direction.
2252 $mwRedir = MagicWord
::get( 'redirect' );
2253 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2254 $redirectArticle = new Article( $this );
2255 $newid = $redirectArticle->insertOn( $dbw );
2256 $redirectRevision = new Revision( array(
2258 'comment' => $comment,
2259 'text' => $redirectText ) );
2260 $redirectRevision->insertOn( $dbw );
2261 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2262 $linkCache->clearLink( $this->getPrefixedDBkey() );
2265 $log = new LogPage( 'move' );
2266 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2268 # Now, we record the link from the redirect to the new title.
2269 # It should have no other outgoing links...
2270 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2271 $dbw->insert( 'pagelinks',
2273 'pl_from' => $newid,
2274 'pl_namespace' => $nt->getNamespace(),
2275 'pl_title' => $nt->getDbKey() ),
2279 if ( $wgUseSquid ) {
2280 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2281 $u = new SquidUpdate( $urls );
2287 * Move page to non-existing title.
2288 * @param Title &$nt the new Title
2290 private function moveToNewTitle( &$nt, $reason = '' ) {
2292 $fname = 'MovePageForm::moveToNewTitle';
2293 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2295 $comment .= ": $reason";
2298 $newid = $nt->getArticleID();
2299 $oldid = $this->getArticleID();
2300 $dbw = wfGetDB( DB_MASTER
);
2301 $now = $dbw->timestamp();
2302 $linkCache =& LinkCache
::singleton();
2304 # Save a null revision in the page's history notifying of the move
2305 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2306 $nullRevId = $nullRevision->insertOn( $dbw );
2309 $dbw->update( 'page',
2311 'page_touched' => $now,
2312 'page_namespace' => $nt->getNamespace(),
2313 'page_title' => $nt->getDBkey(),
2314 'page_latest' => $nullRevId,
2316 /* WHERE */ array( 'page_id' => $oldid ),
2320 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2323 $mwRedir = MagicWord
::get( 'redirect' );
2324 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2325 $redirectArticle = new Article( $this );
2326 $newid = $redirectArticle->insertOn( $dbw );
2327 $redirectRevision = new Revision( array(
2329 'comment' => $comment,
2330 'text' => $redirectText ) );
2331 $redirectRevision->insertOn( $dbw );
2332 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2333 $linkCache->clearLink( $this->getPrefixedDBkey() );
2336 $log = new LogPage( 'move' );
2337 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2339 # Purge caches as per article creation
2340 Article
::onArticleCreate( $nt );
2342 # Record the just-created redirect's linking to the page
2343 $dbw->insert( 'pagelinks',
2345 'pl_from' => $newid,
2346 'pl_namespace' => $nt->getNamespace(),
2347 'pl_title' => $nt->getDBkey() ),
2350 # Purge old title from squid
2351 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2352 $this->purgeSquid();
2356 * Checks if $this can be moved to a given Title
2357 * - Selects for update, so don't call it unless you mean business
2359 * @param Title &$nt the new title to check
2361 public function isValidMoveTarget( $nt ) {
2363 $fname = 'Title::isValidMoveTarget';
2364 $dbw = wfGetDB( DB_MASTER
);
2367 $id = $nt->getArticleID();
2368 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2369 array( 'page_is_redirect','old_text','old_flags' ),
2370 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2371 $fname, 'FOR UPDATE' );
2373 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2375 wfDebug( __METHOD__
. ": not a redirect\n" );
2378 $text = Revision
::getRevisionText( $obj );
2380 # Does the redirect point to the source?
2381 # Or is it a broken self-redirect, usually caused by namespace collisions?
2383 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2384 $redirTitle = Title
::newFromText( $m[1] );
2385 if( !is_object( $redirTitle ) ||
2386 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2387 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2388 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2393 wfDebug( __METHOD__
. ": failsafe\n" );
2397 # Does the article have a history?
2398 $row = $dbw->selectRow( array( 'page', 'revision'),
2400 array( 'page_namespace' => $nt->getNamespace(),
2401 'page_title' => $nt->getDBkey(),
2402 'page_id=rev_page AND page_latest != rev_id'
2403 ), $fname, 'FOR UPDATE'
2406 # Return true if there was no history
2407 return $row === false;
2411 * Can this title be added to a user's watchlist?
2415 public function isWatchable() {
2416 return !$this->isExternal()
2417 && Namespace::isWatchable( $this->getNamespace() );
2421 * Get categories to which this Title belongs and return an array of
2422 * categories' names.
2424 * @return array an array of parents in the form:
2425 * $parent => $currentarticle
2427 public function getParentCategories() {
2430 $titlekey = $this->getArticleId();
2431 $dbr = wfGetDB( DB_SLAVE
);
2432 $categorylinks = $dbr->tableName( 'categorylinks' );
2435 $sql = "SELECT * FROM $categorylinks"
2436 ." WHERE cl_from='$titlekey'"
2437 ." AND cl_from <> '0'"
2438 ." ORDER BY cl_sortkey";
2440 $res = $dbr->query ( $sql ) ;
2442 if($dbr->numRows($res) > 0) {
2443 while ( $x = $dbr->fetchObject ( $res ) )
2444 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2445 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2446 $dbr->freeResult ( $res ) ;
2454 * Get a tree of parent categories
2455 * @param array $children an array with the children in the keys, to check for circular refs
2458 public function getParentCategoryTree( $children = array() ) {
2459 $parents = $this->getParentCategories();
2461 if($parents != '') {
2462 foreach($parents as $parent => $current) {
2463 if ( array_key_exists( $parent, $children ) ) {
2464 # Circular reference
2465 $stack[$parent] = array();
2467 $nt = Title
::newFromText($parent);
2469 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2481 * Get an associative array for selecting this title from
2486 public function pageCond() {
2487 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2491 * Get the revision ID of the previous revision
2493 * @param integer $revision Revision ID. Get the revision that was before this one.
2494 * @return integer $oldrevision|false
2496 public function getPreviousRevisionID( $revision ) {
2497 $dbr = wfGetDB( DB_SLAVE
);
2498 return $dbr->selectField( 'revision', 'rev_id',
2499 'rev_page=' . intval( $this->getArticleId() ) .
2500 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2504 * Get the revision ID of the next revision
2506 * @param integer $revision Revision ID. Get the revision that was after this one.
2507 * @return integer $oldrevision|false
2509 public function getNextRevisionID( $revision ) {
2510 $dbr = wfGetDB( DB_SLAVE
);
2511 return $dbr->selectField( 'revision', 'rev_id',
2512 'rev_page=' . intval( $this->getArticleId() ) .
2513 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2517 * Get the number of revisions between the given revision IDs.
2519 * @param integer $old Revision ID.
2520 * @param integer $new Revision ID.
2521 * @return integer Number of revisions between these IDs.
2523 public function countRevisionsBetween( $old, $new ) {
2524 $dbr = wfGetDB( DB_SLAVE
);
2525 return $dbr->selectField( 'revision', 'count(*)',
2526 'rev_page = ' . intval( $this->getArticleId() ) .
2527 ' AND rev_id > ' . intval( $old ) .
2528 ' AND rev_id < ' . intval( $new ) );
2532 * Compare with another title.
2534 * @param Title $title
2537 public function equals( $title ) {
2538 // Note: === is necessary for proper matching of number-like titles.
2539 return $this->getInterwiki() === $title->getInterwiki()
2540 && $this->getNamespace() == $title->getNamespace()
2541 && $this->getDbkey() === $title->getDbkey();
2545 * Return a string representation of this title
2549 public function __toString() {
2550 return $this->getPrefixedText();
2554 * Check if page exists
2557 public function exists() {
2558 return $this->getArticleId() != 0;
2562 * Do we know that this title definitely exists, or should we otherwise
2563 * consider that it exists?
2567 public function isAlwaysKnown() {
2568 return $this->isExternal()
2569 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2570 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $this->mDbkeyform
) );
2574 * Update page_touched timestamps and send squid purge messages for
2575 * pages linking to this title. May be sent to the job queue depending
2576 * on the number of links. Typically called on create and delete.
2578 public function touchLinks() {
2579 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2582 if ( $this->getNamespace() == NS_CATEGORY
) {
2583 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2589 * Get the last touched timestamp
2591 public function getTouched() {
2592 $dbr = wfGetDB( DB_SLAVE
);
2593 $touched = $dbr->selectField( 'page', 'page_touched',
2595 'page_namespace' => $this->getNamespace(),
2596 'page_title' => $this->getDBkey()
2602 public function trackbackURL() {
2603 global $wgTitle, $wgScriptPath, $wgServer;
2605 return "$wgServer$wgScriptPath/trackback.php?article="
2606 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2609 public function trackbackRDF() {
2610 $url = htmlspecialchars($this->getFullURL());
2611 $title = htmlspecialchars($this->getText());
2612 $tburl = $this->trackbackURL();
2615 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2616 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2617 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2620 dc:identifier=\"$url\"
2622 trackback:ping=\"$tburl\" />
2627 * Generate strings used for xml 'id' names in monobook tabs
2630 public function getNamespaceKey() {
2632 switch ($this->getNamespace()) {
2635 return 'nstab-main';
2638 return 'nstab-user';
2640 return 'nstab-media';
2642 return 'nstab-special';
2644 case NS_PROJECT_TALK
:
2645 return 'nstab-project';
2648 return 'nstab-image';
2650 case NS_MEDIAWIKI_TALK
:
2651 return 'nstab-mediawiki';
2653 case NS_TEMPLATE_TALK
:
2654 return 'nstab-template';
2657 return 'nstab-help';
2659 case NS_CATEGORY_TALK
:
2660 return 'nstab-category';
2662 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2667 * Returns true if this title resolves to the named special page
2668 * @param string $name The special page name
2670 public function isSpecial( $name ) {
2671 if ( $this->getNamespace() == NS_SPECIAL
) {
2672 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2673 if ( $name == $thisName ) {
2681 * If the Title refers to a special page alias which is not the local default,
2682 * returns a new Title which points to the local default. Otherwise, returns $this.
2684 public function fixSpecialName() {
2685 if ( $this->getNamespace() == NS_SPECIAL
) {
2686 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2687 if ( $canonicalName ) {
2688 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2689 if ( $localName != $this->mDbkeyform
) {
2690 return Title
::makeTitle( NS_SPECIAL
, $localName );
2698 * Is this Title in a namespace which contains content?
2699 * In other words, is this a content page, for the purposes of calculating
2704 public function isContentPage() {
2705 return Namespace::isContent( $this->getNamespace() );