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
283 if( preg_match( '!\[{2}(.*?)(?:\||\]{2})!', $text, $m ) ) {
284 // Strip preceding colon used to "escape" categories, etc.
285 // and URL-decode links
286 $m[1] = urldecode( ltrim( $m[1], ':' ) );
287 $title = Title
::newFromText( $m[1] );
288 // Redirects to Special:Userlogout are not permitted
289 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
296 #----------------------------------------------------------------------------
298 #----------------------------------------------------------------------------
301 * Get the prefixed DB key associated with an ID
302 * @param int $id the page_id of the article
303 * @return Title an object representing the article, or NULL
304 * if no such article was found
308 function nameOf( $id ) {
309 $fname = 'Title::nameOf';
310 $dbr = wfGetDB( DB_SLAVE
);
312 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
313 if ( $s === false ) { return NULL; }
315 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
320 * Get a regex character class describing the legal characters in a link
321 * @return string the list of characters, not delimited
323 public static function legalChars() {
324 global $wgLegalTitleChars;
325 return $wgLegalTitleChars;
329 * Get a string representation of a title suitable for
330 * including in a search index
332 * @param int $ns a namespace index
333 * @param string $title text-form main part
334 * @return string a stripped-down title string ready for the
337 public static function indexTitle( $ns, $title ) {
340 $lc = SearchEngine
::legalSearchChars() . '&#;';
341 $t = $wgContLang->stripForSearch( $title );
342 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
343 $t = $wgContLang->lc( $t );
346 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
347 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
349 $t = preg_replace( "/\\s+/", ' ', $t );
351 if ( $ns == NS_IMAGE
) {
352 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
358 * Make a prefixed DB key from a DB key and a namespace index
359 * @param int $ns numerical representation of the namespace
360 * @param string $title the DB key form the title
361 * @return string the prefixed form of the title
363 public static function makeName( $ns, $title ) {
366 $n = $wgContLang->getNsText( $ns );
367 return $n == '' ?
$title : "$n:$title";
371 * Returns the URL associated with an interwiki prefix
372 * @param string $key the interwiki prefix (e.g. "MeatBall")
373 * @return the associated URL, containing "$1", which should be
374 * replaced by an article title
377 public function getInterwikiLink( $key ) {
378 global $wgMemc, $wgInterwikiExpiry;
379 global $wgInterwikiCache, $wgContLang;
380 $fname = 'Title::getInterwikiLink';
382 $key = $wgContLang->lc( $key );
384 $k = wfMemcKey( 'interwiki', $key );
385 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
386 return Title
::$interwikiCache[$k]->iw_url
;
389 if ($wgInterwikiCache) {
390 return Title
::getInterwikiCached( $key );
393 $s = $wgMemc->get( $k );
394 # Ignore old keys with no iw_local
395 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
396 Title
::$interwikiCache[$k] = $s;
400 $dbr = wfGetDB( DB_SLAVE
);
401 $res = $dbr->select( 'interwiki',
402 array( 'iw_url', 'iw_local', 'iw_trans' ),
403 array( 'iw_prefix' => $key ), $fname );
408 $s = $dbr->fetchObject( $res );
410 # Cache non-existence: create a blank object and save it to memcached
416 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
417 Title
::$interwikiCache[$k] = $s;
423 * Fetch interwiki prefix data from local cache in constant database
425 * More logic is explained in DefaultSettings
427 * @return string URL of interwiki site
429 public static function getInterwikiCached( $key ) {
430 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
434 $db=dba_open($wgInterwikiCache,'r','cdb');
435 /* Resolve site name */
436 if ($wgInterwikiScopes>=3 and !$site) {
437 $site = dba_fetch('__sites:' . wfWikiID(), $db);
439 $site = $wgInterwikiFallbackSite;
441 $value = dba_fetch( wfMemcKey( $key ), $db);
442 if ($value=='' and $wgInterwikiScopes>=3) {
444 $value = dba_fetch("_{$site}:{$key}", $db);
446 if ($value=='' and $wgInterwikiScopes>=2) {
448 $value = dba_fetch("__global:{$key}", $db);
457 list($local,$url)=explode(' ',$value,2);
459 $s->iw_local
=(int)$local;
461 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
465 * Determine whether the object refers to a page within
468 * @return bool TRUE if this is an in-project interwiki link
469 * or a wikilink, FALSE otherwise
471 public function isLocal() {
472 if ( $this->mInterwiki
!= '' ) {
473 # Make sure key is loaded into cache
474 $this->getInterwikiLink( $this->mInterwiki
);
475 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
476 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
483 * Determine whether the object refers to a page within
484 * this project and is transcludable.
486 * @return bool TRUE if this is transcludable
488 public function isTrans() {
489 if ($this->mInterwiki
== '')
491 # Make sure key is loaded into cache
492 $this->getInterwikiLink( $this->mInterwiki
);
493 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
494 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
498 * Escape a text fragment, say from a link, for a URL
500 static function escapeFragmentForURL( $fragment ) {
501 $fragment = str_replace( ' ', '_', $fragment );
502 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
503 $replaceArray = array(
507 return strtr( $fragment, $replaceArray );
510 #----------------------------------------------------------------------------
512 #----------------------------------------------------------------------------
514 /** Simple accessors */
516 * Get the text form (spaces not underscores) of the main part
519 public function getText() { return $this->mTextform
; }
521 * Get the URL-encoded form of the main part
524 public function getPartialURL() { return $this->mUrlform
; }
526 * Get the main part with underscores
529 public function getDBkey() { return $this->mDbkeyform
; }
531 * Get the namespace index, i.e. one of the NS_xxxx constants
534 public function getNamespace() { return $this->mNamespace
; }
536 * Get the namespace text
539 public function getNsText() {
540 global $wgContLang, $wgCanonicalNamespaceNames;
542 if ( '' != $this->mInterwiki
) {
543 // This probably shouldn't even happen. ohh man, oh yuck.
544 // But for interwiki transclusion it sometimes does.
545 // Shit. Shit shit shit.
547 // Use the canonical namespaces if possible to try to
548 // resolve a foreign namespace.
549 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
550 return $wgCanonicalNamespaceNames[$this->mNamespace
];
553 return $wgContLang->getNsText( $this->mNamespace
);
556 * Get the DB key with the initial letter case as specified by the user
558 function getUserCaseDBKey() {
559 return $this->mUserCaseDBKey
;
562 * Get the namespace text of the subject (rather than talk) page
565 public function getSubjectNsText() {
567 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
571 * Get the namespace text of the talk page
574 public function getTalkNsText() {
576 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
580 * Could this title have a corresponding talk page?
583 public function canTalk() {
584 return( Namespace::canTalk( $this->mNamespace
) );
588 * Get the interwiki prefix (or null string)
591 public function getInterwiki() { return $this->mInterwiki
; }
593 * Get the Title fragment (i.e. the bit after the #) in text form
596 public function getFragment() { return $this->mFragment
; }
598 * Get the fragment in URL form, including the "#" character if there is one
601 public function getFragmentForURL() {
602 if ( $this->mFragment
== '' ) {
605 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
609 * Get the default namespace index, for when there is no namespace
612 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
615 * Get title for search index
616 * @return string a stripped-down title string ready for the
619 public function getIndexTitle() {
620 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
624 * Get the prefixed database key form
625 * @return string the prefixed title, with underscores and
626 * any interwiki and namespace prefixes
628 public function getPrefixedDBkey() {
629 $s = $this->prefix( $this->mDbkeyform
);
630 $s = str_replace( ' ', '_', $s );
635 * Get the prefixed title with spaces.
636 * This is the form usually used for display
637 * @return string the prefixed title, with spaces
639 public function getPrefixedText() {
640 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
641 $s = $this->prefix( $this->mTextform
);
642 $s = str_replace( '_', ' ', $s );
643 $this->mPrefixedText
= $s;
645 return $this->mPrefixedText
;
649 * Get the prefixed title with spaces, plus any fragment
650 * (part beginning with '#')
651 * @return string the prefixed title, with spaces and
652 * the fragment, including '#'
654 public function getFullText() {
655 $text = $this->getPrefixedText();
656 if( '' != $this->mFragment
) {
657 $text .= '#' . $this->mFragment
;
663 * Get the base name, i.e. the leftmost parts before the /
664 * @return string Base name
666 public function getBaseText() {
667 global $wgNamespacesWithSubpages;
668 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
669 $parts = explode( '/', $this->getText() );
670 # Don't discard the real title if there's no subpage involved
671 if( count( $parts ) > 1 )
672 unset( $parts[ count( $parts ) - 1 ] );
673 return implode( '/', $parts );
675 return $this->getText();
680 * Get the lowest-level subpage name, i.e. the rightmost part after /
681 * @return string Subpage name
683 public function getSubpageText() {
684 global $wgNamespacesWithSubpages;
685 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
686 $parts = explode( '/', $this->mTextform
);
687 return( $parts[ count( $parts ) - 1 ] );
689 return( $this->mTextform
);
694 * Get a URL-encoded form of the subpage text
695 * @return string URL-encoded subpage name
697 public function getSubpageUrlForm() {
698 $text = $this->getSubpageText();
699 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
700 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
705 * Get a URL-encoded title (not an actual URL) including interwiki
706 * @return string the URL-encoded form
708 public function getPrefixedURL() {
709 $s = $this->prefix( $this->mDbkeyform
);
710 $s = str_replace( ' ', '_', $s );
712 $s = wfUrlencode ( $s ) ;
714 # Cleaning up URL to make it look nice -- is this safe?
715 $s = str_replace( '%28', '(', $s );
716 $s = str_replace( '%29', ')', $s );
722 * Get a real URL referring to this title, with interwiki link and
725 * @param string $query an optional query string, not used
726 * for interwiki links
727 * @param string $variant language variant of url (for sr, zh..)
728 * @return string the URL
730 public function getFullURL( $query = '', $variant = false ) {
731 global $wgContLang, $wgServer, $wgRequest;
733 if ( '' == $this->mInterwiki
) {
734 $url = $this->getLocalUrl( $query, $variant );
736 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
737 // Correct fix would be to move the prepending elsewhere.
738 if ($wgRequest->getVal('action') != 'render') {
739 $url = $wgServer . $url;
742 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
744 $namespace = wfUrlencode( $this->getNsText() );
745 if ( '' != $namespace ) {
746 # Can this actually happen? Interwikis shouldn't be parsed.
747 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
750 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
751 $url = wfAppendQuery( $url, $query );
754 # Finally, add the fragment.
755 $url .= $this->getFragmentForURL();
757 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
762 * Get a URL with no fragment or server name. If this page is generated
763 * with action=render, $wgServer is prepended.
764 * @param string $query an optional query string; if not specified,
765 * $wgArticlePath will be used.
766 * @param string $variant language variant of url (for sr, zh..)
767 * @return string the URL
769 public function getLocalURL( $query = '', $variant = false ) {
770 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
771 global $wgVariantArticlePath, $wgContLang, $wgUser;
773 // internal links should point to same variant as current page (only anonymous users)
774 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
775 $pref = $wgContLang->getPreferredVariant(false);
776 if($pref != $wgContLang->getCode())
780 if ( $this->isExternal() ) {
781 $url = $this->getFullURL();
783 // This is currently only used for edit section links in the
784 // context of interwiki transclusion. In theory we should
785 // append the query to the end of any existing query string,
786 // but interwiki transclusion is already broken in that case.
790 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
791 if ( $query == '' ) {
792 if($variant!=false && $wgContLang->hasVariants()){
793 if($wgVariantArticlePath==false) {
794 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
796 $variantArticlePath = $wgVariantArticlePath;
798 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
799 $url = str_replace( '$1', $dbkey, $url );
802 $url = str_replace( '$1', $dbkey, $wgArticlePath );
805 global $wgActionPaths;
808 if( !empty( $wgActionPaths ) &&
809 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
811 $action = urldecode( $matches[2] );
812 if( isset( $wgActionPaths[$action] ) ) {
813 $query = $matches[1];
814 if( isset( $matches[4] ) ) $query .= $matches[4];
815 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
816 if( $query != '' ) $url .= '?' . $query;
819 if ( $url === false ) {
820 if ( $query == '-' ) {
823 $url = "{$wgScript}?title={$dbkey}&{$query}";
827 // FIXME: this causes breakage in various places when we
828 // actually expected a local URL and end up with dupe prefixes.
829 if ($wgRequest->getVal('action') == 'render') {
830 $url = $wgServer . $url;
833 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
838 * Get an HTML-escaped version of the URL form, suitable for
839 * using in a link, without a server name or fragment
840 * @param string $query an optional query string
841 * @return string the URL
843 public function escapeLocalURL( $query = '' ) {
844 return htmlspecialchars( $this->getLocalURL( $query ) );
848 * Get an HTML-escaped version of the URL form, suitable for
849 * using in a link, including the server name and fragment
851 * @return string the URL
852 * @param string $query an optional query string
854 public function escapeFullURL( $query = '' ) {
855 return htmlspecialchars( $this->getFullURL( $query ) );
859 * Get the URL form for an internal link.
860 * - Used in various Squid-related code, in case we have a different
861 * internal hostname for the server from the exposed one.
863 * @param string $query an optional query string
864 * @param string $variant language variant of url (for sr, zh..)
865 * @return string the URL
867 public function getInternalURL( $query = '', $variant = false ) {
868 global $wgInternalServer;
869 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
870 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
875 * Get the edit URL for this Title
876 * @return string the URL, or a null string if this is an
879 public function getEditURL() {
880 if ( '' != $this->mInterwiki
) { return ''; }
881 $s = $this->getLocalURL( 'action=edit' );
887 * Get the HTML-escaped displayable text form.
888 * Used for the title field in <a> tags.
889 * @return string the text, including any prefixes
891 public function getEscapedText() {
892 return htmlspecialchars( $this->getPrefixedText() );
896 * Is this Title interwiki?
899 public function isExternal() { return ( '' != $this->mInterwiki
); }
902 * Is this page "semi-protected" - the *only* protection is autoconfirm?
904 * @param string Action to check (default: edit)
907 public function isSemiProtected( $action = 'edit' ) {
908 if( $this->exists() ) {
909 $restrictions = $this->getRestrictions( $action );
910 if( count( $restrictions ) > 0 ) {
911 foreach( $restrictions as $restriction ) {
912 if( strtolower( $restriction ) != 'autoconfirmed' )
921 # If it doesn't exist, it can't be protected
927 * Does the title correspond to a protected article?
928 * @param string $what the action the page is protected from,
929 * by default checks move and edit
932 public function isProtected( $action = '' ) {
933 global $wgRestrictionLevels;
935 # Special pages have inherent protection
936 if( $this->getNamespace() == NS_SPECIAL
)
939 # Check regular protection levels
940 if( $action == 'edit' ||
$action == '' ) {
941 $r = $this->getRestrictions( 'edit' );
942 foreach( $wgRestrictionLevels as $level ) {
943 if( in_array( $level, $r ) && $level != '' ) {
949 if( $action == 'move' ||
$action == '' ) {
950 $r = $this->getRestrictions( 'move' );
951 foreach( $wgRestrictionLevels as $level ) {
952 if( in_array( $level, $r ) && $level != '' ) {
962 * Is $wgUser is watching this page?
965 public function userIsWatching() {
968 if ( is_null( $this->mWatched
) ) {
969 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
970 $this->mWatched
= false;
972 $this->mWatched
= $wgUser->isWatched( $this );
975 return $this->mWatched
;
979 * Can $wgUser perform $action on this page?
980 * This skips potentially expensive cascading permission checks.
982 * Suitable for use for nonessential UI controls in common cases, but
983 * _not_ for functional access control.
985 * May provide false positives, but should never provide a false negative.
987 * @param string $action action that permission needs to be checked for
990 public function quickUserCan( $action ) {
991 return $this->userCan( $action, false );
995 * Determines if $wgUser is unable to edit this page because it has been protected
996 * by $wgNamespaceProtection.
1000 public function isNamespaceProtected() {
1001 global $wgNamespaceProtection, $wgUser;
1002 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1003 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1004 if( $right != '' && !$wgUser->isAllowed( $right ) )
1012 * Can $wgUser perform $action on this page?
1013 * @param string $action action that permission needs to be checked for
1014 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1017 public function userCan( $action, $doExpensiveQueries = true ) {
1019 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1023 * Can $user perform $action on this page?
1024 * @param string $action action that permission needs to be checked for
1025 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1026 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1028 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1029 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1034 if ( wfReadOnly() && $action != 'read' ) {
1035 $errors[] = array( 'readonlytext' );
1038 global $wgEmailConfirmToEdit, $wgUser;
1040 if ( $wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed() )
1042 $errors[] = array( 'confirmedittext' );
1045 if ( $user->isBlockedFrom( $this ) ) {
1046 $block = $user->mBlock
;
1048 // This is from OutputPage::blockedPage
1049 // Copied at r23888 by werdna
1051 $id = $user->blockedBy();
1052 $reason = $user->blockedFor();
1055 if ( is_numeric( $id ) ) {
1056 $name = User
::whoIs( $id );
1061 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1062 $blockid = $block->mId
;
1063 $blockExpiry = $user->mBlock
->mExpiry
;
1065 if ( $blockExpiry == 'infinity' ) {
1066 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1067 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1069 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1070 if ( strpos( $option, ':' ) == false )
1073 list ($show, $value) = explode( ":", $option );
1075 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1076 $blockExpiry = $show;
1081 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1084 $intended = $user->mBlock
->mAddress
;
1086 $errors[] = array ( ($block->mAuto ?
'autoblockedtext-concise' : 'blockedtext-concise'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended );
1093 * Can $user perform $action on this page?
1094 * This is an internal function, which checks ONLY that previously checked by userCan (i.e. it leaves out checks on wfReadOnly() and blocks)
1095 * @param string $action action that permission needs to be checked for
1096 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1097 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1099 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1100 $fname = 'Title::userCan';
1101 wfProfileIn( $fname );
1105 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1106 return $result ?
array() : array( array( 'badaccess-group0' ) );
1109 if( NS_SPECIAL
== $this->mNamespace
) {
1110 $errors[] = array('ns-specialprotected');
1113 if ( $this->isNamespaceProtected() ) {
1114 $ns = $this->getNamespace() == NS_MAIN
1115 ?
wfMsg( 'nstab-main' )
1116 : $this->getNsText();
1117 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1118 ?
array('protectedinterface')
1119 : array( 'namespaceprotected', $ns ) );
1122 if( $this->mDbkeyform
== '_' ) {
1123 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1124 $errors[] = array('badaccess-group0');
1127 # protect css/js subpages of user pages
1128 # XXX: this might be better using restrictions
1129 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1130 if( $this->isCssJsSubpage()
1131 && !$user->isAllowed('editinterface')
1132 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1133 $errors[] = array('customcssjsprotected');
1136 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1137 # We /could/ use the protection level on the source page, but it's fairly ugly
1138 # as we have to establish a precedence hierarchy for pages included by multiple
1139 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1140 # as they could remove the protection anyway.
1141 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1142 # Cascading protection depends on more than this page...
1143 # Several cascading protected pages may include this page...
1144 # Check each cascading level
1145 # This is only for protection restrictions, not for all actions
1146 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1147 foreach( $restrictions[$action] as $right ) {
1148 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1149 if( '' != $right && !$user->isAllowed( $right ) ) {
1151 foreach( $cascadingSources as $page )
1152 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1153 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1159 foreach( $this->getRestrictions($action) as $right ) {
1160 // Backwards compatibility, rewrite sysop -> protect
1161 if ( $right == 'sysop' ) {
1164 if( '' != $right && !$user->isAllowed( $right ) ) {
1165 $errors[] = array( 'protectedpagetext' );
1169 if( $action == 'create' ) {
1170 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1171 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1172 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1174 } elseif( $action == 'move' &&
1175 !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1176 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1177 } else if ( !$user->isAllowed( $action ) ) {
1180 global $wgGroupPermissions;
1181 foreach( $wgGroupPermissions as $key => $value ) {
1182 if( isset( $value[$action] ) && $value[$action] == true ) {
1183 $groupName = User
::getGroupName( $key );
1184 $groupPage = User
::getGroupPage( $key );
1186 $skin = $user->getSkin();
1187 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1189 $groups[] = $groupName;
1193 $n = count( $groups );
1194 $groups = implode( ', ', $groups );
1199 $return = array( "badaccess-group$n", $groups );
1202 $return = array( 'badaccess-groups', $groups );
1204 $errors[] = $return;
1207 wfProfileOut( $fname );
1212 * Can $wgUser edit this page?
1214 * @deprecated use userCan('edit')
1216 public function userCanEdit( $doExpensiveQueries = true ) {
1217 return $this->userCan( 'edit', $doExpensiveQueries );
1221 * Can $wgUser create this page?
1223 * @deprecated use userCan('create')
1225 public function userCanCreate( $doExpensiveQueries = true ) {
1226 return $this->userCan( 'create', $doExpensiveQueries );
1230 * Can $wgUser move this page?
1232 * @deprecated use userCan('move')
1234 public function userCanMove( $doExpensiveQueries = true ) {
1235 return $this->userCan( 'move', $doExpensiveQueries );
1239 * Would anybody with sufficient privileges be able to move this page?
1240 * Some pages just aren't movable.
1244 public function isMovable() {
1245 return Namespace::isMovable( $this->getNamespace() )
1246 && $this->getInterwiki() == '';
1250 * Can $wgUser read this page?
1252 * @todo fold these checks into userCan()
1254 public function userCanRead() {
1258 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1259 if ( $result !== null ) {
1263 if( $wgUser->isAllowed( 'read' ) ) {
1266 global $wgWhitelistRead;
1269 * Always grant access to the login page.
1270 * Even anons need to be able to log in.
1272 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1277 * Check for explicit whitelisting
1279 $name = $this->getPrefixedText();
1280 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead, true ) )
1284 * Old settings might have the title prefixed with
1285 * a colon for main-namespace pages
1287 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1288 if( in_array( ':' . $name, $wgWhitelistRead ) )
1293 * If it's a special page, ditch the subpage bit
1296 if( $this->getNamespace() == NS_SPECIAL
) {
1297 $name = $this->getText();
1298 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1299 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1300 if( in_array( $pure, $wgWhitelistRead, true ) )
1309 * Is this a talk page of some sort?
1312 public function isTalkPage() {
1313 return Namespace::isTalk( $this->getNamespace() );
1317 * Is this a subpage?
1320 public function isSubpage() {
1321 global $wgNamespacesWithSubpages;
1323 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1324 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1331 * Could this page contain custom CSS or JavaScript, based
1336 public function isCssOrJsPage() {
1337 return $this->mNamespace
== NS_MEDIAWIKI
1338 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1342 * Is this a .css or .js subpage of a user page?
1345 public function isCssJsSubpage() {
1346 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1349 * Is this a *valid* .css or .js subpage of a user page?
1350 * Check that the corresponding skin exists
1352 public function isValidCssJsSubpage() {
1353 if ( $this->isCssJsSubpage() ) {
1354 $skinNames = Skin
::getSkinNames();
1355 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1361 * Trim down a .css or .js subpage title to get the corresponding skin name
1363 public function getSkinFromCssJsSubpage() {
1364 $subpage = explode( '/', $this->mTextform
);
1365 $subpage = $subpage[ count( $subpage ) - 1 ];
1366 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1369 * Is this a .css subpage of a user page?
1372 public function isCssSubpage() {
1373 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1376 * Is this a .js subpage of a user page?
1379 public function isJsSubpage() {
1380 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1383 * Protect css/js subpages of user pages: can $wgUser edit
1387 * @todo XXX: this might be better using restrictions
1389 public function userCanEditCssJsSubpage() {
1391 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1395 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1397 * @return bool If the page is subject to cascading restrictions.
1399 public function isCascadeProtected() {
1400 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1401 return ( $sources > 0 );
1405 * Cascading protection: Get the source of any cascading restrictions on this page.
1407 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1408 * @return array( mixed title array, restriction array)
1409 * 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.
1410 * The restriction array is an array of each type, each of which contains an array of unique groups
1412 public function getCascadeProtectionSources( $get_pages = true ) {
1413 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1415 # Define our dimension of restrictions types
1416 $pagerestrictions = array();
1417 foreach( $wgRestrictionTypes as $action )
1418 $pagerestrictions[$action] = array();
1420 if (!$wgEnableCascadingProtection)
1421 return array( false, $pagerestrictions );
1423 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1424 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1425 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1426 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1429 wfProfileIn( __METHOD__
);
1431 $dbr = wfGetDb( DB_SLAVE
);
1433 if ( $this->getNamespace() == NS_IMAGE
) {
1434 $tables = array ('imagelinks', 'page_restrictions');
1435 $where_clauses = array(
1436 'il_to' => $this->getDBkey(),
1438 'pr_cascade' => 1 );
1440 $tables = array ('templatelinks', 'page_restrictions');
1441 $where_clauses = array(
1442 'tl_namespace' => $this->getNamespace(),
1443 'tl_title' => $this->getDBkey(),
1445 'pr_cascade' => 1 );
1449 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1450 $where_clauses[] = 'page_id=pr_page';
1453 $cols = array( 'pr_expiry' );
1456 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1458 $sources = $get_pages ?
array() : false;
1459 $now = wfTimestampNow();
1460 $purgeExpired = false;
1462 while( $row = $dbr->fetchObject( $res ) ) {
1463 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1464 if( $expiry > $now ) {
1466 $page_id = $row->pr_page
;
1467 $page_ns = $row->page_namespace
;
1468 $page_title = $row->page_title
;
1469 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1470 # Add groups needed for each restriction type if its not already there
1471 # Make sure this restriction type still exists
1472 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1473 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1479 // Trigger lazy purge of expired restrictions from the db
1480 $purgeExpired = true;
1483 if( $purgeExpired ) {
1484 Title
::purgeExpiredRestrictions();
1487 wfProfileOut( __METHOD__
);
1490 $this->mCascadeSources
= $sources;
1491 $this->mCascadingRestrictions
= $pagerestrictions;
1493 $this->mHasCascadingRestrictions
= $sources;
1496 return array( $sources, $pagerestrictions );
1499 function areRestrictionsCascading() {
1500 if (!$this->mRestrictionsLoaded
) {
1501 $this->loadRestrictions();
1504 return $this->mCascadeRestriction
;
1508 * Loads a string into mRestrictions array
1509 * @param resource $res restrictions as an SQL result.
1511 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1512 $dbr = wfGetDb( DB_SLAVE
);
1514 $this->mRestrictions
['edit'] = array();
1515 $this->mRestrictions
['move'] = array();
1517 # Backwards-compatibility: also load the restrictions from the page record (old format).
1519 if ( $oldFashionedRestrictions == NULL ) {
1520 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1523 if ($oldFashionedRestrictions != '') {
1525 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1526 $temp = explode( '=', trim( $restrict ) );
1527 if(count($temp) == 1) {
1528 // old old format should be treated as edit/move restriction
1529 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1530 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1532 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1536 $this->mOldRestrictions
= true;
1537 $this->mCascadeRestriction
= false;
1538 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1542 if( $dbr->numRows( $res ) ) {
1543 # Current system - load second to make them override.
1544 $now = wfTimestampNow();
1545 $purgeExpired = false;
1547 while ($row = $dbr->fetchObject( $res ) ) {
1548 # Cycle through all the restrictions.
1550 // This code should be refactored, now that it's being used more generally,
1551 // But I don't really see any harm in leaving it in Block for now -werdna
1552 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1554 // Only apply the restrictions if they haven't expired!
1555 if ( !$expiry ||
$expiry > $now ) {
1556 $this->mRestrictionsExpiry
= $expiry;
1557 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1559 $this->mCascadeRestriction |
= $row->pr_cascade
;
1561 // Trigger a lazy purge of expired restrictions
1562 $purgeExpired = true;
1566 if( $purgeExpired ) {
1567 Title
::purgeExpiredRestrictions();
1571 $this->mRestrictionsLoaded
= true;
1574 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1575 if( !$this->mRestrictionsLoaded
) {
1576 $dbr = wfGetDB( DB_SLAVE
);
1578 $res = $dbr->select( 'page_restrictions', '*',
1579 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1581 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1586 * Purge expired restrictions from the page_restrictions table
1588 static function purgeExpiredRestrictions() {
1589 $dbw = wfGetDB( DB_MASTER
);
1590 $dbw->delete( 'page_restrictions',
1591 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1596 * Accessor/initialisation for mRestrictions
1598 * @param string $action action that permission needs to be checked for
1599 * @return array the array of groups allowed to edit this article
1601 public function getRestrictions( $action ) {
1602 if( $this->exists() ) {
1603 if( !$this->mRestrictionsLoaded
) {
1604 $this->loadRestrictions();
1606 return isset( $this->mRestrictions
[$action] )
1607 ?
$this->mRestrictions
[$action]
1615 * Is there a version of this page in the deletion archive?
1616 * @return int the number of archived revisions
1618 public function isDeleted() {
1619 $fname = 'Title::isDeleted';
1620 if ( $this->getNamespace() < 0 ) {
1623 $dbr = wfGetDB( DB_SLAVE
);
1624 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1625 'ar_title' => $this->getDBkey() ), $fname );
1626 if( $this->getNamespace() == NS_IMAGE
) {
1627 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1628 array( 'fa_name' => $this->getDBkey() ), $fname );
1635 * Get the article ID for this Title from the link cache,
1636 * adding it if necessary
1637 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1639 * @return int the ID
1641 public function getArticleID( $flags = 0 ) {
1642 $linkCache =& LinkCache
::singleton();
1643 if ( $flags & GAID_FOR_UPDATE
) {
1644 $oldUpdate = $linkCache->forUpdate( true );
1645 $this->mArticleID
= $linkCache->addLinkObj( $this );
1646 $linkCache->forUpdate( $oldUpdate );
1648 if ( -1 == $this->mArticleID
) {
1649 $this->mArticleID
= $linkCache->addLinkObj( $this );
1652 return $this->mArticleID
;
1655 public function getLatestRevID() {
1656 if ($this->mLatestID
!== false)
1657 return $this->mLatestID
;
1659 $db = wfGetDB(DB_SLAVE
);
1660 return $this->mLatestID
= $db->selectField( 'revision',
1662 array('rev_page' => $this->getArticleID()),
1663 'Title::getLatestRevID' );
1667 * This clears some fields in this object, and clears any associated
1668 * keys in the "bad links" section of the link cache.
1670 * - This is called from Article::insertNewArticle() to allow
1671 * loading of the new page_id. It's also called from
1672 * Article::doDeleteArticle()
1674 * @param int $newid the new Article ID
1676 public function resetArticleID( $newid ) {
1677 $linkCache =& LinkCache
::singleton();
1678 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1680 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1681 else { $this->mArticleID
= $newid; }
1682 $this->mRestrictionsLoaded
= false;
1683 $this->mRestrictions
= array();
1687 * Updates page_touched for this page; called from LinksUpdate.php
1688 * @return bool true if the update succeded
1690 public function invalidateCache() {
1691 global $wgUseFileCache;
1693 if ( wfReadOnly() ) {
1697 $dbw = wfGetDB( DB_MASTER
);
1698 $success = $dbw->update( 'page',
1700 'page_touched' => $dbw->timestamp()
1701 ), array( /* WHERE */
1702 'page_namespace' => $this->getNamespace() ,
1703 'page_title' => $this->getDBkey()
1704 ), 'Title::invalidateCache'
1707 if ($wgUseFileCache) {
1708 $cache = new HTMLFileCache($this);
1709 @unlink
($cache->fileCacheName());
1716 * Prefix some arbitrary text with the namespace or interwiki prefix
1719 * @param string $name the text
1720 * @return string the prefixed text
1723 /* private */ function prefix( $name ) {
1725 if ( '' != $this->mInterwiki
) {
1726 $p = $this->mInterwiki
. ':';
1728 if ( 0 != $this->mNamespace
) {
1729 $p .= $this->getNsText() . ':';
1735 * Secure and split - main initialisation function for this object
1737 * Assumes that mDbkeyform has been set, and is urldecoded
1738 * and uses underscores, but not otherwise munged. This function
1739 * removes illegal characters, splits off the interwiki and
1740 * namespace prefixes, sets the other forms, and canonicalizes
1742 * @return bool true on success
1744 private function secureAndSplit() {
1745 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1748 static $rxTc = false;
1750 # % is needed as well
1751 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1754 $this->mInterwiki
= $this->mFragment
= '';
1755 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1757 $dbkey = $this->mDbkeyform
;
1759 # Strip Unicode bidi override characters.
1760 # Sometimes they slip into cut-n-pasted page titles, where the
1761 # override chars get included in list displays.
1762 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1763 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1765 # Clean up whitespace
1767 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1768 $dbkey = trim( $dbkey, '_' );
1770 if ( '' == $dbkey ) {
1774 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1775 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1779 $this->mDbkeyform
= $dbkey;
1781 # Initial colon indicates main namespace rather than specified default
1782 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1783 if ( ':' == $dbkey{0} ) {
1784 $this->mNamespace
= NS_MAIN
;
1785 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1786 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1789 # Namespace or interwiki prefix
1793 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1795 if ( $ns = $wgContLang->getNsIndex( $p )) {
1796 # Ordinary namespace
1798 $this->mNamespace
= $ns;
1799 } elseif( $this->getInterwikiLink( $p ) ) {
1801 # Can't make a local interwiki link to an interwiki link.
1802 # That's just crazy!
1808 $this->mInterwiki
= $wgContLang->lc( $p );
1810 # Redundant interwiki prefix to the local wiki
1811 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1812 if( $dbkey == '' ) {
1813 # Can't have an empty self-link
1816 $this->mInterwiki
= '';
1818 # Do another namespace split...
1822 # If there's an initial colon after the interwiki, that also
1823 # resets the default namespace
1824 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1825 $this->mNamespace
= NS_MAIN
;
1826 $dbkey = substr( $dbkey, 1 );
1829 # If there's no recognized interwiki or namespace,
1830 # then let the colon expression be part of the title.
1835 # We already know that some pages won't be in the database!
1837 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1838 $this->mArticleID
= 0;
1840 $fragment = strstr( $dbkey, '#' );
1841 if ( false !== $fragment ) {
1842 $this->setFragment( $fragment );
1843 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1844 # remove whitespace again: prevents "Foo_bar_#"
1845 # becoming "Foo_bar_"
1846 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1849 # Reject illegal characters.
1851 if( preg_match( $rxTc, $dbkey ) ) {
1856 * Pages with "/./" or "/../" appearing in the URLs will
1857 * often be unreachable due to the way web browsers deal
1858 * with 'relative' URLs. Forbid them explicitly.
1860 if ( strpos( $dbkey, '.' ) !== false &&
1861 ( $dbkey === '.' ||
$dbkey === '..' ||
1862 strpos( $dbkey, './' ) === 0 ||
1863 strpos( $dbkey, '../' ) === 0 ||
1864 strpos( $dbkey, '/./' ) !== false ||
1865 strpos( $dbkey, '/../' ) !== false ) )
1871 * Magic tilde sequences? Nu-uh!
1873 if( strpos( $dbkey, '~~~' ) !== false ) {
1878 * Limit the size of titles to 255 bytes.
1879 * This is typically the size of the underlying database field.
1880 * We make an exception for special pages, which don't need to be stored
1881 * in the database, and may edge over 255 bytes due to subpage syntax
1882 * for long titles, e.g. [[Special:Block/Long name]]
1884 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
1885 strlen( $dbkey ) > 512 )
1891 * Normally, all wiki links are forced to have
1892 * an initial capital letter so [[foo]] and [[Foo]]
1893 * point to the same place.
1895 * Don't force it for interwikis, since the other
1896 * site might be case-sensitive.
1898 $this->mUserCaseDBKey
= $dbkey;
1899 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1900 $dbkey = $wgContLang->ucfirst( $dbkey );
1904 * Can't make a link to a namespace alone...
1905 * "empty" local links can only be self-links
1906 * with a fragment identifier.
1909 $this->mInterwiki
== '' &&
1910 $this->mNamespace
!= NS_MAIN
) {
1914 // Any remaining initial :s are illegal.
1915 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1920 $this->mDbkeyform
= $dbkey;
1921 $this->mUrlform
= wfUrlencode( $dbkey );
1923 $this->mTextform
= str_replace( '_', ' ', $dbkey );
1929 * Set the fragment for this title
1930 * This is kind of bad, since except for this rarely-used function, Title objects
1931 * are immutable. The reason this is here is because it's better than setting the
1932 * members directly, which is what Linker::formatComment was doing previously.
1934 * @param string $fragment text
1935 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1937 public function setFragment( $fragment ) {
1938 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1942 * Get a Title object associated with the talk page of this article
1943 * @return Title the object for the talk page
1945 public function getTalkPage() {
1946 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1950 * Get a title object associated with the subject page of this
1953 * @return Title the object for the subject page
1955 public function getSubjectPage() {
1956 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1960 * Get an array of Title objects linking to this Title
1961 * Also stores the IDs in the link cache.
1963 * WARNING: do not use this function on arbitrary user-supplied titles!
1964 * On heavily-used templates it will max out the memory.
1966 * @param string $options may be FOR UPDATE
1967 * @return array the Title objects linking here
1969 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1970 $linkCache =& LinkCache
::singleton();
1973 $db = wfGetDB( DB_MASTER
);
1975 $db = wfGetDB( DB_SLAVE
);
1978 $res = $db->select( array( 'page', $table ),
1979 array( 'page_namespace', 'page_title', 'page_id' ),
1981 "{$prefix}_from=page_id",
1982 "{$prefix}_namespace" => $this->getNamespace(),
1983 "{$prefix}_title" => $this->getDbKey() ),
1984 'Title::getLinksTo',
1988 if ( $db->numRows( $res ) ) {
1989 while ( $row = $db->fetchObject( $res ) ) {
1990 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1991 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1992 $retVal[] = $titleObj;
1996 $db->freeResult( $res );
2001 * Get an array of Title objects using this Title as a template
2002 * Also stores the IDs in the link cache.
2004 * WARNING: do not use this function on arbitrary user-supplied titles!
2005 * On heavily-used templates it will max out the memory.
2007 * @param string $options may be FOR UPDATE
2008 * @return array the Title objects linking here
2010 public function getTemplateLinksTo( $options = '' ) {
2011 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2015 * Get an array of Title objects referring to non-existent articles linked from this page
2017 * @param string $options may be FOR UPDATE
2018 * @return array the Title objects
2020 public function getBrokenLinksFrom( $options = '' ) {
2022 $db = wfGetDB( DB_MASTER
);
2024 $db = wfGetDB( DB_SLAVE
);
2027 $res = $db->safeQuery(
2028 "SELECT pl_namespace, pl_title
2031 ON pl_namespace=page_namespace
2032 AND pl_title=page_title
2034 AND page_namespace IS NULL
2036 $db->tableName( 'pagelinks' ),
2037 $db->tableName( 'page' ),
2038 $this->getArticleId(),
2042 if ( $db->numRows( $res ) ) {
2043 while ( $row = $db->fetchObject( $res ) ) {
2044 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2047 $db->freeResult( $res );
2053 * Get a list of URLs to purge from the Squid cache when this
2056 * @return array the URLs
2058 public function getSquidURLs() {
2062 $this->getInternalURL(),
2063 $this->getInternalURL( 'action=history' )
2066 // purge variant urls as well
2067 if($wgContLang->hasVariants()){
2068 $variants = $wgContLang->getVariants();
2069 foreach($variants as $vCode){
2070 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2071 $urls[] = $this->getInternalURL('',$vCode);
2078 public function purgeSquid() {
2080 if ( $wgUseSquid ) {
2081 $urls = $this->getSquidURLs();
2082 $u = new SquidUpdate( $urls );
2088 * Move this page without authentication
2089 * @param Title &$nt the new page Title
2091 public function moveNoAuth( &$nt ) {
2092 return $this->moveTo( $nt, false );
2096 * Check whether a given move operation would be valid.
2097 * Returns true if ok, or a message key string for an error message
2098 * if invalid. (Scarrrrry ugly interface this.)
2099 * @param Title &$nt the new title
2100 * @param bool $auth indicates whether $wgUser's permissions
2102 * @return mixed true on success, message name on failure
2104 public function isValidMoveOperation( &$nt, $auth = true ) {
2105 if( !$this or !$nt ) {
2106 return 'badtitletext';
2108 if( $this->equals( $nt ) ) {
2111 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2112 return 'immobile_namespace';
2115 $oldid = $this->getArticleID();
2116 $newid = $nt->getArticleID();
2118 if ( strlen( $nt->getDBkey() ) < 1 ) {
2119 return 'articleexists';
2121 if ( ( '' == $this->getDBkey() ) ||
2123 ( '' == $nt->getDBkey() ) ) {
2124 return 'badarticleerror';
2128 !$this->userCan( 'edit' ) ||
!$nt->userCan( 'edit' ) ||
2129 !$this->userCan( 'move' ) ||
!$nt->userCan( 'move' ) ) ) {
2130 return 'protectedpage';
2133 # The move is allowed only if (1) the target doesn't exist, or
2134 # (2) the target is a redirect to the source, and has no history
2135 # (so we can undo bad moves right after they're done).
2137 if ( 0 != $newid ) { # Target exists; check for validity
2138 if ( ! $this->isValidMoveTarget( $nt ) ) {
2139 return 'articleexists';
2146 * Move a title to a new location
2147 * @param Title &$nt the new title
2148 * @param bool $auth indicates whether $wgUser's permissions
2150 * @return mixed true on success, message name on failure
2152 public function moveTo( &$nt, $auth = true, $reason = '' ) {
2153 $err = $this->isValidMoveOperation( $nt, $auth );
2154 if( is_string( $err ) ) {
2158 $pageid = $this->getArticleID();
2159 if( $nt->exists() ) {
2160 $this->moveOverExistingRedirect( $nt, $reason );
2161 $pageCountChange = 0;
2162 } else { # Target didn't exist, do normal move.
2163 $this->moveToNewTitle( $nt, $reason );
2164 $pageCountChange = 1;
2166 $redirid = $this->getArticleID();
2168 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2169 $dbw = wfGetDB( DB_MASTER
);
2170 $categorylinks = $dbw->tableName( 'categorylinks' );
2171 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2172 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2173 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2174 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2178 $oldnamespace = $this->getNamespace() & ~
1;
2179 $newnamespace = $nt->getNamespace() & ~
1;
2180 $oldtitle = $this->getDBkey();
2181 $newtitle = $nt->getDBkey();
2183 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2184 WatchedItem
::duplicateEntries( $this, $nt );
2187 # Update search engine
2188 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2190 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2194 if( $this->isContentPage() && !$nt->isContentPage() ) {
2195 # No longer a content page
2196 # Not viewed, edited, removing
2197 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2198 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2199 # Now a content page
2200 # Not viewed, edited, adding
2201 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2202 } elseif( $pageCountChange ) {
2204 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2213 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2218 * Move page to a title which is at present a redirect to the
2221 * @param Title &$nt the page to move to, which should currently
2224 private function moveOverExistingRedirect( &$nt, $reason = '' ) {
2226 $fname = 'Title::moveOverExistingRedirect';
2227 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2230 $comment .= ": $reason";
2233 $now = wfTimestampNow();
2234 $newid = $nt->getArticleID();
2235 $oldid = $this->getArticleID();
2236 $dbw = wfGetDB( DB_MASTER
);
2237 $linkCache =& LinkCache
::singleton();
2239 # Delete the old redirect. We don't save it to history since
2240 # by definition if we've got here it's rather uninteresting.
2241 # We have to remove it so that the next step doesn't trigger
2242 # a conflict on the unique namespace+title index...
2243 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2245 # Save a null revision in the page's history notifying of the move
2246 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2247 $nullRevId = $nullRevision->insertOn( $dbw );
2249 # Change the name of the target page:
2250 $dbw->update( 'page',
2252 'page_touched' => $dbw->timestamp($now),
2253 'page_namespace' => $nt->getNamespace(),
2254 'page_title' => $nt->getDBkey(),
2255 'page_latest' => $nullRevId,
2257 /* WHERE */ array( 'page_id' => $oldid ),
2260 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2262 # Recreate the redirect, this time in the other direction.
2263 $mwRedir = MagicWord
::get( 'redirect' );
2264 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2265 $redirectArticle = new Article( $this );
2266 $newid = $redirectArticle->insertOn( $dbw );
2267 $redirectRevision = new Revision( array(
2269 'comment' => $comment,
2270 'text' => $redirectText ) );
2271 $redirectRevision->insertOn( $dbw );
2272 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2273 $linkCache->clearLink( $this->getPrefixedDBkey() );
2276 $log = new LogPage( 'move' );
2277 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2279 # Now, we record the link from the redirect to the new title.
2280 # It should have no other outgoing links...
2281 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2282 $dbw->insert( 'pagelinks',
2284 'pl_from' => $newid,
2285 'pl_namespace' => $nt->getNamespace(),
2286 'pl_title' => $nt->getDbKey() ),
2290 if ( $wgUseSquid ) {
2291 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2292 $u = new SquidUpdate( $urls );
2298 * Move page to non-existing title.
2299 * @param Title &$nt the new Title
2301 private function moveToNewTitle( &$nt, $reason = '' ) {
2303 $fname = 'MovePageForm::moveToNewTitle';
2304 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2306 $comment .= ": $reason";
2309 $newid = $nt->getArticleID();
2310 $oldid = $this->getArticleID();
2311 $dbw = wfGetDB( DB_MASTER
);
2312 $now = $dbw->timestamp();
2313 $linkCache =& LinkCache
::singleton();
2315 # Save a null revision in the page's history notifying of the move
2316 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2317 $nullRevId = $nullRevision->insertOn( $dbw );
2320 $dbw->update( 'page',
2322 'page_touched' => $now,
2323 'page_namespace' => $nt->getNamespace(),
2324 'page_title' => $nt->getDBkey(),
2325 'page_latest' => $nullRevId,
2327 /* WHERE */ array( 'page_id' => $oldid ),
2331 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2334 $mwRedir = MagicWord
::get( 'redirect' );
2335 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2336 $redirectArticle = new Article( $this );
2337 $newid = $redirectArticle->insertOn( $dbw );
2338 $redirectRevision = new Revision( array(
2340 'comment' => $comment,
2341 'text' => $redirectText ) );
2342 $redirectRevision->insertOn( $dbw );
2343 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2344 $linkCache->clearLink( $this->getPrefixedDBkey() );
2347 $log = new LogPage( 'move' );
2348 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2350 # Purge caches as per article creation
2351 Article
::onArticleCreate( $nt );
2353 # Record the just-created redirect's linking to the page
2354 $dbw->insert( 'pagelinks',
2356 'pl_from' => $newid,
2357 'pl_namespace' => $nt->getNamespace(),
2358 'pl_title' => $nt->getDBkey() ),
2361 # Purge old title from squid
2362 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2363 $this->purgeSquid();
2367 * Checks if $this can be moved to a given Title
2368 * - Selects for update, so don't call it unless you mean business
2370 * @param Title &$nt the new title to check
2372 public function isValidMoveTarget( $nt ) {
2374 $fname = 'Title::isValidMoveTarget';
2375 $dbw = wfGetDB( DB_MASTER
);
2378 $id = $nt->getArticleID();
2379 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2380 array( 'page_is_redirect','old_text','old_flags' ),
2381 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2382 $fname, 'FOR UPDATE' );
2384 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2386 wfDebug( __METHOD__
. ": not a redirect\n" );
2389 $text = Revision
::getRevisionText( $obj );
2391 # Does the redirect point to the source?
2392 # Or is it a broken self-redirect, usually caused by namespace collisions?
2394 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2395 $redirTitle = Title
::newFromText( $m[1] );
2396 if( !is_object( $redirTitle ) ||
2397 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2398 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2399 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2404 wfDebug( __METHOD__
. ": failsafe\n" );
2408 # Does the article have a history?
2409 $row = $dbw->selectRow( array( 'page', 'revision'),
2411 array( 'page_namespace' => $nt->getNamespace(),
2412 'page_title' => $nt->getDBkey(),
2413 'page_id=rev_page AND page_latest != rev_id'
2414 ), $fname, 'FOR UPDATE'
2417 # Return true if there was no history
2418 return $row === false;
2422 * Can this title be added to a user's watchlist?
2426 public function isWatchable() {
2427 return !$this->isExternal()
2428 && Namespace::isWatchable( $this->getNamespace() );
2432 * Get categories to which this Title belongs and return an array of
2433 * categories' names.
2435 * @return array an array of parents in the form:
2436 * $parent => $currentarticle
2438 public function getParentCategories() {
2441 $titlekey = $this->getArticleId();
2442 $dbr = wfGetDB( DB_SLAVE
);
2443 $categorylinks = $dbr->tableName( 'categorylinks' );
2446 $sql = "SELECT * FROM $categorylinks"
2447 ." WHERE cl_from='$titlekey'"
2448 ." AND cl_from <> '0'"
2449 ." ORDER BY cl_sortkey";
2451 $res = $dbr->query ( $sql ) ;
2453 if($dbr->numRows($res) > 0) {
2454 while ( $x = $dbr->fetchObject ( $res ) )
2455 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2456 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2457 $dbr->freeResult ( $res ) ;
2465 * Get a tree of parent categories
2466 * @param array $children an array with the children in the keys, to check for circular refs
2469 public function getParentCategoryTree( $children = array() ) {
2470 $parents = $this->getParentCategories();
2472 if($parents != '') {
2473 foreach($parents as $parent => $current) {
2474 if ( array_key_exists( $parent, $children ) ) {
2475 # Circular reference
2476 $stack[$parent] = array();
2478 $nt = Title
::newFromText($parent);
2480 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2492 * Get an associative array for selecting this title from
2497 public function pageCond() {
2498 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2502 * Get the revision ID of the previous revision
2504 * @param integer $revision Revision ID. Get the revision that was before this one.
2505 * @return integer $oldrevision|false
2507 public function getPreviousRevisionID( $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 DESC' );
2515 * Get the revision ID of the next revision
2517 * @param integer $revision Revision ID. Get the revision that was after this one.
2518 * @return integer $oldrevision|false
2520 public function getNextRevisionID( $revision ) {
2521 $dbr = wfGetDB( DB_SLAVE
);
2522 return $dbr->selectField( 'revision', 'rev_id',
2523 'rev_page=' . intval( $this->getArticleId() ) .
2524 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2528 * Get the number of revisions between the given revision IDs.
2530 * @param integer $old Revision ID.
2531 * @param integer $new Revision ID.
2532 * @return integer Number of revisions between these IDs.
2534 public function countRevisionsBetween( $old, $new ) {
2535 $dbr = wfGetDB( DB_SLAVE
);
2536 return $dbr->selectField( 'revision', 'count(*)',
2537 'rev_page = ' . intval( $this->getArticleId() ) .
2538 ' AND rev_id > ' . intval( $old ) .
2539 ' AND rev_id < ' . intval( $new ) );
2543 * Compare with another title.
2545 * @param Title $title
2548 public function equals( $title ) {
2549 // Note: === is necessary for proper matching of number-like titles.
2550 return $this->getInterwiki() === $title->getInterwiki()
2551 && $this->getNamespace() == $title->getNamespace()
2552 && $this->getDbkey() === $title->getDbkey();
2556 * Return a string representation of this title
2560 public function __toString() {
2561 return $this->getPrefixedText();
2565 * Check if page exists
2568 public function exists() {
2569 return $this->getArticleId() != 0;
2573 * Do we know that this title definitely exists, or should we otherwise
2574 * consider that it exists?
2578 public function isAlwaysKnown() {
2579 return $this->isExternal()
2580 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2581 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $this->mDbkeyform
) );
2585 * Update page_touched timestamps and send squid purge messages for
2586 * pages linking to this title. May be sent to the job queue depending
2587 * on the number of links. Typically called on create and delete.
2589 public function touchLinks() {
2590 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2593 if ( $this->getNamespace() == NS_CATEGORY
) {
2594 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2600 * Get the last touched timestamp
2602 public function getTouched() {
2603 $dbr = wfGetDB( DB_SLAVE
);
2604 $touched = $dbr->selectField( 'page', 'page_touched',
2606 'page_namespace' => $this->getNamespace(),
2607 'page_title' => $this->getDBkey()
2613 public function trackbackURL() {
2614 global $wgTitle, $wgScriptPath, $wgServer;
2616 return "$wgServer$wgScriptPath/trackback.php?article="
2617 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2620 public function trackbackRDF() {
2621 $url = htmlspecialchars($this->getFullURL());
2622 $title = htmlspecialchars($this->getText());
2623 $tburl = $this->trackbackURL();
2626 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2627 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2628 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2631 dc:identifier=\"$url\"
2633 trackback:ping=\"$tburl\" />
2638 * Generate strings used for xml 'id' names in monobook tabs
2641 public function getNamespaceKey() {
2643 switch ($this->getNamespace()) {
2646 return 'nstab-main';
2649 return 'nstab-user';
2651 return 'nstab-media';
2653 return 'nstab-special';
2655 case NS_PROJECT_TALK
:
2656 return 'nstab-project';
2659 return 'nstab-image';
2661 case NS_MEDIAWIKI_TALK
:
2662 return 'nstab-mediawiki';
2664 case NS_TEMPLATE_TALK
:
2665 return 'nstab-template';
2668 return 'nstab-help';
2670 case NS_CATEGORY_TALK
:
2671 return 'nstab-category';
2673 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2678 * Returns true if this title resolves to the named special page
2679 * @param string $name The special page name
2681 public function isSpecial( $name ) {
2682 if ( $this->getNamespace() == NS_SPECIAL
) {
2683 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2684 if ( $name == $thisName ) {
2692 * If the Title refers to a special page alias which is not the local default,
2693 * returns a new Title which points to the local default. Otherwise, returns $this.
2695 public function fixSpecialName() {
2696 if ( $this->getNamespace() == NS_SPECIAL
) {
2697 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2698 if ( $canonicalName ) {
2699 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2700 if ( $localName != $this->mDbkeyform
) {
2701 return Title
::makeTitle( NS_SPECIAL
, $localName );
2709 * Is this Title in a namespace which contains content?
2710 * In other words, is this a content page, for the purposes of calculating
2715 public function isContentPage() {
2716 return Namespace::isContent( $this->getNamespace() );