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 if( strpos( $m[1], '%' ) !== false ) {
287 // Match behavior of inline link parsing here;
288 // don't interpret + as " " most of the time!
289 // It might be safe to just use rawurldecode instead, though.
290 $m[1] = urldecode( ltrim( $m[1], ':' ) );
292 $title = Title
::newFromText( $m[1] );
293 // Redirects to Special:Userlogout are not permitted
294 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
301 #----------------------------------------------------------------------------
303 #----------------------------------------------------------------------------
306 * Get the prefixed DB key associated with an ID
307 * @param int $id the page_id of the article
308 * @return Title an object representing the article, or NULL
309 * if no such article was found
313 function nameOf( $id ) {
314 $fname = 'Title::nameOf';
315 $dbr = wfGetDB( DB_SLAVE
);
317 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
318 if ( $s === false ) { return NULL; }
320 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
325 * Get a regex character class describing the legal characters in a link
326 * @return string the list of characters, not delimited
328 public static function legalChars() {
329 global $wgLegalTitleChars;
330 return $wgLegalTitleChars;
334 * Get a string representation of a title suitable for
335 * including in a search index
337 * @param int $ns a namespace index
338 * @param string $title text-form main part
339 * @return string a stripped-down title string ready for the
342 public static function indexTitle( $ns, $title ) {
345 $lc = SearchEngine
::legalSearchChars() . '&#;';
346 $t = $wgContLang->stripForSearch( $title );
347 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
348 $t = $wgContLang->lc( $t );
351 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
352 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
354 $t = preg_replace( "/\\s+/", ' ', $t );
356 if ( $ns == NS_IMAGE
) {
357 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
363 * Make a prefixed DB key from a DB key and a namespace index
364 * @param int $ns numerical representation of the namespace
365 * @param string $title the DB key form the title
366 * @return string the prefixed form of the title
368 public static function makeName( $ns, $title ) {
371 $n = $wgContLang->getNsText( $ns );
372 return $n == '' ?
$title : "$n:$title";
376 * Returns the URL associated with an interwiki prefix
377 * @param string $key the interwiki prefix (e.g. "MeatBall")
378 * @return the associated URL, containing "$1", which should be
379 * replaced by an article title
382 public function getInterwikiLink( $key ) {
383 global $wgMemc, $wgInterwikiExpiry;
384 global $wgInterwikiCache, $wgContLang;
385 $fname = 'Title::getInterwikiLink';
387 $key = $wgContLang->lc( $key );
389 $k = wfMemcKey( 'interwiki', $key );
390 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
391 return Title
::$interwikiCache[$k]->iw_url
;
394 if ($wgInterwikiCache) {
395 return Title
::getInterwikiCached( $key );
398 $s = $wgMemc->get( $k );
399 # Ignore old keys with no iw_local
400 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
401 Title
::$interwikiCache[$k] = $s;
405 $dbr = wfGetDB( DB_SLAVE
);
406 $res = $dbr->select( 'interwiki',
407 array( 'iw_url', 'iw_local', 'iw_trans' ),
408 array( 'iw_prefix' => $key ), $fname );
413 $s = $dbr->fetchObject( $res );
415 # Cache non-existence: create a blank object and save it to memcached
421 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
422 Title
::$interwikiCache[$k] = $s;
428 * Fetch interwiki prefix data from local cache in constant database
430 * More logic is explained in DefaultSettings
432 * @return string URL of interwiki site
434 public static function getInterwikiCached( $key ) {
435 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
439 $db=dba_open($wgInterwikiCache,'r','cdb');
440 /* Resolve site name */
441 if ($wgInterwikiScopes>=3 and !$site) {
442 $site = dba_fetch('__sites:' . wfWikiID(), $db);
444 $site = $wgInterwikiFallbackSite;
446 $value = dba_fetch( wfMemcKey( $key ), $db);
447 if ($value=='' and $wgInterwikiScopes>=3) {
449 $value = dba_fetch("_{$site}:{$key}", $db);
451 if ($value=='' and $wgInterwikiScopes>=2) {
453 $value = dba_fetch("__global:{$key}", $db);
462 list($local,$url)=explode(' ',$value,2);
464 $s->iw_local
=(int)$local;
466 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
470 * Determine whether the object refers to a page within
473 * @return bool TRUE if this is an in-project interwiki link
474 * or a wikilink, FALSE otherwise
476 public function isLocal() {
477 if ( $this->mInterwiki
!= '' ) {
478 # Make sure key is loaded into cache
479 $this->getInterwikiLink( $this->mInterwiki
);
480 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
481 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return bool TRUE if this is transcludable
493 public function isTrans() {
494 if ($this->mInterwiki
== '')
496 # Make sure key is loaded into cache
497 $this->getInterwikiLink( $this->mInterwiki
);
498 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
499 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
503 * Escape a text fragment, say from a link, for a URL
505 static function escapeFragmentForURL( $fragment ) {
506 $fragment = str_replace( ' ', '_', $fragment );
507 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
508 $replaceArray = array(
512 return strtr( $fragment, $replaceArray );
515 #----------------------------------------------------------------------------
517 #----------------------------------------------------------------------------
519 /** Simple accessors */
521 * Get the text form (spaces not underscores) of the main part
524 public function getText() { return $this->mTextform
; }
526 * Get the URL-encoded form of the main part
529 public function getPartialURL() { return $this->mUrlform
; }
531 * Get the main part with underscores
534 public function getDBkey() { return $this->mDbkeyform
; }
536 * Get the namespace index, i.e. one of the NS_xxxx constants
539 public function getNamespace() { return $this->mNamespace
; }
541 * Get the namespace text
544 public function getNsText() {
545 global $wgContLang, $wgCanonicalNamespaceNames;
547 if ( '' != $this->mInterwiki
) {
548 // This probably shouldn't even happen. ohh man, oh yuck.
549 // But for interwiki transclusion it sometimes does.
550 // Shit. Shit shit shit.
552 // Use the canonical namespaces if possible to try to
553 // resolve a foreign namespace.
554 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
555 return $wgCanonicalNamespaceNames[$this->mNamespace
];
558 return $wgContLang->getNsText( $this->mNamespace
);
561 * Get the DB key with the initial letter case as specified by the user
563 function getUserCaseDBKey() {
564 return $this->mUserCaseDBKey
;
567 * Get the namespace text of the subject (rather than talk) page
570 public function getSubjectNsText() {
572 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
576 * Get the namespace text of the talk page
579 public function getTalkNsText() {
581 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
585 * Could this title have a corresponding talk page?
588 public function canTalk() {
589 return( Namespace::canTalk( $this->mNamespace
) );
593 * Get the interwiki prefix (or null string)
596 public function getInterwiki() { return $this->mInterwiki
; }
598 * Get the Title fragment (i.e. the bit after the #) in text form
601 public function getFragment() { return $this->mFragment
; }
603 * Get the fragment in URL form, including the "#" character if there is one
606 public function getFragmentForURL() {
607 if ( $this->mFragment
== '' ) {
610 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
614 * Get the default namespace index, for when there is no namespace
617 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
620 * Get title for search index
621 * @return string a stripped-down title string ready for the
624 public function getIndexTitle() {
625 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
629 * Get the prefixed database key form
630 * @return string the prefixed title, with underscores and
631 * any interwiki and namespace prefixes
633 public function getPrefixedDBkey() {
634 $s = $this->prefix( $this->mDbkeyform
);
635 $s = str_replace( ' ', '_', $s );
640 * Get the prefixed title with spaces.
641 * This is the form usually used for display
642 * @return string the prefixed title, with spaces
644 public function getPrefixedText() {
645 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
646 $s = $this->prefix( $this->mTextform
);
647 $s = str_replace( '_', ' ', $s );
648 $this->mPrefixedText
= $s;
650 return $this->mPrefixedText
;
654 * Get the prefixed title with spaces, plus any fragment
655 * (part beginning with '#')
656 * @return string the prefixed title, with spaces and
657 * the fragment, including '#'
659 public function getFullText() {
660 $text = $this->getPrefixedText();
661 if( '' != $this->mFragment
) {
662 $text .= '#' . $this->mFragment
;
668 * Get the base name, i.e. the leftmost parts before the /
669 * @return string Base name
671 public function getBaseText() {
672 global $wgNamespacesWithSubpages;
673 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
674 $parts = explode( '/', $this->getText() );
675 # Don't discard the real title if there's no subpage involved
676 if( count( $parts ) > 1 )
677 unset( $parts[ count( $parts ) - 1 ] );
678 return implode( '/', $parts );
680 return $this->getText();
685 * Get the lowest-level subpage name, i.e. the rightmost part after /
686 * @return string Subpage name
688 public function getSubpageText() {
689 global $wgNamespacesWithSubpages;
690 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
691 $parts = explode( '/', $this->mTextform
);
692 return( $parts[ count( $parts ) - 1 ] );
694 return( $this->mTextform
);
699 * Get a URL-encoded form of the subpage text
700 * @return string URL-encoded subpage name
702 public function getSubpageUrlForm() {
703 $text = $this->getSubpageText();
704 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
705 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
710 * Get a URL-encoded title (not an actual URL) including interwiki
711 * @return string the URL-encoded form
713 public function getPrefixedURL() {
714 $s = $this->prefix( $this->mDbkeyform
);
715 $s = str_replace( ' ', '_', $s );
717 $s = wfUrlencode ( $s ) ;
719 # Cleaning up URL to make it look nice -- is this safe?
720 $s = str_replace( '%28', '(', $s );
721 $s = str_replace( '%29', ')', $s );
727 * Get a real URL referring to this title, with interwiki link and
730 * @param string $query an optional query string, not used
731 * for interwiki links
732 * @param string $variant language variant of url (for sr, zh..)
733 * @return string the URL
735 public function getFullURL( $query = '', $variant = false ) {
736 global $wgContLang, $wgServer, $wgRequest;
738 if ( '' == $this->mInterwiki
) {
739 $url = $this->getLocalUrl( $query, $variant );
741 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
742 // Correct fix would be to move the prepending elsewhere.
743 if ($wgRequest->getVal('action') != 'render') {
744 $url = $wgServer . $url;
747 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
749 $namespace = wfUrlencode( $this->getNsText() );
750 if ( '' != $namespace ) {
751 # Can this actually happen? Interwikis shouldn't be parsed.
752 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
755 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
756 $url = wfAppendQuery( $url, $query );
759 # Finally, add the fragment.
760 $url .= $this->getFragmentForURL();
762 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
767 * Get a URL with no fragment or server name. If this page is generated
768 * with action=render, $wgServer is prepended.
769 * @param string $query an optional query string; if not specified,
770 * $wgArticlePath will be used.
771 * @param string $variant language variant of url (for sr, zh..)
772 * @return string the URL
774 public function getLocalURL( $query = '', $variant = false ) {
775 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
776 global $wgVariantArticlePath, $wgContLang, $wgUser;
778 // internal links should point to same variant as current page (only anonymous users)
779 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
780 $pref = $wgContLang->getPreferredVariant(false);
781 if($pref != $wgContLang->getCode())
785 if ( $this->isExternal() ) {
786 $url = $this->getFullURL();
788 // This is currently only used for edit section links in the
789 // context of interwiki transclusion. In theory we should
790 // append the query to the end of any existing query string,
791 // but interwiki transclusion is already broken in that case.
795 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
796 if ( $query == '' ) {
797 if($variant!=false && $wgContLang->hasVariants()){
798 if($wgVariantArticlePath==false) {
799 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
801 $variantArticlePath = $wgVariantArticlePath;
803 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
804 $url = str_replace( '$1', $dbkey, $url );
807 $url = str_replace( '$1', $dbkey, $wgArticlePath );
810 global $wgActionPaths;
813 if( !empty( $wgActionPaths ) &&
814 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
816 $action = urldecode( $matches[2] );
817 if( isset( $wgActionPaths[$action] ) ) {
818 $query = $matches[1];
819 if( isset( $matches[4] ) ) $query .= $matches[4];
820 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
821 if( $query != '' ) $url .= '?' . $query;
824 if ( $url === false ) {
825 if ( $query == '-' ) {
828 $url = "{$wgScript}?title={$dbkey}&{$query}";
832 // FIXME: this causes breakage in various places when we
833 // actually expected a local URL and end up with dupe prefixes.
834 if ($wgRequest->getVal('action') == 'render') {
835 $url = $wgServer . $url;
838 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
843 * Get an HTML-escaped version of the URL form, suitable for
844 * using in a link, without a server name or fragment
845 * @param string $query an optional query string
846 * @return string the URL
848 public function escapeLocalURL( $query = '' ) {
849 return htmlspecialchars( $this->getLocalURL( $query ) );
853 * Get an HTML-escaped version of the URL form, suitable for
854 * using in a link, including the server name and fragment
856 * @return string the URL
857 * @param string $query an optional query string
859 public function escapeFullURL( $query = '' ) {
860 return htmlspecialchars( $this->getFullURL( $query ) );
864 * Get the URL form for an internal link.
865 * - Used in various Squid-related code, in case we have a different
866 * internal hostname for the server from the exposed one.
868 * @param string $query an optional query string
869 * @param string $variant language variant of url (for sr, zh..)
870 * @return string the URL
872 public function getInternalURL( $query = '', $variant = false ) {
873 global $wgInternalServer;
874 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
875 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
880 * Get the edit URL for this Title
881 * @return string the URL, or a null string if this is an
884 public function getEditURL() {
885 if ( '' != $this->mInterwiki
) { return ''; }
886 $s = $this->getLocalURL( 'action=edit' );
892 * Get the HTML-escaped displayable text form.
893 * Used for the title field in <a> tags.
894 * @return string the text, including any prefixes
896 public function getEscapedText() {
897 return htmlspecialchars( $this->getPrefixedText() );
901 * Is this Title interwiki?
904 public function isExternal() { return ( '' != $this->mInterwiki
); }
907 * Is this page "semi-protected" - the *only* protection is autoconfirm?
909 * @param string Action to check (default: edit)
912 public function isSemiProtected( $action = 'edit' ) {
913 if( $this->exists() ) {
914 $restrictions = $this->getRestrictions( $action );
915 if( count( $restrictions ) > 0 ) {
916 foreach( $restrictions as $restriction ) {
917 if( strtolower( $restriction ) != 'autoconfirmed' )
926 # If it doesn't exist, it can't be protected
932 * Does the title correspond to a protected article?
933 * @param string $what the action the page is protected from,
934 * by default checks move and edit
937 public function isProtected( $action = '' ) {
938 global $wgRestrictionLevels;
940 # Special pages have inherent protection
941 if( $this->getNamespace() == NS_SPECIAL
)
944 # Check regular protection levels
945 if( $action == 'edit' ||
$action == '' ) {
946 $r = $this->getRestrictions( 'edit' );
947 foreach( $wgRestrictionLevels as $level ) {
948 if( in_array( $level, $r ) && $level != '' ) {
954 if( $action == 'move' ||
$action == '' ) {
955 $r = $this->getRestrictions( 'move' );
956 foreach( $wgRestrictionLevels as $level ) {
957 if( in_array( $level, $r ) && $level != '' ) {
967 * Is $wgUser is watching this page?
970 public function userIsWatching() {
973 if ( is_null( $this->mWatched
) ) {
974 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
975 $this->mWatched
= false;
977 $this->mWatched
= $wgUser->isWatched( $this );
980 return $this->mWatched
;
984 * Can $wgUser perform $action on this page?
985 * This skips potentially expensive cascading permission checks.
987 * Suitable for use for nonessential UI controls in common cases, but
988 * _not_ for functional access control.
990 * May provide false positives, but should never provide a false negative.
992 * @param string $action action that permission needs to be checked for
995 public function quickUserCan( $action ) {
996 return $this->userCan( $action, false );
1000 * Determines if $wgUser is unable to edit this page because it has been protected
1001 * by $wgNamespaceProtection.
1005 public function isNamespaceProtected() {
1006 global $wgNamespaceProtection, $wgUser;
1007 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1008 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1009 if( $right != '' && !$wgUser->isAllowed( $right ) )
1017 * Can $wgUser perform $action on this page?
1018 * @param string $action action that permission needs to be checked for
1019 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1022 public function userCan( $action, $doExpensiveQueries = true ) {
1024 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1028 * Can $user perform $action on this page?
1029 * @param string $action action that permission needs to be checked for
1030 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1031 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1033 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1034 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1039 if ( wfReadOnly() && $action != 'read' ) {
1041 $errors[] = array( 'readonlytext', $wgReadOnly );
1044 global $wgEmailConfirmToEdit, $wgUser;
1046 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() )
1048 $errors[] = array( 'confirmedittext' );
1051 if ( $user->isBlockedFrom( $this ) ) {
1052 $block = $user->mBlock
;
1054 // This is from OutputPage::blockedPage
1055 // Copied at r23888 by werdna
1057 $id = $user->blockedBy();
1058 $reason = $user->blockedFor();
1059 if( $reason == '' ) {
1060 $reason = wfMsg( 'blockednoreason' );
1064 if ( is_numeric( $id ) ) {
1065 $name = User
::whoIs( $id );
1070 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1071 $blockid = $block->mId
;
1072 $blockExpiry = $user->mBlock
->mExpiry
;
1073 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1075 if ( $blockExpiry == 'infinity' ) {
1076 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1077 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1079 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1080 if ( strpos( $option, ':' ) == false )
1083 list ($show, $value) = explode( ":", $option );
1085 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1086 $blockExpiry = $show;
1091 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1094 $intended = $user->mBlock
->mAddress
;
1096 $errors[] = array ( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1103 * Can $user perform $action on this page?
1104 * This is an internal function, which checks ONLY that previously checked by userCan (i.e. it leaves out checks on wfReadOnly() and blocks)
1105 * @param string $action action that permission needs to be checked for
1106 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1107 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1109 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1110 $fname = 'Title::userCan';
1111 wfProfileIn( $fname );
1115 // Use getUserPermissionsErrors instead
1116 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1117 return $result ?
array() : array( array( 'badaccess-group0' ) );
1120 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1121 if ($result != array() && is_array($result) && !is_array($result[0]))
1122 $errors[] = $result; # A single array representing an error
1123 else if (is_array($result) && is_array($result[0]))
1124 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1125 else if ($result != '' && $result != null && $result !== true && $result !== false)
1126 $errors[] = array($result); # A string representing a message-id
1127 else if ($result === false )
1128 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1131 if( NS_SPECIAL
== $this->mNamespace
) {
1132 $errors[] = array('ns-specialprotected');
1135 if ( $this->isNamespaceProtected() ) {
1136 $ns = $this->getNamespace() == NS_MAIN
1137 ?
wfMsg( 'nstab-main' )
1138 : $this->getNsText();
1139 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1140 ?
array('protectedinterface')
1141 : array( 'namespaceprotected', $ns ) );
1144 if( $this->mDbkeyform
== '_' ) {
1145 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1146 $errors[] = array('badaccess-group0');
1149 # protect css/js subpages of user pages
1150 # XXX: this might be better using restrictions
1151 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1152 if( $this->isCssJsSubpage()
1153 && !$user->isAllowed('editusercssjs')
1154 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1155 $errors[] = array('customcssjsprotected');
1158 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1159 # We /could/ use the protection level on the source page, but it's fairly ugly
1160 # as we have to establish a precedence hierarchy for pages included by multiple
1161 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1162 # as they could remove the protection anyway.
1163 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1164 # Cascading protection depends on more than this page...
1165 # Several cascading protected pages may include this page...
1166 # Check each cascading level
1167 # This is only for protection restrictions, not for all actions
1168 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1169 foreach( $restrictions[$action] as $right ) {
1170 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1171 if( '' != $right && !$user->isAllowed( $right ) ) {
1173 foreach( $cascadingSources as $page )
1174 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1175 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1181 foreach( $this->getRestrictions($action) as $right ) {
1182 // Backwards compatibility, rewrite sysop -> protect
1183 if ( $right == 'sysop' ) {
1186 if( '' != $right && !$user->isAllowed( $right ) ) {
1187 $errors[] = array( 'protectedpagetext', $right );
1191 if ($action == 'protect') {
1192 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1193 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1198 if ($action == 'create') {
1199 $title_protection = $this->getTitleProtection();
1201 if (is_array($title_protection)) {
1202 extract($title_protection);
1204 if ($pt_create_perm == 'sysop')
1205 $pt_create_perm = 'protect';
1207 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1208 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1212 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1213 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1214 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1216 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1217 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1218 } elseif ( !$user->isAllowed( $action ) ) {
1221 global $wgGroupPermissions;
1222 foreach( $wgGroupPermissions as $key => $value ) {
1223 if( isset( $value[$action] ) && $value[$action] == true ) {
1224 $groupName = User
::getGroupName( $key );
1225 $groupPage = User
::getGroupPage( $key );
1227 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1229 $groups[] = $groupName;
1233 $n = count( $groups );
1234 $groups = implode( ', ', $groups );
1239 $return = array( "badaccess-group$n", $groups );
1242 $return = array( 'badaccess-groups', $groups );
1244 $errors[] = $return;
1247 wfProfileOut( $fname );
1252 * Is this title subject to title protection?
1253 * @return mixed An associative array representing any existent title
1254 * protection, or false if there's none.
1256 private function getTitleProtection() {
1257 // Can't protect pages in special namespaces
1258 if ( $this->getNamespace() < 0 ) {
1262 $dbr = wfGetDB( DB_SLAVE
);
1263 $res = $dbr->select( 'protected_titles', '*',
1264 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBKey()) );
1266 if ($row = $dbr->fetchRow( $res )) {
1273 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1274 global $wgGroupPermissions,$wgUser,$wgContLang;
1276 if ($create_perm == implode(',',$this->getRestrictions('create'))
1277 && $expiry == $this->mRestrictionsExpiry
) {
1282 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBKey() );
1284 $dbw = wfGetDB( DB_MASTER
);
1286 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1288 $expiry_description = '';
1289 if ( $encodedExpiry != 'infinity' ) {
1290 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1293 # Update protection table
1294 if ($create_perm != '' ) {
1295 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1296 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1297 , 'pt_create_perm' => $create_perm
1298 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1299 , 'pt_expiry' => $encodedExpiry
1300 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1302 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1303 'pt_title' => $title ), __METHOD__
);
1305 # Update the protection log
1306 $log = new LogPage( 'protect' );
1308 if( $create_perm ) {
1309 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1311 $log->addEntry( 'unprotect', $this, $reason );
1318 * Remove any title protection (due to page existing
1320 public function deleteTitleProtection() {
1321 $dbw = wfGetDB( DB_MASTER
);
1323 $dbw->delete( 'protected_titles',
1324 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBKey()), __METHOD__
);
1328 * Can $wgUser edit this page?
1330 * @deprecated use userCan('edit')
1332 public function userCanEdit( $doExpensiveQueries = true ) {
1333 return $this->userCan( 'edit', $doExpensiveQueries );
1337 * Can $wgUser create this page?
1339 * @deprecated use userCan('create')
1341 public function userCanCreate( $doExpensiveQueries = true ) {
1342 return $this->userCan( 'create', $doExpensiveQueries );
1346 * Can $wgUser move this page?
1348 * @deprecated use userCan('move')
1350 public function userCanMove( $doExpensiveQueries = true ) {
1351 return $this->userCan( 'move', $doExpensiveQueries );
1355 * Would anybody with sufficient privileges be able to move this page?
1356 * Some pages just aren't movable.
1360 public function isMovable() {
1361 return Namespace::isMovable( $this->getNamespace() )
1362 && $this->getInterwiki() == '';
1366 * Can $wgUser read this page?
1368 * @todo fold these checks into userCan()
1370 public function userCanRead() {
1374 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1375 if ( $result !== null ) {
1379 if( $wgUser->isAllowed( 'read' ) ) {
1382 global $wgWhitelistRead;
1385 * Always grant access to the login page.
1386 * Even anons need to be able to log in.
1388 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1393 * Bail out if there isn't whitelist
1395 if( !is_array($wgWhitelistRead) ) {
1400 * Check for explicit whitelisting
1402 $name = $this->getPrefixedText();
1403 if( in_array( $name, $wgWhitelistRead, true ) )
1407 * Old settings might have the title prefixed with
1408 * a colon for main-namespace pages
1410 if( $this->getNamespace() == NS_MAIN
) {
1411 if( in_array( ':' . $name, $wgWhitelistRead ) )
1416 * If it's a special page, ditch the subpage bit
1419 if( $this->getNamespace() == NS_SPECIAL
) {
1420 $name = $this->getDBKey();
1421 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1422 if ( $name === false ) {
1423 # Invalid special page, but we show standard login required message
1427 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1428 if( in_array( $pure, $wgWhitelistRead, true ) )
1437 * Is this a talk page of some sort?
1440 public function isTalkPage() {
1441 return Namespace::isTalk( $this->getNamespace() );
1445 * Is this a subpage?
1448 public function isSubpage() {
1449 global $wgNamespacesWithSubpages;
1451 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1452 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1459 * Could this page contain custom CSS or JavaScript, based
1464 public function isCssOrJsPage() {
1465 return $this->mNamespace
== NS_MEDIAWIKI
1466 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1470 * Is this a .css or .js subpage of a user page?
1473 public function isCssJsSubpage() {
1474 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1477 * Is this a *valid* .css or .js subpage of a user page?
1478 * Check that the corresponding skin exists
1480 public function isValidCssJsSubpage() {
1481 if ( $this->isCssJsSubpage() ) {
1482 $skinNames = Skin
::getSkinNames();
1483 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1489 * Trim down a .css or .js subpage title to get the corresponding skin name
1491 public function getSkinFromCssJsSubpage() {
1492 $subpage = explode( '/', $this->mTextform
);
1493 $subpage = $subpage[ count( $subpage ) - 1 ];
1494 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1497 * Is this a .css subpage of a user page?
1500 public function isCssSubpage() {
1501 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1504 * Is this a .js subpage of a user page?
1507 public function isJsSubpage() {
1508 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1511 * Protect css/js subpages of user pages: can $wgUser edit
1515 * @todo XXX: this might be better using restrictions
1517 public function userCanEditCssJsSubpage() {
1519 return ( $wgUser->isAllowed('editusercssjs') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1523 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1525 * @return bool If the page is subject to cascading restrictions.
1527 public function isCascadeProtected() {
1528 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1529 return ( $sources > 0 );
1533 * Cascading protection: Get the source of any cascading restrictions on this page.
1535 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1536 * @return array( mixed title array, restriction array)
1537 * 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.
1538 * The restriction array is an array of each type, each of which contains an array of unique groups
1540 public function getCascadeProtectionSources( $get_pages = true ) {
1541 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1543 # Define our dimension of restrictions types
1544 $pagerestrictions = array();
1545 foreach( $wgRestrictionTypes as $action )
1546 $pagerestrictions[$action] = array();
1548 if (!$wgEnableCascadingProtection)
1549 return array( false, $pagerestrictions );
1551 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1552 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1553 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1554 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1557 wfProfileIn( __METHOD__
);
1559 $dbr = wfGetDb( DB_SLAVE
);
1561 if ( $this->getNamespace() == NS_IMAGE
) {
1562 $tables = array ('imagelinks', 'page_restrictions');
1563 $where_clauses = array(
1564 'il_to' => $this->getDBkey(),
1566 'pr_cascade' => 1 );
1568 $tables = array ('templatelinks', 'page_restrictions');
1569 $where_clauses = array(
1570 'tl_namespace' => $this->getNamespace(),
1571 'tl_title' => $this->getDBkey(),
1573 'pr_cascade' => 1 );
1577 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1578 $where_clauses[] = 'page_id=pr_page';
1581 $cols = array( 'pr_expiry' );
1584 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1586 $sources = $get_pages ?
array() : false;
1587 $now = wfTimestampNow();
1588 $purgeExpired = false;
1590 while( $row = $dbr->fetchObject( $res ) ) {
1591 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1592 if( $expiry > $now ) {
1594 $page_id = $row->pr_page
;
1595 $page_ns = $row->page_namespace
;
1596 $page_title = $row->page_title
;
1597 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1598 # Add groups needed for each restriction type if its not already there
1599 # Make sure this restriction type still exists
1600 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1601 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1607 // Trigger lazy purge of expired restrictions from the db
1608 $purgeExpired = true;
1611 if( $purgeExpired ) {
1612 Title
::purgeExpiredRestrictions();
1615 wfProfileOut( __METHOD__
);
1618 $this->mCascadeSources
= $sources;
1619 $this->mCascadingRestrictions
= $pagerestrictions;
1621 $this->mHasCascadingRestrictions
= $sources;
1624 return array( $sources, $pagerestrictions );
1627 function areRestrictionsCascading() {
1628 if (!$this->mRestrictionsLoaded
) {
1629 $this->loadRestrictions();
1632 return $this->mCascadeRestriction
;
1636 * Loads a string into mRestrictions array
1637 * @param resource $res restrictions as an SQL result.
1639 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1640 $dbr = wfGetDb( DB_SLAVE
);
1642 $this->mRestrictions
['edit'] = array();
1643 $this->mRestrictions
['move'] = array();
1645 # Backwards-compatibility: also load the restrictions from the page record (old format).
1647 if ( $oldFashionedRestrictions == NULL ) {
1648 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1651 if ($oldFashionedRestrictions != '') {
1653 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1654 $temp = explode( '=', trim( $restrict ) );
1655 if(count($temp) == 1) {
1656 // old old format should be treated as edit/move restriction
1657 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1658 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1660 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1664 $this->mOldRestrictions
= true;
1665 $this->mCascadeRestriction
= false;
1666 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1670 if( $dbr->numRows( $res ) ) {
1671 # Current system - load second to make them override.
1672 $now = wfTimestampNow();
1673 $purgeExpired = false;
1675 while ($row = $dbr->fetchObject( $res ) ) {
1676 # Cycle through all the restrictions.
1678 // This code should be refactored, now that it's being used more generally,
1679 // But I don't really see any harm in leaving it in Block for now -werdna
1680 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1682 // Only apply the restrictions if they haven't expired!
1683 if ( !$expiry ||
$expiry > $now ) {
1684 $this->mRestrictionsExpiry
= $expiry;
1685 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1687 $this->mCascadeRestriction |
= $row->pr_cascade
;
1689 // Trigger a lazy purge of expired restrictions
1690 $purgeExpired = true;
1694 if( $purgeExpired ) {
1695 Title
::purgeExpiredRestrictions();
1699 $this->mRestrictionsLoaded
= true;
1702 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1703 if( !$this->mRestrictionsLoaded
) {
1704 if ($this->exists()) {
1705 $dbr = wfGetDB( DB_SLAVE
);
1707 $res = $dbr->select( 'page_restrictions', '*',
1708 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1710 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1712 $title_protection = $this->getTitleProtection();
1714 if (is_array($title_protection)) {
1715 extract($title_protection);
1717 $now = wfTimestampNow();
1718 $expiry = Block
::decodeExpiry($pt_expiry);
1720 if (!$expiry ||
$expiry > $now) {
1721 // Apply the restrictions
1722 $this->mRestrictionsExpiry
= $expiry;
1723 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1724 } else { // Get rid of the old restrictions
1725 Title
::purgeExpiredRestrictions();
1728 $this->mRestrictionsLoaded
= true;
1734 * Purge expired restrictions from the page_restrictions table
1736 static function purgeExpiredRestrictions() {
1737 $dbw = wfGetDB( DB_MASTER
);
1738 $dbw->delete( 'page_restrictions',
1739 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1742 $dbw->delete( 'protected_titles',
1743 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1748 * Accessor/initialisation for mRestrictions
1750 * @param string $action action that permission needs to be checked for
1751 * @return array the array of groups allowed to edit this article
1753 public function getRestrictions( $action ) {
1754 if( !$this->mRestrictionsLoaded
) {
1755 $this->loadRestrictions();
1757 return isset( $this->mRestrictions
[$action] )
1758 ?
$this->mRestrictions
[$action]
1763 * Is there a version of this page in the deletion archive?
1764 * @return int the number of archived revisions
1766 public function isDeleted() {
1767 $fname = 'Title::isDeleted';
1768 if ( $this->getNamespace() < 0 ) {
1771 $dbr = wfGetDB( DB_SLAVE
);
1772 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1773 'ar_title' => $this->getDBkey() ), $fname );
1774 if( $this->getNamespace() == NS_IMAGE
) {
1775 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1776 array( 'fa_name' => $this->getDBkey() ), $fname );
1783 * Get the article ID for this Title from the link cache,
1784 * adding it if necessary
1785 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1787 * @return int the ID
1789 public function getArticleID( $flags = 0 ) {
1790 $linkCache =& LinkCache
::singleton();
1791 if ( $flags & GAID_FOR_UPDATE
) {
1792 $oldUpdate = $linkCache->forUpdate( true );
1793 $this->mArticleID
= $linkCache->addLinkObj( $this );
1794 $linkCache->forUpdate( $oldUpdate );
1796 if ( -1 == $this->mArticleID
) {
1797 $this->mArticleID
= $linkCache->addLinkObj( $this );
1800 return $this->mArticleID
;
1803 public function getLatestRevID() {
1804 if ($this->mLatestID
!== false)
1805 return $this->mLatestID
;
1807 $db = wfGetDB(DB_SLAVE
);
1808 return $this->mLatestID
= $db->selectField( 'revision',
1810 array('rev_page' => $this->getArticleID()),
1811 'Title::getLatestRevID' );
1815 * This clears some fields in this object, and clears any associated
1816 * keys in the "bad links" section of the link cache.
1818 * - This is called from Article::insertNewArticle() to allow
1819 * loading of the new page_id. It's also called from
1820 * Article::doDeleteArticle()
1822 * @param int $newid the new Article ID
1824 public function resetArticleID( $newid ) {
1825 $linkCache =& LinkCache
::singleton();
1826 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1828 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1829 else { $this->mArticleID
= $newid; }
1830 $this->mRestrictionsLoaded
= false;
1831 $this->mRestrictions
= array();
1835 * Updates page_touched for this page; called from LinksUpdate.php
1836 * @return bool true if the update succeded
1838 public function invalidateCache() {
1839 global $wgUseFileCache;
1841 if ( wfReadOnly() ) {
1845 $dbw = wfGetDB( DB_MASTER
);
1846 $success = $dbw->update( 'page',
1848 'page_touched' => $dbw->timestamp()
1849 ), array( /* WHERE */
1850 'page_namespace' => $this->getNamespace() ,
1851 'page_title' => $this->getDBkey()
1852 ), 'Title::invalidateCache'
1855 if ($wgUseFileCache) {
1856 $cache = new HTMLFileCache($this);
1857 @unlink
($cache->fileCacheName());
1864 * Prefix some arbitrary text with the namespace or interwiki prefix
1867 * @param string $name the text
1868 * @return string the prefixed text
1871 /* private */ function prefix( $name ) {
1873 if ( '' != $this->mInterwiki
) {
1874 $p = $this->mInterwiki
. ':';
1876 if ( 0 != $this->mNamespace
) {
1877 $p .= $this->getNsText() . ':';
1883 * Secure and split - main initialisation function for this object
1885 * Assumes that mDbkeyform has been set, and is urldecoded
1886 * and uses underscores, but not otherwise munged. This function
1887 * removes illegal characters, splits off the interwiki and
1888 * namespace prefixes, sets the other forms, and canonicalizes
1890 * @return bool true on success
1892 private function secureAndSplit() {
1893 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1896 static $rxTc = false;
1898 # Matching titles will be held as illegal.
1900 # Any character not allowed is forbidden...
1901 '[^' . Title
::legalChars() . ']' .
1902 # URL percent encoding sequences interfere with the ability
1903 # to round-trip titles -- you can't link to them consistently.
1904 '|%[0-9A-Fa-f]{2}' .
1905 # XML/HTML character references produce similar issues.
1906 '|&[A-Za-z0-9\x80-\xff]+;' .
1908 '|&#x[0-9A-Fa-f]+;' .
1912 $this->mInterwiki
= $this->mFragment
= '';
1913 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1915 $dbkey = $this->mDbkeyform
;
1917 # Strip Unicode bidi override characters.
1918 # Sometimes they slip into cut-n-pasted page titles, where the
1919 # override chars get included in list displays.
1920 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1921 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1923 # Clean up whitespace
1925 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1926 $dbkey = trim( $dbkey, '_' );
1928 if ( '' == $dbkey ) {
1932 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1933 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1937 $this->mDbkeyform
= $dbkey;
1939 # Initial colon indicates main namespace rather than specified default
1940 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1941 if ( ':' == $dbkey{0} ) {
1942 $this->mNamespace
= NS_MAIN
;
1943 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1944 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1947 # Namespace or interwiki prefix
1951 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1953 if ( $ns = $wgContLang->getNsIndex( $p )) {
1954 # Ordinary namespace
1956 $this->mNamespace
= $ns;
1957 } elseif( $this->getInterwikiLink( $p ) ) {
1959 # Can't make a local interwiki link to an interwiki link.
1960 # That's just crazy!
1966 $this->mInterwiki
= $wgContLang->lc( $p );
1968 # Redundant interwiki prefix to the local wiki
1969 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1970 if( $dbkey == '' ) {
1971 # Can't have an empty self-link
1974 $this->mInterwiki
= '';
1976 # Do another namespace split...
1980 # If there's an initial colon after the interwiki, that also
1981 # resets the default namespace
1982 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1983 $this->mNamespace
= NS_MAIN
;
1984 $dbkey = substr( $dbkey, 1 );
1987 # If there's no recognized interwiki or namespace,
1988 # then let the colon expression be part of the title.
1993 # We already know that some pages won't be in the database!
1995 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
1996 $this->mArticleID
= 0;
1998 $fragment = strstr( $dbkey, '#' );
1999 if ( false !== $fragment ) {
2000 $this->setFragment( $fragment );
2001 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2002 # remove whitespace again: prevents "Foo_bar_#"
2003 # becoming "Foo_bar_"
2004 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2007 # Reject illegal characters.
2009 if( preg_match( $rxTc, $dbkey ) ) {
2014 * Pages with "/./" or "/../" appearing in the URLs will
2015 * often be unreachable due to the way web browsers deal
2016 * with 'relative' URLs. Forbid them explicitly.
2018 if ( strpos( $dbkey, '.' ) !== false &&
2019 ( $dbkey === '.' ||
$dbkey === '..' ||
2020 strpos( $dbkey, './' ) === 0 ||
2021 strpos( $dbkey, '../' ) === 0 ||
2022 strpos( $dbkey, '/./' ) !== false ||
2023 strpos( $dbkey, '/../' ) !== false ) )
2029 * Magic tilde sequences? Nu-uh!
2031 if( strpos( $dbkey, '~~~' ) !== false ) {
2036 * Limit the size of titles to 255 bytes.
2037 * This is typically the size of the underlying database field.
2038 * We make an exception for special pages, which don't need to be stored
2039 * in the database, and may edge over 255 bytes due to subpage syntax
2040 * for long titles, e.g. [[Special:Block/Long name]]
2042 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2043 strlen( $dbkey ) > 512 )
2049 * Normally, all wiki links are forced to have
2050 * an initial capital letter so [[foo]] and [[Foo]]
2051 * point to the same place.
2053 * Don't force it for interwikis, since the other
2054 * site might be case-sensitive.
2056 $this->mUserCaseDBKey
= $dbkey;
2057 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2058 $dbkey = $wgContLang->ucfirst( $dbkey );
2062 * Can't make a link to a namespace alone...
2063 * "empty" local links can only be self-links
2064 * with a fragment identifier.
2067 $this->mInterwiki
== '' &&
2068 $this->mNamespace
!= NS_MAIN
) {
2071 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2072 // IP names are not allowed for accounts, and can only be referring to
2073 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2074 // there are numerous ways to present the same IP. Having sp:contribs scan
2075 // them all is silly and having some show the edits and others not is
2076 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2077 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2078 IP
::sanitizeIP( $dbkey ) : $dbkey;
2079 // Any remaining initial :s are illegal.
2080 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2085 $this->mDbkeyform
= $dbkey;
2086 $this->mUrlform
= wfUrlencode( $dbkey );
2088 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2094 * Set the fragment for this title
2095 * This is kind of bad, since except for this rarely-used function, Title objects
2096 * are immutable. The reason this is here is because it's better than setting the
2097 * members directly, which is what Linker::formatComment was doing previously.
2099 * @param string $fragment text
2100 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2102 public function setFragment( $fragment ) {
2103 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2107 * Get a Title object associated with the talk page of this article
2108 * @return Title the object for the talk page
2110 public function getTalkPage() {
2111 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2115 * Get a title object associated with the subject page of this
2118 * @return Title the object for the subject page
2120 public function getSubjectPage() {
2121 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2125 * Get an array of Title objects linking to this Title
2126 * Also stores the IDs in the link cache.
2128 * WARNING: do not use this function on arbitrary user-supplied titles!
2129 * On heavily-used templates it will max out the memory.
2131 * @param string $options may be FOR UPDATE
2132 * @return array the Title objects linking here
2134 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2135 $linkCache =& LinkCache
::singleton();
2138 $db = wfGetDB( DB_MASTER
);
2140 $db = wfGetDB( DB_SLAVE
);
2143 $res = $db->select( array( 'page', $table ),
2144 array( 'page_namespace', 'page_title', 'page_id' ),
2146 "{$prefix}_from=page_id",
2147 "{$prefix}_namespace" => $this->getNamespace(),
2148 "{$prefix}_title" => $this->getDbKey() ),
2149 'Title::getLinksTo',
2153 if ( $db->numRows( $res ) ) {
2154 while ( $row = $db->fetchObject( $res ) ) {
2155 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2156 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
2157 $retVal[] = $titleObj;
2161 $db->freeResult( $res );
2166 * Get an array of Title objects using this Title as a template
2167 * Also stores the IDs in the link cache.
2169 * WARNING: do not use this function on arbitrary user-supplied titles!
2170 * On heavily-used templates it will max out the memory.
2172 * @param string $options may be FOR UPDATE
2173 * @return array the Title objects linking here
2175 public function getTemplateLinksTo( $options = '' ) {
2176 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2180 * Get an array of Title objects referring to non-existent articles linked from this page
2182 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2183 * @param string $options may be FOR UPDATE
2184 * @return array the Title objects
2186 public function getBrokenLinksFrom( $options = '' ) {
2187 if ( $this->getArticleId() == 0 ) {
2188 # All links from article ID 0 are false positives
2193 $db = wfGetDB( DB_MASTER
);
2195 $db = wfGetDB( DB_SLAVE
);
2198 $res = $db->safeQuery(
2199 "SELECT pl_namespace, pl_title
2202 ON pl_namespace=page_namespace
2203 AND pl_title=page_title
2205 AND page_namespace IS NULL
2207 $db->tableName( 'pagelinks' ),
2208 $db->tableName( 'page' ),
2209 $this->getArticleId(),
2213 if ( $db->numRows( $res ) ) {
2214 while ( $row = $db->fetchObject( $res ) ) {
2215 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2218 $db->freeResult( $res );
2224 * Get a list of URLs to purge from the Squid cache when this
2227 * @return array the URLs
2229 public function getSquidURLs() {
2233 $this->getInternalURL(),
2234 $this->getInternalURL( 'action=history' )
2237 // purge variant urls as well
2238 if($wgContLang->hasVariants()){
2239 $variants = $wgContLang->getVariants();
2240 foreach($variants as $vCode){
2241 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2242 $urls[] = $this->getInternalURL('',$vCode);
2249 public function purgeSquid() {
2251 if ( $wgUseSquid ) {
2252 $urls = $this->getSquidURLs();
2253 $u = new SquidUpdate( $urls );
2259 * Move this page without authentication
2260 * @param Title &$nt the new page Title
2262 public function moveNoAuth( &$nt ) {
2263 return $this->moveTo( $nt, false );
2267 * Check whether a given move operation would be valid.
2268 * Returns true if ok, or a message key string for an error message
2269 * if invalid. (Scarrrrry ugly interface this.)
2270 * @param Title &$nt the new title
2271 * @param bool $auth indicates whether $wgUser's permissions
2273 * @return mixed true on success, message name on failure
2275 public function isValidMoveOperation( &$nt, $auth = true ) {
2276 if( !$this or !$nt ) {
2277 return 'badtitletext';
2279 if( $this->equals( $nt ) ) {
2282 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2283 return 'immobile_namespace';
2286 $oldid = $this->getArticleID();
2287 $newid = $nt->getArticleID();
2289 if ( strlen( $nt->getDBkey() ) < 1 ) {
2290 return 'articleexists';
2292 if ( ( '' == $this->getDBkey() ) ||
2294 ( '' == $nt->getDBkey() ) ) {
2295 return 'badarticleerror';
2299 !$this->userCan( 'edit' ) ||
!$nt->userCan( 'edit' ) ||
2300 !$this->userCan( 'move' ) ||
!$nt->userCan( 'move' ) ) ) {
2301 return 'protectedpage';
2306 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
2307 return 'hookaborted';
2310 # The move is allowed only if (1) the target doesn't exist, or
2311 # (2) the target is a redirect to the source, and has no history
2312 # (so we can undo bad moves right after they're done).
2314 if ( 0 != $newid ) { # Target exists; check for validity
2315 if ( ! $this->isValidMoveTarget( $nt ) ) {
2316 return 'articleexists';
2319 $tp = $nt->getTitleProtection();
2320 if ( $tp and !$wgUser->isAllowed( $tp['pt_create_perm'] ) ) {
2321 return 'cantmove-titleprotected';
2328 * Move a title to a new location
2329 * @param Title &$nt the new title
2330 * @param bool $auth indicates whether $wgUser's permissions
2332 * @param string $reason The reason for the move
2333 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2334 * Ignored if the user doesn't have the suppressredirect right.
2335 * @return mixed true on success, message name on failure
2337 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2338 $err = $this->isValidMoveOperation( $nt, $auth );
2339 if( is_string( $err ) ) {
2343 $pageid = $this->getArticleID();
2344 if( $nt->exists() ) {
2345 $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2346 $pageCountChange = ($createRedirect ?
0 : -1);
2347 } else { # Target didn't exist, do normal move.
2348 $this->moveToNewTitle( $nt, $reason, $createRedirect );
2349 $pageCountChange = ($createRedirect ?
1 : 0);
2351 $redirid = $this->getArticleID();
2353 // Category memberships include a sort key which may be customized.
2354 // If it's left as the default (the page title), we need to update
2355 // the sort key to match the new title.
2357 // Be careful to avoid resetting cl_timestamp, which may disturb
2358 // time-based lists on some sites.
2360 // Warning -- if the sort key is *explicitly* set to the old title,
2361 // we can't actually distinguish it from a default here, and it'll
2362 // be set to the new title even though it really shouldn't.
2363 // It'll get corrected on the next edit, but resetting cl_timestamp.
2364 $dbw = wfGetDB( DB_MASTER
);
2365 $dbw->update( 'categorylinks',
2367 'cl_sortkey' => $nt->getPrefixedText(),
2368 'cl_timestamp=cl_timestamp' ),
2370 'cl_from' => $pageid,
2371 'cl_sortkey' => $this->getPrefixedText() ),
2376 $oldnamespace = $this->getNamespace() & ~
1;
2377 $newnamespace = $nt->getNamespace() & ~
1;
2378 $oldtitle = $this->getDBkey();
2379 $newtitle = $nt->getDBkey();
2381 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2382 WatchedItem
::duplicateEntries( $this, $nt );
2385 # Update search engine
2386 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2388 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2392 if( $this->isContentPage() && !$nt->isContentPage() ) {
2393 # No longer a content page
2394 # Not viewed, edited, removing
2395 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2396 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2397 # Now a content page
2398 # Not viewed, edited, adding
2399 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2400 } elseif( $pageCountChange ) {
2402 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2409 # Update message cache for interface messages
2410 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2411 global $wgMessageCache;
2412 $newarticle = new Article( $nt );
2413 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2417 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2422 * Move page to a title which is at present a redirect to the
2425 * @param Title &$nt the page to move to, which should currently
2427 * @param string $reason The reason for the move
2428 * @param bool $createRedirect Whether to leave a redirect at the old title.
2429 * Ignored if the user doesn't have the suppressredirect right
2431 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2432 global $wgUseSquid, $wgUser;
2433 $fname = 'Title::moveOverExistingRedirect';
2434 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2437 $comment .= ": $reason";
2440 $now = wfTimestampNow();
2441 $newid = $nt->getArticleID();
2442 $oldid = $this->getArticleID();
2443 $dbw = wfGetDB( DB_MASTER
);
2444 $linkCache =& LinkCache
::singleton();
2446 # Delete the old redirect. We don't save it to history since
2447 # by definition if we've got here it's rather uninteresting.
2448 # We have to remove it so that the next step doesn't trigger
2449 # a conflict on the unique namespace+title index...
2450 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2452 # Save a null revision in the page's history notifying of the move
2453 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2454 $nullRevId = $nullRevision->insertOn( $dbw );
2456 # Change the name of the target page:
2457 $dbw->update( 'page',
2459 'page_touched' => $dbw->timestamp($now),
2460 'page_namespace' => $nt->getNamespace(),
2461 'page_title' => $nt->getDBkey(),
2462 'page_latest' => $nullRevId,
2464 /* WHERE */ array( 'page_id' => $oldid ),
2467 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2469 # Recreate the redirect, this time in the other direction.
2470 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2472 $mwRedir = MagicWord
::get( 'redirect' );
2473 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2474 $redirectArticle = new Article( $this );
2475 $newid = $redirectArticle->insertOn( $dbw );
2476 $redirectRevision = new Revision( array(
2478 'comment' => $comment,
2479 'text' => $redirectText ) );
2480 $redirectRevision->insertOn( $dbw );
2481 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2482 $linkCache->clearLink( $this->getPrefixedDBkey() );
2484 # Now, we record the link from the redirect to the new title.
2485 # It should have no other outgoing links...
2486 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2487 $dbw->insert( 'pagelinks',
2489 'pl_from' => $newid,
2490 'pl_namespace' => $nt->getNamespace(),
2491 'pl_title' => $nt->getDbKey() ),
2496 $log = new LogPage( 'move' );
2497 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2500 if ( $wgUseSquid ) {
2501 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2502 $u = new SquidUpdate( $urls );
2508 * Move page to non-existing title.
2509 * @param Title &$nt the new Title
2510 * @param string $reason The reason for the move
2511 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2512 * Ignored if the user doesn't have the suppressredirect right
2514 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2515 global $wgUseSquid, $wgUser;
2516 $fname = 'MovePageForm::moveToNewTitle';
2517 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2519 $comment .= ": $reason";
2522 $newid = $nt->getArticleID();
2523 $oldid = $this->getArticleID();
2524 $dbw = wfGetDB( DB_MASTER
);
2525 $now = $dbw->timestamp();
2526 $linkCache =& LinkCache
::singleton();
2528 # Save a null revision in the page's history notifying of the move
2529 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2530 $nullRevId = $nullRevision->insertOn( $dbw );
2533 $dbw->update( 'page',
2535 'page_touched' => $now,
2536 'page_namespace' => $nt->getNamespace(),
2537 'page_title' => $nt->getDBkey(),
2538 'page_latest' => $nullRevId,
2540 /* WHERE */ array( 'page_id' => $oldid ),
2544 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2546 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2549 $mwRedir = MagicWord
::get( 'redirect' );
2550 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2551 $redirectArticle = new Article( $this );
2552 $newid = $redirectArticle->insertOn( $dbw );
2553 $redirectRevision = new Revision( array(
2555 'comment' => $comment,
2556 'text' => $redirectText ) );
2557 $redirectRevision->insertOn( $dbw );
2558 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2559 $linkCache->clearLink( $this->getPrefixedDBkey() );
2560 # Record the just-created redirect's linking to the page
2561 $dbw->insert( 'pagelinks',
2563 'pl_from' => $newid,
2564 'pl_namespace' => $nt->getNamespace(),
2565 'pl_title' => $nt->getDBkey() ),
2570 $log = new LogPage( 'move' );
2571 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2573 # Purge caches as per article creation
2574 Article
::onArticleCreate( $nt );
2576 # Purge old title from squid
2577 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2578 $this->purgeSquid();
2582 * Checks if $this can be moved to a given Title
2583 * - Selects for update, so don't call it unless you mean business
2585 * @param Title &$nt the new title to check
2587 public function isValidMoveTarget( $nt ) {
2589 $fname = 'Title::isValidMoveTarget';
2590 $dbw = wfGetDB( DB_MASTER
);
2593 $id = $nt->getArticleID();
2594 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2595 array( 'page_is_redirect','old_text','old_flags' ),
2596 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2597 $fname, 'FOR UPDATE' );
2599 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2601 wfDebug( __METHOD__
. ": not a redirect\n" );
2604 $text = Revision
::getRevisionText( $obj );
2606 # Does the redirect point to the source?
2607 # Or is it a broken self-redirect, usually caused by namespace collisions?
2609 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2610 $redirTitle = Title
::newFromText( $m[1] );
2611 if( !is_object( $redirTitle ) ||
2612 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2613 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2614 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2619 wfDebug( __METHOD__
. ": failsafe\n" );
2623 # Does the article have a history?
2624 $row = $dbw->selectRow( array( 'page', 'revision'),
2626 array( 'page_namespace' => $nt->getNamespace(),
2627 'page_title' => $nt->getDBkey(),
2628 'page_id=rev_page AND page_latest != rev_id'
2629 ), $fname, 'FOR UPDATE'
2632 # Return true if there was no history
2633 return $row === false;
2637 * Can this title be added to a user's watchlist?
2641 public function isWatchable() {
2642 return !$this->isExternal()
2643 && Namespace::isWatchable( $this->getNamespace() );
2647 * Get categories to which this Title belongs and return an array of
2648 * categories' names.
2650 * @return array an array of parents in the form:
2651 * $parent => $currentarticle
2653 public function getParentCategories() {
2656 $titlekey = $this->getArticleId();
2657 $dbr = wfGetDB( DB_SLAVE
);
2658 $categorylinks = $dbr->tableName( 'categorylinks' );
2661 $sql = "SELECT * FROM $categorylinks"
2662 ." WHERE cl_from='$titlekey'"
2663 ." AND cl_from <> '0'"
2664 ." ORDER BY cl_sortkey";
2666 $res = $dbr->query ( $sql ) ;
2668 if($dbr->numRows($res) > 0) {
2669 while ( $x = $dbr->fetchObject ( $res ) )
2670 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2671 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2672 $dbr->freeResult ( $res ) ;
2680 * Get a tree of parent categories
2681 * @param array $children an array with the children in the keys, to check for circular refs
2684 public function getParentCategoryTree( $children = array() ) {
2685 $parents = $this->getParentCategories();
2687 if($parents != '') {
2688 foreach($parents as $parent => $current) {
2689 if ( array_key_exists( $parent, $children ) ) {
2690 # Circular reference
2691 $stack[$parent] = array();
2693 $nt = Title
::newFromText($parent);
2695 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2707 * Get an associative array for selecting this title from
2712 public function pageCond() {
2713 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2717 * Get the revision ID of the previous revision
2719 * @param integer $revision Revision ID. Get the revision that was before this one.
2720 * @return integer $oldrevision|false
2722 public function getPreviousRevisionID( $revision ) {
2723 $dbr = wfGetDB( DB_SLAVE
);
2724 return $dbr->selectField( 'revision', 'rev_id',
2725 'rev_page=' . intval( $this->getArticleId() ) .
2726 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2730 * Get the revision ID of the next revision
2732 * @param integer $revision Revision ID. Get the revision that was after this one.
2733 * @return integer $oldrevision|false
2735 public function getNextRevisionID( $revision ) {
2736 $dbr = wfGetDB( DB_SLAVE
);
2737 return $dbr->selectField( 'revision', 'rev_id',
2738 'rev_page=' . intval( $this->getArticleId() ) .
2739 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2743 * Get the number of revisions between the given revision IDs.
2745 * @param integer $old Revision ID.
2746 * @param integer $new Revision ID.
2747 * @return integer Number of revisions between these IDs.
2749 public function countRevisionsBetween( $old, $new ) {
2750 $dbr = wfGetDB( DB_SLAVE
);
2751 return $dbr->selectField( 'revision', 'count(*)',
2752 'rev_page = ' . intval( $this->getArticleId() ) .
2753 ' AND rev_id > ' . intval( $old ) .
2754 ' AND rev_id < ' . intval( $new ) );
2758 * Compare with another title.
2760 * @param Title $title
2763 public function equals( $title ) {
2764 // Note: === is necessary for proper matching of number-like titles.
2765 return $this->getInterwiki() === $title->getInterwiki()
2766 && $this->getNamespace() == $title->getNamespace()
2767 && $this->getDbkey() === $title->getDbkey();
2771 * Return a string representation of this title
2775 public function __toString() {
2776 return $this->getPrefixedText();
2780 * Check if page exists
2783 public function exists() {
2784 return $this->getArticleId() != 0;
2788 * Do we know that this title definitely exists, or should we otherwise
2789 * consider that it exists?
2793 public function isAlwaysKnown() {
2794 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
2795 // the full l10n of that language to be loaded. That takes much memory and
2796 // isn't needed. So we strip the language part away.
2797 // Also, extension messages which are not loaded, are shown as red, because
2798 // we don't call MessageCache::loadAllMessages.
2799 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
2800 return $this->isExternal()
2801 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2802 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
2806 * Update page_touched timestamps and send squid purge messages for
2807 * pages linking to this title. May be sent to the job queue depending
2808 * on the number of links. Typically called on create and delete.
2810 public function touchLinks() {
2811 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2814 if ( $this->getNamespace() == NS_CATEGORY
) {
2815 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2821 * Get the last touched timestamp
2823 public function getTouched() {
2824 $dbr = wfGetDB( DB_SLAVE
);
2825 $touched = $dbr->selectField( 'page', 'page_touched',
2827 'page_namespace' => $this->getNamespace(),
2828 'page_title' => $this->getDBkey()
2834 public function trackbackURL() {
2835 global $wgTitle, $wgScriptPath, $wgServer;
2837 return "$wgServer$wgScriptPath/trackback.php?article="
2838 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2841 public function trackbackRDF() {
2842 $url = htmlspecialchars($this->getFullURL());
2843 $title = htmlspecialchars($this->getText());
2844 $tburl = $this->trackbackURL();
2847 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2848 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2849 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2852 dc:identifier=\"$url\"
2854 trackback:ping=\"$tburl\" />
2859 * Generate strings used for xml 'id' names in monobook tabs
2862 public function getNamespaceKey() {
2864 switch ($this->getNamespace()) {
2867 return 'nstab-main';
2870 return 'nstab-user';
2872 return 'nstab-media';
2874 return 'nstab-special';
2876 case NS_PROJECT_TALK
:
2877 return 'nstab-project';
2880 return 'nstab-image';
2882 case NS_MEDIAWIKI_TALK
:
2883 return 'nstab-mediawiki';
2885 case NS_TEMPLATE_TALK
:
2886 return 'nstab-template';
2889 return 'nstab-help';
2891 case NS_CATEGORY_TALK
:
2892 return 'nstab-category';
2894 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2899 * Returns true if this title resolves to the named special page
2900 * @param string $name The special page name
2902 public function isSpecial( $name ) {
2903 if ( $this->getNamespace() == NS_SPECIAL
) {
2904 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2905 if ( $name == $thisName ) {
2913 * If the Title refers to a special page alias which is not the local default,
2914 * returns a new Title which points to the local default. Otherwise, returns $this.
2916 public function fixSpecialName() {
2917 if ( $this->getNamespace() == NS_SPECIAL
) {
2918 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2919 if ( $canonicalName ) {
2920 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2921 if ( $localName != $this->mDbkeyform
) {
2922 return Title
::makeTitle( NS_SPECIAL
, $localName );
2930 * Is this Title in a namespace which contains content?
2931 * In other words, is this a content page, for the purposes of calculating
2936 public function isContentPage() {
2937 return Namespace::isContent( $this->getNamespace() );