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 if ( !count( $ids ) ) {
213 $dbr = wfGetDB( DB_SLAVE
);
214 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
215 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
218 while ( $row = $dbr->fetchObject( $res ) ) {
219 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
225 * Create a new Title from a namespace index and a DB key.
226 * It's assumed that $ns and $title are *valid*, for instance when
227 * they came directly from the database or a special page name.
228 * For convenience, spaces are converted to underscores so that
229 * eg user_text fields can be used directly.
231 * @param int $ns the namespace of the article
232 * @param string $title the unprefixed database key form
233 * @return Title the new object
235 public static function &makeTitle( $ns, $title ) {
239 $t->mNamespace
= $ns = intval( $ns );
240 $t->mDbkeyform
= str_replace( ' ', '_', $title );
241 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
242 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
243 $t->mTextform
= str_replace( '_', ' ', $title );
248 * Create a new Title from a namespace index and a DB key.
249 * The parameters will be checked for validity, which is a bit slower
250 * than makeTitle() but safer for user-provided data.
252 * @param int $ns the namespace of the article
253 * @param string $title the database key form
254 * @return Title the new object, or NULL on an error
256 public static function makeTitleSafe( $ns, $title ) {
258 $t->mDbkeyform
= Title
::makeName( $ns, $title );
259 if( $t->secureAndSplit() ) {
267 * Create a new Title for the Main Page
268 * @return Title the new object
270 public static function newMainPage() {
271 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
272 // Don't give fatal errors if the message is broken
274 $title = Title
::newFromText( 'Main Page' );
280 * Extract a redirect destination from a string and return the
281 * Title, or null if the text doesn't contain a valid redirect
283 * @param string $text Text with possible redirect
286 public static function newFromRedirect( $text ) {
287 $redir = MagicWord
::get( 'redirect' );
288 if( $redir->matchStart( trim($text) ) ) {
289 // Extract the first link and see if it's usable
291 if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
292 // Strip preceding colon used to "escape" categories, etc.
293 // and URL-decode links
294 if( strpos( $m[1], '%' ) !== false ) {
295 // Match behavior of inline link parsing here;
296 // don't interpret + as " " most of the time!
297 // It might be safe to just use rawurldecode instead, though.
298 $m[1] = urldecode( ltrim( $m[1], ':' ) );
300 $title = Title
::newFromText( $m[1] );
301 // Redirects to Special:Userlogout are not permitted
302 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
309 #----------------------------------------------------------------------------
311 #----------------------------------------------------------------------------
314 * Get the prefixed DB key associated with an ID
315 * @param int $id the page_id of the article
316 * @return Title an object representing the article, or NULL
317 * if no such article was found
321 function nameOf( $id ) {
322 $fname = 'Title::nameOf';
323 $dbr = wfGetDB( DB_SLAVE
);
325 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
326 if ( $s === false ) { return NULL; }
328 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
333 * Get a regex character class describing the legal characters in a link
334 * @return string the list of characters, not delimited
336 public static function legalChars() {
337 global $wgLegalTitleChars;
338 return $wgLegalTitleChars;
342 * Get a string representation of a title suitable for
343 * including in a search index
345 * @param int $ns a namespace index
346 * @param string $title text-form main part
347 * @return string a stripped-down title string ready for the
350 public static function indexTitle( $ns, $title ) {
353 $lc = SearchEngine
::legalSearchChars() . '&#;';
354 $t = $wgContLang->stripForSearch( $title );
355 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
356 $t = $wgContLang->lc( $t );
359 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
360 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
362 $t = preg_replace( "/\\s+/", ' ', $t );
364 if ( $ns == NS_IMAGE
) {
365 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
371 * Make a prefixed DB key from a DB key and a namespace index
372 * @param int $ns numerical representation of the namespace
373 * @param string $title the DB key form the title
374 * @return string the prefixed form of the title
376 public static function makeName( $ns, $title ) {
379 $n = $wgContLang->getNsText( $ns );
380 return $n == '' ?
$title : "$n:$title";
384 * Returns the URL associated with an interwiki prefix
385 * @param string $key the interwiki prefix (e.g. "MeatBall")
386 * @return the associated URL, containing "$1", which should be
387 * replaced by an article title
390 public function getInterwikiLink( $key ) {
391 global $wgMemc, $wgInterwikiExpiry;
392 global $wgInterwikiCache, $wgContLang;
393 $fname = 'Title::getInterwikiLink';
395 $key = $wgContLang->lc( $key );
397 $k = wfMemcKey( 'interwiki', $key );
398 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
399 return Title
::$interwikiCache[$k]->iw_url
;
402 if ($wgInterwikiCache) {
403 return Title
::getInterwikiCached( $key );
406 $s = $wgMemc->get( $k );
407 # Ignore old keys with no iw_local
408 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
409 Title
::$interwikiCache[$k] = $s;
413 $dbr = wfGetDB( DB_SLAVE
);
414 $res = $dbr->select( 'interwiki',
415 array( 'iw_url', 'iw_local', 'iw_trans' ),
416 array( 'iw_prefix' => $key ), $fname );
421 $s = $dbr->fetchObject( $res );
423 # Cache non-existence: create a blank object and save it to memcached
429 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
430 Title
::$interwikiCache[$k] = $s;
436 * Fetch interwiki prefix data from local cache in constant database
438 * More logic is explained in DefaultSettings
440 * @return string URL of interwiki site
442 public static function getInterwikiCached( $key ) {
443 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
447 $db=dba_open($wgInterwikiCache,'r','cdb');
448 /* Resolve site name */
449 if ($wgInterwikiScopes>=3 and !$site) {
450 $site = dba_fetch('__sites:' . wfWikiID(), $db);
452 $site = $wgInterwikiFallbackSite;
454 $value = dba_fetch( wfMemcKey( $key ), $db);
455 if ($value=='' and $wgInterwikiScopes>=3) {
457 $value = dba_fetch("_{$site}:{$key}", $db);
459 if ($value=='' and $wgInterwikiScopes>=2) {
461 $value = dba_fetch("__global:{$key}", $db);
470 list($local,$url)=explode(' ',$value,2);
472 $s->iw_local
=(int)$local;
474 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
478 * Determine whether the object refers to a page within
481 * @return bool TRUE if this is an in-project interwiki link
482 * or a wikilink, FALSE otherwise
484 public function isLocal() {
485 if ( $this->mInterwiki
!= '' ) {
486 # Make sure key is loaded into cache
487 $this->getInterwikiLink( $this->mInterwiki
);
488 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
489 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
496 * Determine whether the object refers to a page within
497 * this project and is transcludable.
499 * @return bool TRUE if this is transcludable
501 public function isTrans() {
502 if ($this->mInterwiki
== '')
504 # Make sure key is loaded into cache
505 $this->getInterwikiLink( $this->mInterwiki
);
506 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
507 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
511 * Escape a text fragment, say from a link, for a URL
513 static function escapeFragmentForURL( $fragment ) {
514 $fragment = str_replace( ' ', '_', $fragment );
515 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
516 $replaceArray = array(
520 return strtr( $fragment, $replaceArray );
523 #----------------------------------------------------------------------------
525 #----------------------------------------------------------------------------
527 /** Simple accessors */
529 * Get the text form (spaces not underscores) of the main part
532 public function getText() { return $this->mTextform
; }
534 * Get the URL-encoded form of the main part
537 public function getPartialURL() { return $this->mUrlform
; }
539 * Get the main part with underscores
542 public function getDBkey() { return $this->mDbkeyform
; }
544 * Get the namespace index, i.e. one of the NS_xxxx constants
547 public function getNamespace() { return $this->mNamespace
; }
549 * Get the namespace text
552 public function getNsText() {
553 global $wgContLang, $wgCanonicalNamespaceNames;
555 if ( '' != $this->mInterwiki
) {
556 // This probably shouldn't even happen. ohh man, oh yuck.
557 // But for interwiki transclusion it sometimes does.
558 // Shit. Shit shit shit.
560 // Use the canonical namespaces if possible to try to
561 // resolve a foreign namespace.
562 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
563 return $wgCanonicalNamespaceNames[$this->mNamespace
];
566 return $wgContLang->getNsText( $this->mNamespace
);
569 * Get the DB key with the initial letter case as specified by the user
571 function getUserCaseDBKey() {
572 return $this->mUserCaseDBKey
;
575 * Get the namespace text of the subject (rather than talk) page
578 public function getSubjectNsText() {
580 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
584 * Get the namespace text of the talk page
587 public function getTalkNsText() {
589 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
593 * Could this title have a corresponding talk page?
596 public function canTalk() {
597 return( MWNamespace
::canTalk( $this->mNamespace
) );
601 * Get the interwiki prefix (or null string)
604 public function getInterwiki() { return $this->mInterwiki
; }
606 * Get the Title fragment (i.e. the bit after the #) in text form
609 public function getFragment() { return $this->mFragment
; }
611 * Get the fragment in URL form, including the "#" character if there is one
614 public function getFragmentForURL() {
615 if ( $this->mFragment
== '' ) {
618 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
622 * Get the default namespace index, for when there is no namespace
625 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
628 * Get title for search index
629 * @return string a stripped-down title string ready for the
632 public function getIndexTitle() {
633 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
637 * Get the prefixed database key form
638 * @return string the prefixed title, with underscores and
639 * any interwiki and namespace prefixes
641 public function getPrefixedDBkey() {
642 $s = $this->prefix( $this->mDbkeyform
);
643 $s = str_replace( ' ', '_', $s );
648 * Get the prefixed title with spaces.
649 * This is the form usually used for display
650 * @return string the prefixed title, with spaces
652 public function getPrefixedText() {
653 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
654 $s = $this->prefix( $this->mTextform
);
655 $s = str_replace( '_', ' ', $s );
656 $this->mPrefixedText
= $s;
658 return $this->mPrefixedText
;
662 * Get the prefixed title with spaces, plus any fragment
663 * (part beginning with '#')
664 * @return string the prefixed title, with spaces and
665 * the fragment, including '#'
667 public function getFullText() {
668 $text = $this->getPrefixedText();
669 if( '' != $this->mFragment
) {
670 $text .= '#' . $this->mFragment
;
676 * Get the base name, i.e. the leftmost parts before the /
677 * @return string Base name
679 public function getBaseText() {
680 global $wgNamespacesWithSubpages;
681 if( !empty( $wgNamespacesWithSubpages[$this->mNamespace
] ) ) {
682 $parts = explode( '/', $this->getText() );
683 # Don't discard the real title if there's no subpage involved
684 if( count( $parts ) > 1 )
685 unset( $parts[ count( $parts ) - 1 ] );
686 return implode( '/', $parts );
688 return $this->getText();
693 * Get the lowest-level subpage name, i.e. the rightmost part after /
694 * @return string Subpage name
696 public function getSubpageText() {
697 global $wgNamespacesWithSubpages;
698 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
699 $parts = explode( '/', $this->mTextform
);
700 return( $parts[ count( $parts ) - 1 ] );
702 return( $this->mTextform
);
707 * Get a URL-encoded form of the subpage text
708 * @return string URL-encoded subpage name
710 public function getSubpageUrlForm() {
711 $text = $this->getSubpageText();
712 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
713 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
718 * Get a URL-encoded title (not an actual URL) including interwiki
719 * @return string the URL-encoded form
721 public function getPrefixedURL() {
722 $s = $this->prefix( $this->mDbkeyform
);
723 $s = str_replace( ' ', '_', $s );
725 $s = wfUrlencode ( $s ) ;
727 # Cleaning up URL to make it look nice -- is this safe?
728 $s = str_replace( '%28', '(', $s );
729 $s = str_replace( '%29', ')', $s );
735 * Get a real URL referring to this title, with interwiki link and
738 * @param string $query an optional query string, not used
739 * for interwiki links
740 * @param string $variant language variant of url (for sr, zh..)
741 * @return string the URL
743 public function getFullURL( $query = '', $variant = false ) {
744 global $wgContLang, $wgServer, $wgRequest;
746 if ( '' == $this->mInterwiki
) {
747 $url = $this->getLocalUrl( $query, $variant );
749 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
750 // Correct fix would be to move the prepending elsewhere.
751 if ($wgRequest->getVal('action') != 'render') {
752 $url = $wgServer . $url;
755 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
757 $namespace = wfUrlencode( $this->getNsText() );
758 if ( '' != $namespace ) {
759 # Can this actually happen? Interwikis shouldn't be parsed.
760 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
763 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
764 $url = wfAppendQuery( $url, $query );
767 # Finally, add the fragment.
768 $url .= $this->getFragmentForURL();
770 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
775 * Get a URL with no fragment or server name. If this page is generated
776 * with action=render, $wgServer is prepended.
777 * @param string $query an optional query string; if not specified,
778 * $wgArticlePath will be used.
779 * @param string $variant language variant of url (for sr, zh..)
780 * @return string the URL
782 public function getLocalURL( $query = '', $variant = false ) {
783 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
784 global $wgVariantArticlePath, $wgContLang, $wgUser;
786 // internal links should point to same variant as current page (only anonymous users)
787 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
788 $pref = $wgContLang->getPreferredVariant(false);
789 if($pref != $wgContLang->getCode())
793 if ( $this->isExternal() ) {
794 $url = $this->getFullURL();
796 // This is currently only used for edit section links in the
797 // context of interwiki transclusion. In theory we should
798 // append the query to the end of any existing query string,
799 // but interwiki transclusion is already broken in that case.
803 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
804 if ( $query == '' ) {
805 if( $variant != false && $wgContLang->hasVariants() ) {
806 if( $wgVariantArticlePath == false ) {
807 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
809 $variantArticlePath = $wgVariantArticlePath;
811 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
812 $url = str_replace( '$1', $dbkey, $url );
814 $url = str_replace( '$1', $dbkey, $wgArticlePath );
817 global $wgActionPaths;
820 if( !empty( $wgActionPaths ) &&
821 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
823 $action = urldecode( $matches[2] );
824 if( isset( $wgActionPaths[$action] ) ) {
825 $query = $matches[1];
826 if( isset( $matches[4] ) ) $query .= $matches[4];
827 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
828 if( $query != '' ) $url .= '?' . $query;
831 if ( $url === false ) {
832 if ( $query == '-' ) {
835 $url = "{$wgScript}?title={$dbkey}&{$query}";
839 // FIXME: this causes breakage in various places when we
840 // actually expected a local URL and end up with dupe prefixes.
841 if ($wgRequest->getVal('action') == 'render') {
842 $url = $wgServer . $url;
845 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
850 * Get an HTML-escaped version of the URL form, suitable for
851 * using in a link, without a server name or fragment
852 * @param string $query an optional query string
853 * @return string the URL
855 public function escapeLocalURL( $query = '' ) {
856 return htmlspecialchars( $this->getLocalURL( $query ) );
860 * Get an HTML-escaped version of the URL form, suitable for
861 * using in a link, including the server name and fragment
863 * @return string the URL
864 * @param string $query an optional query string
866 public function escapeFullURL( $query = '' ) {
867 return htmlspecialchars( $this->getFullURL( $query ) );
871 * Get the URL form for an internal link.
872 * - Used in various Squid-related code, in case we have a different
873 * internal hostname for the server from the exposed one.
875 * @param string $query an optional query string
876 * @param string $variant language variant of url (for sr, zh..)
877 * @return string the URL
879 public function getInternalURL( $query = '', $variant = false ) {
880 global $wgInternalServer;
881 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
882 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
887 * Get the edit URL for this Title
888 * @return string the URL, or a null string if this is an
891 public function getEditURL() {
892 if ( '' != $this->mInterwiki
) { return ''; }
893 $s = $this->getLocalURL( 'action=edit' );
899 * Get the HTML-escaped displayable text form.
900 * Used for the title field in <a> tags.
901 * @return string the text, including any prefixes
903 public function getEscapedText() {
904 return htmlspecialchars( $this->getPrefixedText() );
908 * Is this Title interwiki?
911 public function isExternal() { return ( '' != $this->mInterwiki
); }
914 * Is this page "semi-protected" - the *only* protection is autoconfirm?
916 * @param string Action to check (default: edit)
919 public function isSemiProtected( $action = 'edit' ) {
920 if( $this->exists() ) {
921 $restrictions = $this->getRestrictions( $action );
922 if( count( $restrictions ) > 0 ) {
923 foreach( $restrictions as $restriction ) {
924 if( strtolower( $restriction ) != 'autoconfirmed' )
933 # If it doesn't exist, it can't be protected
939 * Does the title correspond to a protected article?
940 * @param string $what the action the page is protected from,
941 * by default checks move and edit
944 public function isProtected( $action = '' ) {
945 global $wgRestrictionLevels, $wgRestrictionTypes;
947 # Special pages have inherent protection
948 if( $this->getNamespace() == NS_SPECIAL
)
951 # Check regular protection levels
952 foreach( $wgRestrictionTypes as $type ){
953 if( $action == $type ||
$action == '' ) {
954 $r = $this->getRestrictions( $type );
955 foreach( $wgRestrictionLevels as $level ) {
956 if( in_array( $level, $r ) && $level != '' ) {
967 * Is $wgUser 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?
1030 * FIXME: This *does not* check throttles (User::pingLimiter()).
1032 * @param string $action action that permission needs to be checked for
1033 * @param User $user user to check
1034 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1035 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1037 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1038 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1042 global $wgEmailConfirmToEdit;
1044 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1045 $errors[] = array( 'confirmedittext' );
1048 if ( $user->isBlockedFrom( $this ) ) {
1049 $block = $user->mBlock
;
1051 // This is from OutputPage::blockedPage
1052 // Copied at r23888 by werdna
1054 $id = $user->blockedBy();
1055 $reason = $user->blockedFor();
1056 if( $reason == '' ) {
1057 $reason = wfMsg( 'blockednoreason' );
1061 if ( is_numeric( $id ) ) {
1062 $name = User
::whoIs( $id );
1067 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1068 $blockid = $block->mId
;
1069 $blockExpiry = $user->mBlock
->mExpiry
;
1070 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1072 if ( $blockExpiry == 'infinity' ) {
1073 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1074 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1076 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1077 if ( strpos( $option, ':' ) == false )
1080 list ($show, $value) = explode( ":", $option );
1082 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1083 $blockExpiry = $show;
1088 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1091 $intended = $user->mBlock
->mAddress
;
1093 $errors[] = array ( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1100 * Can $user perform $action on this page? This is an internal function,
1101 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1102 * checks on wfReadOnly() and blocks)
1104 * @param string $action action that permission needs to be checked for
1105 * @param User $user user to check
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 wfProfileIn( __METHOD__
);
1114 // Use getUserPermissionsErrors instead
1115 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1116 return $result ?
array() : array( array( 'badaccess-group0' ) );
1119 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1120 if ($result != array() && is_array($result) && !is_array($result[0]))
1121 $errors[] = $result; # A single array representing an error
1122 else if (is_array($result) && is_array($result[0]))
1123 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1124 else if ($result != '' && $result != null && $result !== true && $result !== false)
1125 $errors[] = array($result); # A string representing a message-id
1126 else if ($result === false )
1127 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1129 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1130 if ($result != array() && is_array($result) && !is_array($result[0]))
1131 $errors[] = $result; # A single array representing an error
1132 else if (is_array($result) && is_array($result[0]))
1133 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1134 else if ($result != '' && $result != null && $result !== true && $result !== false)
1135 $errors[] = array($result); # A string representing a message-id
1136 else if ($result === false )
1137 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1140 if( NS_SPECIAL
== $this->mNamespace
) {
1141 $errors[] = array('ns-specialprotected');
1144 if ( $this->isNamespaceProtected() ) {
1145 $ns = $this->getNamespace() == NS_MAIN
1146 ?
wfMsg( 'nstab-main' )
1147 : $this->getNsText();
1148 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1149 ?
array('protectedinterface')
1150 : array( 'namespaceprotected', $ns ) );
1153 if( $this->mDbkeyform
== '_' ) {
1154 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1155 $errors[] = array('badaccess-group0');
1158 # protect css/js subpages of user pages
1159 # XXX: this might be better using restrictions
1160 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1161 if( $this->isCssJsSubpage()
1162 && !$user->isAllowed('editusercssjs')
1163 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1164 $errors[] = array('customcssjsprotected');
1167 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1168 # We /could/ use the protection level on the source page, but it's fairly ugly
1169 # as we have to establish a precedence hierarchy for pages included by multiple
1170 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1171 # as they could remove the protection anyway.
1172 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1173 # Cascading protection depends on more than this page...
1174 # Several cascading protected pages may include this page...
1175 # Check each cascading level
1176 # This is only for protection restrictions, not for all actions
1177 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1178 foreach( $restrictions[$action] as $right ) {
1179 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1180 if( '' != $right && !$user->isAllowed( $right ) ) {
1182 foreach( $cascadingSources as $page )
1183 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1184 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1190 foreach( $this->getRestrictions($action) as $right ) {
1191 // Backwards compatibility, rewrite sysop -> protect
1192 if ( $right == 'sysop' ) {
1195 if( '' != $right && !$user->isAllowed( $right ) ) {
1196 //Users with 'editprotected' permission can edit protected pages
1197 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1198 //Users with 'editprotected' permission cannot edit protected pages
1199 //with cascading option turned on.
1200 if($this->mCascadeRestriction
) {
1201 $errors[] = array( 'protectedpagetext', $right );
1203 //Nothing, user can edit!
1206 $errors[] = array( 'protectedpagetext', $right );
1211 if ($action == 'protect') {
1212 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1213 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1217 if ($action == 'create') {
1218 $title_protection = $this->getTitleProtection();
1220 if (is_array($title_protection)) {
1221 extract($title_protection);
1223 if ($pt_create_perm == 'sysop')
1224 $pt_create_perm = 'protect';
1226 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1227 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1231 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1232 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1233 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1235 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1236 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1237 } elseif ( !$user->isAllowed( $action ) ) {
1240 global $wgGroupPermissions;
1241 foreach( $wgGroupPermissions as $key => $value ) {
1242 if( isset( $value[$action] ) && $value[$action] == true ) {
1243 $groupName = User
::getGroupName( $key );
1244 $groupPage = User
::getGroupPage( $key );
1246 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1248 $groups[] = $groupName;
1252 $n = count( $groups );
1253 $groups = implode( ', ', $groups );
1258 $return = array( "badaccess-group$n", $groups );
1261 $return = array( 'badaccess-groups', $groups );
1263 $errors[] = $return;
1266 wfProfileOut( __METHOD__
);
1271 * Is this title subject to title protection?
1272 * @return mixed An associative array representing any existent title
1273 * protection, or false if there's none.
1275 private function getTitleProtection() {
1276 // Can't protect pages in special namespaces
1277 if ( $this->getNamespace() < 0 ) {
1281 $dbr = wfGetDB( DB_SLAVE
);
1282 $res = $dbr->select( 'protected_titles', '*',
1283 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1285 if ($row = $dbr->fetchRow( $res )) {
1292 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1293 global $wgGroupPermissions,$wgUser,$wgContLang;
1295 if ($create_perm == implode(',',$this->getRestrictions('create'))
1296 && $expiry == $this->mRestrictionsExpiry
) {
1301 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1303 $dbw = wfGetDB( DB_MASTER
);
1305 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1307 $expiry_description = '';
1308 if ( $encodedExpiry != 'infinity' ) {
1309 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1312 # Update protection table
1313 if ($create_perm != '' ) {
1314 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1315 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1316 , 'pt_create_perm' => $create_perm
1317 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1318 , 'pt_expiry' => $encodedExpiry
1319 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1321 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1322 'pt_title' => $title ), __METHOD__
);
1324 # Update the protection log
1325 $log = new LogPage( 'protect' );
1327 if( $create_perm ) {
1328 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1330 $log->addEntry( 'unprotect', $this, $reason );
1337 * Remove any title protection (due to page existing
1339 public function deleteTitleProtection() {
1340 $dbw = wfGetDB( DB_MASTER
);
1342 $dbw->delete( 'protected_titles',
1343 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1347 * Can $wgUser edit this page?
1349 * @deprecated use userCan('edit')
1351 public function userCanEdit( $doExpensiveQueries = true ) {
1352 return $this->userCan( 'edit', $doExpensiveQueries );
1356 * Can $wgUser create this page?
1358 * @deprecated use userCan('create')
1360 public function userCanCreate( $doExpensiveQueries = true ) {
1361 return $this->userCan( 'create', $doExpensiveQueries );
1365 * Can $wgUser move this page?
1367 * @deprecated use userCan('move')
1369 public function userCanMove( $doExpensiveQueries = true ) {
1370 return $this->userCan( 'move', $doExpensiveQueries );
1374 * Would anybody with sufficient privileges be able to move this page?
1375 * Some pages just aren't movable.
1379 public function isMovable() {
1380 return MWNamespace
::isMovable( $this->getNamespace() )
1381 && $this->getInterwiki() == '';
1385 * Can $wgUser read this page?
1387 * @todo fold these checks into userCan()
1389 public function userCanRead() {
1393 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1394 if ( $result !== null ) {
1398 if( $wgUser->isAllowed( 'read' ) ) {
1401 global $wgWhitelistRead;
1404 * Always grant access to the login page.
1405 * Even anons need to be able to log in.
1407 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1412 * Bail out if there isn't whitelist
1414 if( !is_array($wgWhitelistRead) ) {
1419 * Check for explicit whitelisting
1421 $name = $this->getPrefixedText();
1422 if( in_array( $name, $wgWhitelistRead, true ) )
1426 * Old settings might have the title prefixed with
1427 * a colon for main-namespace pages
1429 if( $this->getNamespace() == NS_MAIN
) {
1430 if( in_array( ':' . $name, $wgWhitelistRead ) )
1435 * If it's a special page, ditch the subpage bit
1438 if( $this->getNamespace() == NS_SPECIAL
) {
1439 $name = $this->getDBkey();
1440 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1441 if ( $name === false ) {
1442 # Invalid special page, but we show standard login required message
1446 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1447 if( in_array( $pure, $wgWhitelistRead, true ) )
1456 * Is this a talk page of some sort?
1459 public function isTalkPage() {
1460 return MWNamespace
::isTalk( $this->getNamespace() );
1464 * Is this a subpage?
1467 public function isSubpage() {
1468 global $wgNamespacesWithSubpages;
1470 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1471 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1478 * Could this page contain custom CSS or JavaScript, based
1483 public function isCssOrJsPage() {
1484 return $this->mNamespace
== NS_MEDIAWIKI
1485 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1489 * Is this a .css or .js subpage of a user page?
1492 public function isCssJsSubpage() {
1493 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1496 * Is this a *valid* .css or .js subpage of a user page?
1497 * Check that the corresponding skin exists
1499 public function isValidCssJsSubpage() {
1500 if ( $this->isCssJsSubpage() ) {
1501 $skinNames = Skin
::getSkinNames();
1502 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1508 * Trim down a .css or .js subpage title to get the corresponding skin name
1510 public function getSkinFromCssJsSubpage() {
1511 $subpage = explode( '/', $this->mTextform
);
1512 $subpage = $subpage[ count( $subpage ) - 1 ];
1513 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1516 * Is this a .css subpage of a user page?
1519 public function isCssSubpage() {
1520 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1523 * Is this a .js subpage of a user page?
1526 public function isJsSubpage() {
1527 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1530 * Protect css/js subpages of user pages: can $wgUser edit
1534 * @todo XXX: this might be better using restrictions
1536 public function userCanEditCssJsSubpage() {
1538 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1542 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1544 * @return bool If the page is subject to cascading restrictions.
1546 public function isCascadeProtected() {
1547 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1548 return ( $sources > 0 );
1552 * Cascading protection: Get the source of any cascading restrictions on this page.
1554 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1555 * @return array( mixed title array, restriction array)
1556 * 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.
1557 * The restriction array is an array of each type, each of which contains an array of unique groups
1559 public function getCascadeProtectionSources( $get_pages = true ) {
1560 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1562 # Define our dimension of restrictions types
1563 $pagerestrictions = array();
1564 foreach( $wgRestrictionTypes as $action )
1565 $pagerestrictions[$action] = array();
1567 if (!$wgEnableCascadingProtection)
1568 return array( false, $pagerestrictions );
1570 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1571 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1572 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1573 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1576 wfProfileIn( __METHOD__
);
1578 $dbr = wfGetDb( DB_SLAVE
);
1580 if ( $this->getNamespace() == NS_IMAGE
) {
1581 $tables = array ('imagelinks', 'page_restrictions');
1582 $where_clauses = array(
1583 'il_to' => $this->getDBkey(),
1585 'pr_cascade' => 1 );
1587 $tables = array ('templatelinks', 'page_restrictions');
1588 $where_clauses = array(
1589 'tl_namespace' => $this->getNamespace(),
1590 'tl_title' => $this->getDBkey(),
1592 'pr_cascade' => 1 );
1596 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1597 $where_clauses[] = 'page_id=pr_page';
1600 $cols = array( 'pr_expiry' );
1603 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1605 $sources = $get_pages ?
array() : false;
1606 $now = wfTimestampNow();
1607 $purgeExpired = false;
1609 while( $row = $dbr->fetchObject( $res ) ) {
1610 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1611 if( $expiry > $now ) {
1613 $page_id = $row->pr_page
;
1614 $page_ns = $row->page_namespace
;
1615 $page_title = $row->page_title
;
1616 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1617 # Add groups needed for each restriction type if its not already there
1618 # Make sure this restriction type still exists
1619 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1620 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1626 // Trigger lazy purge of expired restrictions from the db
1627 $purgeExpired = true;
1630 if( $purgeExpired ) {
1631 Title
::purgeExpiredRestrictions();
1634 wfProfileOut( __METHOD__
);
1637 $this->mCascadeSources
= $sources;
1638 $this->mCascadingRestrictions
= $pagerestrictions;
1640 $this->mHasCascadingRestrictions
= $sources;
1643 return array( $sources, $pagerestrictions );
1646 function areRestrictionsCascading() {
1647 if (!$this->mRestrictionsLoaded
) {
1648 $this->loadRestrictions();
1651 return $this->mCascadeRestriction
;
1655 * Loads a string into mRestrictions array
1656 * @param resource $res restrictions as an SQL result.
1658 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1659 global $wgRestrictionTypes;
1660 $dbr = wfGetDB( DB_SLAVE
);
1662 foreach( $wgRestrictionTypes as $type ){
1663 $this->mRestrictions
[$type] = array();
1666 $this->mCascadeRestriction
= false;
1667 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1669 # Backwards-compatibility: also load the restrictions from the page record (old format).
1671 if ( $oldFashionedRestrictions == NULL ) {
1672 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1675 if ($oldFashionedRestrictions != '') {
1677 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1678 $temp = explode( '=', trim( $restrict ) );
1679 if(count($temp) == 1) {
1680 // old old format should be treated as edit/move restriction
1681 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1682 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1684 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1688 $this->mOldRestrictions
= true;
1692 if( $dbr->numRows( $res ) ) {
1693 # Current system - load second to make them override.
1694 $now = wfTimestampNow();
1695 $purgeExpired = false;
1697 while ($row = $dbr->fetchObject( $res ) ) {
1698 # Cycle through all the restrictions.
1700 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1701 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1704 // This code should be refactored, now that it's being used more generally,
1705 // But I don't really see any harm in leaving it in Block for now -werdna
1706 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1708 // Only apply the restrictions if they haven't expired!
1709 if ( !$expiry ||
$expiry > $now ) {
1710 $this->mRestrictionsExpiry
= $expiry;
1711 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1713 $this->mCascadeRestriction |
= $row->pr_cascade
;
1715 // Trigger a lazy purge of expired restrictions
1716 $purgeExpired = true;
1720 if( $purgeExpired ) {
1721 Title
::purgeExpiredRestrictions();
1725 $this->mRestrictionsLoaded
= true;
1728 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1729 if( !$this->mRestrictionsLoaded
) {
1730 if ($this->exists()) {
1731 $dbr = wfGetDB( DB_SLAVE
);
1733 $res = $dbr->select( 'page_restrictions', '*',
1734 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1736 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1738 $title_protection = $this->getTitleProtection();
1740 if (is_array($title_protection)) {
1741 extract($title_protection);
1743 $now = wfTimestampNow();
1744 $expiry = Block
::decodeExpiry($pt_expiry);
1746 if (!$expiry ||
$expiry > $now) {
1747 // Apply the restrictions
1748 $this->mRestrictionsExpiry
= $expiry;
1749 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1750 } else { // Get rid of the old restrictions
1751 Title
::purgeExpiredRestrictions();
1754 $this->mRestrictionsLoaded
= true;
1760 * Purge expired restrictions from the page_restrictions table
1762 static function purgeExpiredRestrictions() {
1763 $dbw = wfGetDB( DB_MASTER
);
1764 $dbw->delete( 'page_restrictions',
1765 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1768 $dbw->delete( 'protected_titles',
1769 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1774 * Accessor/initialisation for mRestrictions
1776 * @param string $action action that permission needs to be checked for
1777 * @return array the array of groups allowed to edit this article
1779 public function getRestrictions( $action ) {
1780 if( !$this->mRestrictionsLoaded
) {
1781 $this->loadRestrictions();
1783 return isset( $this->mRestrictions
[$action] )
1784 ?
$this->mRestrictions
[$action]
1789 * Is there a version of this page in the deletion archive?
1790 * @return int the number of archived revisions
1792 public function isDeleted() {
1793 $fname = 'Title::isDeleted';
1794 if ( $this->getNamespace() < 0 ) {
1797 $dbr = wfGetDB( DB_SLAVE
);
1798 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1799 'ar_title' => $this->getDBkey() ), $fname );
1800 if( $this->getNamespace() == NS_IMAGE
) {
1801 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1802 array( 'fa_name' => $this->getDBkey() ), $fname );
1809 * Get the article ID for this Title from the link cache,
1810 * adding it if necessary
1811 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1813 * @return int the ID
1815 public function getArticleID( $flags = 0 ) {
1816 $linkCache =& LinkCache
::singleton();
1817 if ( $flags & GAID_FOR_UPDATE
) {
1818 $oldUpdate = $linkCache->forUpdate( true );
1819 $this->mArticleID
= $linkCache->addLinkObj( $this );
1820 $linkCache->forUpdate( $oldUpdate );
1822 if ( -1 == $this->mArticleID
) {
1823 $this->mArticleID
= $linkCache->addLinkObj( $this );
1826 return $this->mArticleID
;
1829 public function getLatestRevID() {
1830 if ($this->mLatestID
!== false)
1831 return $this->mLatestID
;
1833 $db = wfGetDB(DB_SLAVE
);
1834 return $this->mLatestID
= $db->selectField( 'revision',
1836 array('rev_page' => $this->getArticleID()),
1837 'Title::getLatestRevID' );
1841 * This clears some fields in this object, and clears any associated
1842 * keys in the "bad links" section of the link cache.
1844 * - This is called from Article::insertNewArticle() to allow
1845 * loading of the new page_id. It's also called from
1846 * Article::doDeleteArticle()
1848 * @param int $newid the new Article ID
1850 public function resetArticleID( $newid ) {
1851 $linkCache =& LinkCache
::singleton();
1852 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1854 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1855 else { $this->mArticleID
= $newid; }
1856 $this->mRestrictionsLoaded
= false;
1857 $this->mRestrictions
= array();
1861 * Updates page_touched for this page; called from LinksUpdate.php
1862 * @return bool true if the update succeded
1864 public function invalidateCache() {
1865 global $wgUseFileCache;
1867 if ( wfReadOnly() ) {
1871 $dbw = wfGetDB( DB_MASTER
);
1872 $success = $dbw->update( 'page',
1874 'page_touched' => $dbw->timestamp()
1875 ), array( /* WHERE */
1876 'page_namespace' => $this->getNamespace() ,
1877 'page_title' => $this->getDBkey()
1878 ), 'Title::invalidateCache'
1881 if ($wgUseFileCache) {
1882 $cache = new HTMLFileCache($this);
1883 @unlink
($cache->fileCacheName());
1890 * Prefix some arbitrary text with the namespace or interwiki prefix
1893 * @param string $name the text
1894 * @return string the prefixed text
1897 /* private */ function prefix( $name ) {
1899 if ( '' != $this->mInterwiki
) {
1900 $p = $this->mInterwiki
. ':';
1902 if ( 0 != $this->mNamespace
) {
1903 $p .= $this->getNsText() . ':';
1909 * Secure and split - main initialisation function for this object
1911 * Assumes that mDbkeyform has been set, and is urldecoded
1912 * and uses underscores, but not otherwise munged. This function
1913 * removes illegal characters, splits off the interwiki and
1914 * namespace prefixes, sets the other forms, and canonicalizes
1916 * @return bool true on success
1918 private function secureAndSplit() {
1919 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1922 static $rxTc = false;
1924 # Matching titles will be held as illegal.
1926 # Any character not allowed is forbidden...
1927 '[^' . Title
::legalChars() . ']' .
1928 # URL percent encoding sequences interfere with the ability
1929 # to round-trip titles -- you can't link to them consistently.
1930 '|%[0-9A-Fa-f]{2}' .
1931 # XML/HTML character references produce similar issues.
1932 '|&[A-Za-z0-9\x80-\xff]+;' .
1934 '|&#x[0-9A-Fa-f]+;' .
1938 $this->mInterwiki
= $this->mFragment
= '';
1939 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1941 $dbkey = $this->mDbkeyform
;
1943 # Strip Unicode bidi override characters.
1944 # Sometimes they slip into cut-n-pasted page titles, where the
1945 # override chars get included in list displays.
1946 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1947 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1949 # Clean up whitespace
1951 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1952 $dbkey = trim( $dbkey, '_' );
1954 if ( '' == $dbkey ) {
1958 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
1959 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1963 $this->mDbkeyform
= $dbkey;
1965 # Initial colon indicates main namespace rather than specified default
1966 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1967 if ( ':' == $dbkey{0} ) {
1968 $this->mNamespace
= NS_MAIN
;
1969 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1970 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1973 # Namespace or interwiki prefix
1977 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1979 if ( $ns = $wgContLang->getNsIndex( $p )) {
1980 # Ordinary namespace
1982 $this->mNamespace
= $ns;
1983 } elseif( $this->getInterwikiLink( $p ) ) {
1985 # Can't make a local interwiki link to an interwiki link.
1986 # That's just crazy!
1992 $this->mInterwiki
= $wgContLang->lc( $p );
1994 # Redundant interwiki prefix to the local wiki
1995 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1996 if( $dbkey == '' ) {
1997 # Can't have an empty self-link
2000 $this->mInterwiki
= '';
2002 # Do another namespace split...
2006 # If there's an initial colon after the interwiki, that also
2007 # resets the default namespace
2008 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2009 $this->mNamespace
= NS_MAIN
;
2010 $dbkey = substr( $dbkey, 1 );
2013 # If there's no recognized interwiki or namespace,
2014 # then let the colon expression be part of the title.
2019 # We already know that some pages won't be in the database!
2021 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2022 $this->mArticleID
= 0;
2024 $fragment = strstr( $dbkey, '#' );
2025 if ( false !== $fragment ) {
2026 $this->setFragment( $fragment );
2027 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2028 # remove whitespace again: prevents "Foo_bar_#"
2029 # becoming "Foo_bar_"
2030 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2033 # Reject illegal characters.
2035 if( preg_match( $rxTc, $dbkey ) ) {
2040 * Pages with "/./" or "/../" appearing in the URLs will
2041 * often be unreachable due to the way web browsers deal
2042 * with 'relative' URLs. Forbid them explicitly.
2044 if ( strpos( $dbkey, '.' ) !== false &&
2045 ( $dbkey === '.' ||
$dbkey === '..' ||
2046 strpos( $dbkey, './' ) === 0 ||
2047 strpos( $dbkey, '../' ) === 0 ||
2048 strpos( $dbkey, '/./' ) !== false ||
2049 strpos( $dbkey, '/../' ) !== false ||
2050 substr( $dbkey, -2 ) == '/.' ||
2051 substr( $dbkey, -3 ) == '/..' ) )
2057 * Magic tilde sequences? Nu-uh!
2059 if( strpos( $dbkey, '~~~' ) !== false ) {
2064 * Limit the size of titles to 255 bytes.
2065 * This is typically the size of the underlying database field.
2066 * We make an exception for special pages, which don't need to be stored
2067 * in the database, and may edge over 255 bytes due to subpage syntax
2068 * for long titles, e.g. [[Special:Block/Long name]]
2070 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2071 strlen( $dbkey ) > 512 )
2077 * Normally, all wiki links are forced to have
2078 * an initial capital letter so [[foo]] and [[Foo]]
2079 * point to the same place.
2081 * Don't force it for interwikis, since the other
2082 * site might be case-sensitive.
2084 $this->mUserCaseDBKey
= $dbkey;
2085 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2086 $dbkey = $wgContLang->ucfirst( $dbkey );
2090 * Can't make a link to a namespace alone...
2091 * "empty" local links can only be self-links
2092 * with a fragment identifier.
2095 $this->mInterwiki
== '' &&
2096 $this->mNamespace
!= NS_MAIN
) {
2099 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2100 // IP names are not allowed for accounts, and can only be referring to
2101 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2102 // there are numerous ways to present the same IP. Having sp:contribs scan
2103 // them all is silly and having some show the edits and others not is
2104 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2105 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2106 IP
::sanitizeIP( $dbkey ) : $dbkey;
2107 // Any remaining initial :s are illegal.
2108 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2113 $this->mDbkeyform
= $dbkey;
2114 $this->mUrlform
= wfUrlencode( $dbkey );
2116 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2122 * Set the fragment for this title
2123 * This is kind of bad, since except for this rarely-used function, Title objects
2124 * are immutable. The reason this is here is because it's better than setting the
2125 * members directly, which is what Linker::formatComment was doing previously.
2127 * @param string $fragment text
2128 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2130 public function setFragment( $fragment ) {
2131 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2135 * Get a Title object associated with the talk page of this article
2136 * @return Title the object for the talk page
2138 public function getTalkPage() {
2139 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2143 * Get a title object associated with the subject page of this
2146 * @return Title the object for the subject page
2148 public function getSubjectPage() {
2149 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2153 * Get an array of Title objects linking to this Title
2154 * Also stores the IDs in the link cache.
2156 * WARNING: do not use this function on arbitrary user-supplied titles!
2157 * On heavily-used templates it will max out the memory.
2159 * @param string $options may be FOR UPDATE
2160 * @return array the Title objects linking here
2162 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2163 $linkCache =& LinkCache
::singleton();
2166 $db = wfGetDB( DB_MASTER
);
2168 $db = wfGetDB( DB_SLAVE
);
2171 $res = $db->select( array( 'page', $table ),
2172 array( 'page_namespace', 'page_title', 'page_id' ),
2174 "{$prefix}_from=page_id",
2175 "{$prefix}_namespace" => $this->getNamespace(),
2176 "{$prefix}_title" => $this->getDBkey() ),
2177 'Title::getLinksTo',
2181 if ( $db->numRows( $res ) ) {
2182 while ( $row = $db->fetchObject( $res ) ) {
2183 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2184 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
2185 $retVal[] = $titleObj;
2189 $db->freeResult( $res );
2194 * Get an array of Title objects using this Title as a template
2195 * Also stores the IDs in the link cache.
2197 * WARNING: do not use this function on arbitrary user-supplied titles!
2198 * On heavily-used templates it will max out the memory.
2200 * @param string $options may be FOR UPDATE
2201 * @return array the Title objects linking here
2203 public function getTemplateLinksTo( $options = '' ) {
2204 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2208 * Get an array of Title objects referring to non-existent articles linked from this page
2210 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2211 * @param string $options may be FOR UPDATE
2212 * @return array the Title objects
2214 public function getBrokenLinksFrom( $options = '' ) {
2215 if ( $this->getArticleId() == 0 ) {
2216 # All links from article ID 0 are false positives
2221 $db = wfGetDB( DB_MASTER
);
2223 $db = wfGetDB( DB_SLAVE
);
2226 $res = $db->safeQuery(
2227 "SELECT pl_namespace, pl_title
2230 ON pl_namespace=page_namespace
2231 AND pl_title=page_title
2233 AND page_namespace IS NULL
2235 $db->tableName( 'pagelinks' ),
2236 $db->tableName( 'page' ),
2237 $this->getArticleId(),
2241 if ( $db->numRows( $res ) ) {
2242 while ( $row = $db->fetchObject( $res ) ) {
2243 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2246 $db->freeResult( $res );
2252 * Get a list of URLs to purge from the Squid cache when this
2255 * @return array the URLs
2257 public function getSquidURLs() {
2261 $this->getInternalURL(),
2262 $this->getInternalURL( 'action=history' )
2265 // purge variant urls as well
2266 if($wgContLang->hasVariants()){
2267 $variants = $wgContLang->getVariants();
2268 foreach($variants as $vCode){
2269 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2270 $urls[] = $this->getInternalURL('',$vCode);
2277 public function purgeSquid() {
2279 if ( $wgUseSquid ) {
2280 $urls = $this->getSquidURLs();
2281 $u = new SquidUpdate( $urls );
2287 * Move this page without authentication
2288 * @param Title &$nt the new page Title
2290 public function moveNoAuth( &$nt ) {
2291 return $this->moveTo( $nt, false );
2295 * Check whether a given move operation would be valid.
2296 * Returns true if ok, or a message key string for an error message
2297 * if invalid. (Scarrrrry ugly interface this.)
2298 * @param Title &$nt the new title
2299 * @param bool $auth indicates whether $wgUser's permissions
2301 * @return mixed true on success, message name on failure
2303 public function isValidMoveOperation( &$nt, $auth = true ) {
2304 if( !$this or !$nt ) {
2305 return 'badtitletext';
2307 if( $this->equals( $nt ) ) {
2310 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2311 return 'immobile_namespace';
2314 $oldid = $this->getArticleID();
2315 $newid = $nt->getArticleID();
2317 if ( strlen( $nt->getDBkey() ) < 1 ) {
2318 return 'articleexists';
2320 if ( ( '' == $this->getDBkey() ) ||
2322 ( '' == $nt->getDBkey() ) ) {
2323 return 'badarticleerror';
2328 $errors = array_merge($this->getUserPermissionsErrors('move', $wgUser),
2329 $this->getUserPermissionsErrors('edit', $wgUser),
2330 $nt->getUserPermissionsErrors('move', $wgUser),
2331 $nt->getUserPermissionsErrors('edit', $wgUser));
2332 if($errors !== array())
2333 return $errors[0][0];
2338 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
2339 return 'hookaborted';
2342 # The move is allowed only if (1) the target doesn't exist, or
2343 # (2) the target is a redirect to the source, and has no history
2344 # (so we can undo bad moves right after they're done).
2346 if ( 0 != $newid ) { # Target exists; check for validity
2347 if ( ! $this->isValidMoveTarget( $nt ) ) {
2348 return 'articleexists';
2351 $tp = $nt->getTitleProtection();
2352 if ( $tp and !$wgUser->isAllowed( $tp['pt_create_perm'] ) ) {
2353 return 'cantmove-titleprotected';
2360 * Move a title to a new location
2361 * @param Title &$nt the new title
2362 * @param bool $auth indicates whether $wgUser's permissions
2364 * @param string $reason The reason for the move
2365 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2366 * Ignored if the user doesn't have the suppressredirect right.
2367 * @return mixed true on success, message name on failure
2369 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2370 $err = $this->isValidMoveOperation( $nt, $auth );
2371 if( is_string( $err ) ) {
2375 $pageid = $this->getArticleID();
2376 if( $nt->exists() ) {
2377 $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2378 $pageCountChange = ($createRedirect ?
0 : -1);
2379 } else { # Target didn't exist, do normal move.
2380 $this->moveToNewTitle( $nt, $reason, $createRedirect );
2381 $pageCountChange = ($createRedirect ?
1 : 0);
2383 $redirid = $this->getArticleID();
2385 // Category memberships include a sort key which may be customized.
2386 // If it's left as the default (the page title), we need to update
2387 // the sort key to match the new title.
2389 // Be careful to avoid resetting cl_timestamp, which may disturb
2390 // time-based lists on some sites.
2392 // Warning -- if the sort key is *explicitly* set to the old title,
2393 // we can't actually distinguish it from a default here, and it'll
2394 // be set to the new title even though it really shouldn't.
2395 // It'll get corrected on the next edit, but resetting cl_timestamp.
2396 $dbw = wfGetDB( DB_MASTER
);
2397 $dbw->update( 'categorylinks',
2399 'cl_sortkey' => $nt->getPrefixedText(),
2400 'cl_timestamp=cl_timestamp' ),
2402 'cl_from' => $pageid,
2403 'cl_sortkey' => $this->getPrefixedText() ),
2408 $oldnamespace = $this->getNamespace() & ~
1;
2409 $newnamespace = $nt->getNamespace() & ~
1;
2410 $oldtitle = $this->getDBkey();
2411 $newtitle = $nt->getDBkey();
2413 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2414 WatchedItem
::duplicateEntries( $this, $nt );
2417 # Update search engine
2418 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2420 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2424 if( $this->isContentPage() && !$nt->isContentPage() ) {
2425 # No longer a content page
2426 # Not viewed, edited, removing
2427 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2428 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2429 # Now a content page
2430 # Not viewed, edited, adding
2431 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2432 } elseif( $pageCountChange ) {
2434 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2441 # Update message cache for interface messages
2442 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2443 global $wgMessageCache;
2444 $oldarticle = new Article( $this );
2445 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2446 $newarticle = new Article( $nt );
2447 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2451 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2456 * Move page to a title which is at present a redirect to the
2459 * @param Title &$nt the page to move to, which should currently
2461 * @param string $reason The reason for the move
2462 * @param bool $createRedirect Whether to leave a redirect at the old title.
2463 * Ignored if the user doesn't have the suppressredirect right
2465 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2466 global $wgUseSquid, $wgUser;
2467 $fname = 'Title::moveOverExistingRedirect';
2468 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2471 $comment .= ": $reason";
2474 $now = wfTimestampNow();
2475 $newid = $nt->getArticleID();
2476 $oldid = $this->getArticleID();
2477 $dbw = wfGetDB( DB_MASTER
);
2479 # Delete the old redirect. We don't save it to history since
2480 # by definition if we've got here it's rather uninteresting.
2481 # We have to remove it so that the next step doesn't trigger
2482 # a conflict on the unique namespace+title index...
2483 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2484 if ( !$dbw->cascadingDeletes() ) {
2485 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2486 global $wgUseTrackbacks;
2487 if ($wgUseTrackbacks)
2488 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2489 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2490 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2491 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2492 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2493 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2494 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2495 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2498 # Save a null revision in the page's history notifying of the move
2499 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2500 $nullRevId = $nullRevision->insertOn( $dbw );
2502 # Change the name of the target page:
2503 $dbw->update( 'page',
2505 'page_touched' => $dbw->timestamp($now),
2506 'page_namespace' => $nt->getNamespace(),
2507 'page_title' => $nt->getDBkey(),
2508 'page_latest' => $nullRevId,
2510 /* WHERE */ array( 'page_id' => $oldid ),
2513 $nt->resetArticleID( $oldid );
2515 # Recreate the redirect, this time in the other direction.
2516 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2518 $mwRedir = MagicWord
::get( 'redirect' );
2519 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2520 $redirectArticle = new Article( $this );
2521 $newid = $redirectArticle->insertOn( $dbw );
2522 $redirectRevision = new Revision( array(
2524 'comment' => $comment,
2525 'text' => $redirectText ) );
2526 $redirectRevision->insertOn( $dbw );
2527 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2529 # Now, we record the link from the redirect to the new title.
2530 # It should have no other outgoing links...
2531 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2532 $dbw->insert( 'pagelinks',
2534 'pl_from' => $newid,
2535 'pl_namespace' => $nt->getNamespace(),
2536 'pl_title' => $nt->getDBkey() ),
2539 $this->resetArticleID( 0 );
2543 $log = new LogPage( 'move' );
2544 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2547 if ( $wgUseSquid ) {
2548 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2549 $u = new SquidUpdate( $urls );
2555 * Move page to non-existing title.
2556 * @param Title &$nt the new Title
2557 * @param string $reason The reason for the move
2558 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2559 * Ignored if the user doesn't have the suppressredirect right
2561 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2562 global $wgUseSquid, $wgUser;
2563 $fname = 'MovePageForm::moveToNewTitle';
2564 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2566 $comment .= ": $reason";
2569 $newid = $nt->getArticleID();
2570 $oldid = $this->getArticleID();
2571 $dbw = wfGetDB( DB_MASTER
);
2572 $now = $dbw->timestamp();
2574 # Save a null revision in the page's history notifying of the move
2575 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2576 $nullRevId = $nullRevision->insertOn( $dbw );
2579 $dbw->update( 'page',
2581 'page_touched' => $now,
2582 'page_namespace' => $nt->getNamespace(),
2583 'page_title' => $nt->getDBkey(),
2584 'page_latest' => $nullRevId,
2586 /* WHERE */ array( 'page_id' => $oldid ),
2589 $nt->resetArticleID( $oldid );
2591 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2594 $mwRedir = MagicWord
::get( 'redirect' );
2595 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2596 $redirectArticle = new Article( $this );
2597 $newid = $redirectArticle->insertOn( $dbw );
2598 $redirectRevision = new Revision( array(
2600 'comment' => $comment,
2601 'text' => $redirectText ) );
2602 $redirectRevision->insertOn( $dbw );
2603 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2605 # Record the just-created redirect's linking to the page
2606 $dbw->insert( 'pagelinks',
2608 'pl_from' => $newid,
2609 'pl_namespace' => $nt->getNamespace(),
2610 'pl_title' => $nt->getDBkey() ),
2613 $this->resetArticleID( 0 );
2617 $log = new LogPage( 'move' );
2618 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2620 # Purge caches as per article creation
2621 Article
::onArticleCreate( $nt );
2623 # Purge old title from squid
2624 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2625 $this->purgeSquid();
2629 * Checks if $this can be moved to a given Title
2630 * - Selects for update, so don't call it unless you mean business
2632 * @param Title &$nt the new title to check
2634 public function isValidMoveTarget( $nt ) {
2636 $fname = 'Title::isValidMoveTarget';
2637 $dbw = wfGetDB( DB_MASTER
);
2640 $id = $nt->getArticleID();
2641 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2642 array( 'page_is_redirect','old_text','old_flags' ),
2643 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2644 $fname, 'FOR UPDATE' );
2646 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2648 wfDebug( __METHOD__
. ": not a redirect\n" );
2651 $text = Revision
::getRevisionText( $obj );
2653 # Does the redirect point to the source?
2654 # Or is it a broken self-redirect, usually caused by namespace collisions?
2656 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2657 $redirTitle = Title
::newFromText( $m[1] );
2658 if( !is_object( $redirTitle ) ||
2659 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2660 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2661 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2666 wfDebug( __METHOD__
. ": failsafe\n" );
2670 # Does the article have a history?
2671 $row = $dbw->selectRow( array( 'page', 'revision'),
2673 array( 'page_namespace' => $nt->getNamespace(),
2674 'page_title' => $nt->getDBkey(),
2675 'page_id=rev_page AND page_latest != rev_id'
2676 ), $fname, 'FOR UPDATE'
2679 # Return true if there was no history
2680 return $row === false;
2684 * Can this title be added to a user's watchlist?
2688 public function isWatchable() {
2689 return !$this->isExternal()
2690 && MWNamespace
::isWatchable( $this->getNamespace() );
2694 * Get categories to which this Title belongs and return an array of
2695 * categories' names.
2697 * @return array an array of parents in the form:
2698 * $parent => $currentarticle
2700 public function getParentCategories() {
2703 $titlekey = $this->getArticleId();
2704 $dbr = wfGetDB( DB_SLAVE
);
2705 $categorylinks = $dbr->tableName( 'categorylinks' );
2708 $sql = "SELECT * FROM $categorylinks"
2709 ." WHERE cl_from='$titlekey'"
2710 ." AND cl_from <> '0'"
2711 ." ORDER BY cl_sortkey";
2713 $res = $dbr->query ( $sql ) ;
2715 if($dbr->numRows($res) > 0) {
2716 while ( $x = $dbr->fetchObject ( $res ) )
2717 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2718 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2719 $dbr->freeResult ( $res ) ;
2727 * Get a tree of parent categories
2728 * @param array $children an array with the children in the keys, to check for circular refs
2731 public function getParentCategoryTree( $children = array() ) {
2733 $parents = $this->getParentCategories();
2735 if($parents != '') {
2736 foreach($parents as $parent => $current) {
2737 if ( array_key_exists( $parent, $children ) ) {
2738 # Circular reference
2739 $stack[$parent] = array();
2741 $nt = Title
::newFromText($parent);
2743 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2755 * Get an associative array for selecting this title from
2760 public function pageCond() {
2761 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2765 * Get the revision ID of the previous revision
2767 * @param integer $revision Revision ID. Get the revision that was before this one.
2768 * @return integer $oldrevision|false
2770 public function getPreviousRevisionID( $revision ) {
2771 $dbr = wfGetDB( DB_SLAVE
);
2772 return $dbr->selectField( 'revision', 'rev_id',
2773 'rev_page=' . intval( $this->getArticleId() ) .
2774 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2778 * Get the revision ID of the next revision
2780 * @param integer $revision Revision ID. Get the revision that was after this one.
2781 * @return integer $oldrevision|false
2783 public function getNextRevisionID( $revision ) {
2784 $dbr = wfGetDB( DB_SLAVE
);
2785 return $dbr->selectField( 'revision', 'rev_id',
2786 'rev_page=' . intval( $this->getArticleId() ) .
2787 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2791 * Get the number of revisions between the given revision IDs.
2793 * @param integer $old Revision ID.
2794 * @param integer $new Revision ID.
2795 * @return integer Number of revisions between these IDs.
2797 public function countRevisionsBetween( $old, $new ) {
2798 $dbr = wfGetDB( DB_SLAVE
);
2799 return $dbr->selectField( 'revision', 'count(*)',
2800 'rev_page = ' . intval( $this->getArticleId() ) .
2801 ' AND rev_id > ' . intval( $old ) .
2802 ' AND rev_id < ' . intval( $new ) );
2806 * Compare with another title.
2808 * @param Title $title
2811 public function equals( $title ) {
2812 // Note: === is necessary for proper matching of number-like titles.
2813 return $this->getInterwiki() === $title->getInterwiki()
2814 && $this->getNamespace() == $title->getNamespace()
2815 && $this->getDBkey() === $title->getDBkey();
2819 * Return a string representation of this title
2823 public function __toString() {
2824 return $this->getPrefixedText();
2828 * Check if page exists
2831 public function exists() {
2832 return $this->getArticleId() != 0;
2836 * Do we know that this title definitely exists, or should we otherwise
2837 * consider that it exists?
2841 public function isAlwaysKnown() {
2842 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
2843 // the full l10n of that language to be loaded. That takes much memory and
2844 // isn't needed. So we strip the language part away.
2845 // Also, extension messages which are not loaded, are shown as red, because
2846 // we don't call MessageCache::loadAllMessages.
2847 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
2848 return $this->isExternal()
2849 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2850 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
2854 * Update page_touched timestamps and send squid purge messages for
2855 * pages linking to this title. May be sent to the job queue depending
2856 * on the number of links. Typically called on create and delete.
2858 public function touchLinks() {
2859 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2862 if ( $this->getNamespace() == NS_CATEGORY
) {
2863 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2869 * Get the last touched timestamp
2871 public function getTouched() {
2872 $dbr = wfGetDB( DB_SLAVE
);
2873 $touched = $dbr->selectField( 'page', 'page_touched',
2875 'page_namespace' => $this->getNamespace(),
2876 'page_title' => $this->getDBkey()
2882 public function trackbackURL() {
2883 global $wgTitle, $wgScriptPath, $wgServer;
2885 return "$wgServer$wgScriptPath/trackback.php?article="
2886 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2889 public function trackbackRDF() {
2890 $url = htmlspecialchars($this->getFullURL());
2891 $title = htmlspecialchars($this->getText());
2892 $tburl = $this->trackbackURL();
2894 // Autodiscovery RDF is placed in comments so HTML validator
2895 // won't barf. This is a rather icky workaround, but seems
2896 // frequently used by this kind of RDF thingy.
2898 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
2900 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2901 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2902 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2905 dc:identifier=\"$url\"
2907 trackback:ping=\"$tburl\" />
2913 * Generate strings used for xml 'id' names in monobook tabs
2916 public function getNamespaceKey() {
2918 switch ($this->getNamespace()) {
2921 return 'nstab-main';
2924 return 'nstab-user';
2926 return 'nstab-media';
2928 return 'nstab-special';
2930 case NS_PROJECT_TALK
:
2931 return 'nstab-project';
2934 return 'nstab-image';
2936 case NS_MEDIAWIKI_TALK
:
2937 return 'nstab-mediawiki';
2939 case NS_TEMPLATE_TALK
:
2940 return 'nstab-template';
2943 return 'nstab-help';
2945 case NS_CATEGORY_TALK
:
2946 return 'nstab-category';
2948 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2953 * Returns true if this title resolves to the named special page
2954 * @param string $name The special page name
2956 public function isSpecial( $name ) {
2957 if ( $this->getNamespace() == NS_SPECIAL
) {
2958 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
2959 if ( $name == $thisName ) {
2967 * If the Title refers to a special page alias which is not the local default,
2968 * returns a new Title which points to the local default. Otherwise, returns $this.
2970 public function fixSpecialName() {
2971 if ( $this->getNamespace() == NS_SPECIAL
) {
2972 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
2973 if ( $canonicalName ) {
2974 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
2975 if ( $localName != $this->mDbkeyform
) {
2976 return Title
::makeTitle( NS_SPECIAL
, $localName );
2984 * Is this Title in a namespace which contains content?
2985 * In other words, is this a content page, for the purposes of calculating
2990 public function isContentPage() {
2991 return MWNamespace
::isContent( $this->getNamespace() );