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()
66 var $mLength; # The page length, 0 for special pages
67 var $mRedirect; # Is the article at this title a redirect?
75 /* private */ function __construct() {
76 $this->mInterwiki
= $this->mUrlform
=
77 $this->mTextform
= $this->mDbkeyform
= '';
78 $this->mArticleID
= -1;
79 $this->mNamespace
= NS_MAIN
;
80 $this->mRestrictionsLoaded
= false;
81 $this->mRestrictions
= array();
82 # Dont change the following, NS_MAIN is hardcoded in several place
84 $this->mDefaultNamespace
= NS_MAIN
;
85 $this->mWatched
= NULL;
86 $this->mLatestID
= false;
87 $this->mOldRestrictions
= false;
89 $this->mRedirect
= null;
93 * Create a new Title from a prefixed DB key
94 * @param string $key The database key, which has underscores
95 * instead of spaces, possibly including namespace and
97 * @return Title the new object, or NULL on an error
99 public static function newFromDBkey( $key ) {
101 $t->mDbkeyform
= $key;
102 if( $t->secureAndSplit() )
109 * Create a new Title from text, such as what one would
110 * find in a link. Decodes any HTML entities in the text.
112 * @param string $text the link text; spaces, prefixes,
113 * and an initial ':' indicating the main namespace
115 * @param int $defaultNamespace the namespace to use if
116 * none is specified by a prefix
117 * @return Title the new object, or NULL on an error
119 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
120 if( is_object( $text ) ) {
121 throw new MWException( 'Title::newFromText given an object' );
125 * Wiki pages often contain multiple links to the same page.
126 * Title normalization and parsing can become expensive on
127 * pages with many links, so we can save a little time by
130 * In theory these are value objects and won't get changed...
132 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
133 return Title
::$titleCache[$text];
137 * Convert things like é ā or 〗 into real text...
139 $filteredText = Sanitizer
::decodeCharReferences( $text );
142 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
143 $t->mDefaultNamespace
= $defaultNamespace;
145 static $cachedcount = 0 ;
146 if( $t->secureAndSplit() ) {
147 if( $defaultNamespace == NS_MAIN
) {
148 if( $cachedcount >= MW_TITLECACHE_MAX
) {
149 # Avoid memory leaks on mass operations...
150 Title
::$titleCache = array();
154 Title
::$titleCache[$text] =& $t;
164 * Create a new Title from URL-encoded text. Ensures that
165 * the given title's length does not exceed the maximum.
166 * @param string $url the title, as might be taken from a URL
167 * @return Title the new object, or NULL on an error
169 public static function newFromURL( $url ) {
170 global $wgLegalTitleChars;
173 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
174 # but some URLs used it as a space replacement and they still come
175 # from some external search tools.
176 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
177 $url = str_replace( '+', ' ', $url );
180 $t->mDbkeyform
= str_replace( ' ', '_', $url );
181 if( $t->secureAndSplit() ) {
189 * Create a new Title from an article ID
191 * @todo This is inefficiently implemented, the page row is requested
192 * but not used for anything else
194 * @param int $id the page_id corresponding to the Title to create
195 * @return Title the new object, or NULL on an error
197 public static function newFromID( $id ) {
198 $fname = 'Title::newFromID';
199 $dbr = wfGetDB( DB_SLAVE
);
200 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
201 array( 'page_id' => $id ), $fname );
202 if ( $row !== false ) {
203 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
211 * Make an array of titles from an array of IDs
213 public static function newFromIDs( $ids ) {
214 if ( !count( $ids ) ) {
217 $dbr = wfGetDB( DB_SLAVE
);
218 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
219 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
222 while ( $row = $dbr->fetchObject( $res ) ) {
223 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
229 * Make a Title object from a DB row
230 * @param Row $row (needs at least page_title,page_namespace)
232 public static function newFromRow( $row ) {
233 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
235 $t->mArticleID
= isset($row->page_id
) ?
$row->page_id
: -1;
236 $t->mLength
= isset($row->page_len
) ?
$row->page_len
: -1;
237 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
238 $t->mLatest
= isset($row->page_latest
) ?
$row->page_latest
: 0;
244 * Create a new Title from a namespace index and a DB key.
245 * It's assumed that $ns and $title are *valid*, for instance when
246 * they came directly from the database or a special page name.
247 * For convenience, spaces are converted to underscores so that
248 * eg user_text fields can be used directly.
250 * @param int $ns the namespace of the article
251 * @param string $title the unprefixed database key form
252 * @return Title the new object
254 public static function &makeTitle( $ns, $title ) {
258 $t->mNamespace
= $ns = intval( $ns );
259 $t->mDbkeyform
= str_replace( ' ', '_', $title );
260 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
261 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
262 $t->mTextform
= str_replace( '_', ' ', $title );
267 * Create a new Title from a namespace index and a DB key.
268 * The parameters will be checked for validity, which is a bit slower
269 * than makeTitle() but safer for user-provided data.
271 * @param int $ns the namespace of the article
272 * @param string $title the database key form
273 * @return Title the new object, or NULL on an error
275 public static function makeTitleSafe( $ns, $title ) {
277 $t->mDbkeyform
= Title
::makeName( $ns, $title );
278 if( $t->secureAndSplit() ) {
286 * Create a new Title for the Main Page
287 * @return Title the new object
289 public static function newMainPage() {
290 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
291 // Don't give fatal errors if the message is broken
293 $title = Title
::newFromText( 'Main Page' );
299 * Extract a redirect destination from a string and return the
300 * Title, or null if the text doesn't contain a valid redirect
302 * @param string $text Text with possible redirect
305 public static function newFromRedirect( $text ) {
306 $redir = MagicWord
::get( 'redirect' );
307 if( $redir->matchStart( trim($text) ) ) {
308 // Extract the first link and see if it's usable
310 if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
311 // Strip preceding colon used to "escape" categories, etc.
312 // and URL-decode links
313 if( strpos( $m[1], '%' ) !== false ) {
314 // Match behavior of inline link parsing here;
315 // don't interpret + as " " most of the time!
316 // It might be safe to just use rawurldecode instead, though.
317 $m[1] = urldecode( ltrim( $m[1], ':' ) );
319 $title = Title
::newFromText( $m[1] );
320 // Redirects to Special:Userlogout are not permitted
321 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
328 #----------------------------------------------------------------------------
330 #----------------------------------------------------------------------------
333 * Get the prefixed DB key associated with an ID
334 * @param int $id the page_id of the article
335 * @return Title an object representing the article, or NULL
336 * if no such article was found
340 function nameOf( $id ) {
341 $fname = 'Title::nameOf';
342 $dbr = wfGetDB( DB_SLAVE
);
344 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
345 if ( $s === false ) { return NULL; }
347 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
352 * Get a regex character class describing the legal characters in a link
353 * @return string the list of characters, not delimited
355 public static function legalChars() {
356 global $wgLegalTitleChars;
357 return $wgLegalTitleChars;
361 * Get a string representation of a title suitable for
362 * including in a search index
364 * @param int $ns a namespace index
365 * @param string $title text-form main part
366 * @return string a stripped-down title string ready for the
369 public static function indexTitle( $ns, $title ) {
372 $lc = SearchEngine
::legalSearchChars() . '&#;';
373 $t = $wgContLang->stripForSearch( $title );
374 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
375 $t = $wgContLang->lc( $t );
378 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
379 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
381 $t = preg_replace( "/\\s+/", ' ', $t );
383 if ( $ns == NS_IMAGE
) {
384 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
390 * Make a prefixed DB key from a DB key and a namespace index
391 * @param int $ns numerical representation of the namespace
392 * @param string $title the DB key form the title
393 * @return string the prefixed form of the title
395 public static function makeName( $ns, $title ) {
398 $n = $wgContLang->getNsText( $ns );
399 return $n == '' ?
$title : "$n:$title";
403 * Returns the URL associated with an interwiki prefix
404 * @param string $key the interwiki prefix (e.g. "MeatBall")
405 * @return the associated URL, containing "$1", which should be
406 * replaced by an article title
409 public function getInterwikiLink( $key ) {
410 global $wgMemc, $wgInterwikiExpiry;
411 global $wgInterwikiCache, $wgContLang;
412 $fname = 'Title::getInterwikiLink';
414 $key = $wgContLang->lc( $key );
416 $k = wfMemcKey( 'interwiki', $key );
417 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
418 return Title
::$interwikiCache[$k]->iw_url
;
421 if ($wgInterwikiCache) {
422 return Title
::getInterwikiCached( $key );
425 $s = $wgMemc->get( $k );
426 # Ignore old keys with no iw_local
427 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
428 Title
::$interwikiCache[$k] = $s;
432 $dbr = wfGetDB( DB_SLAVE
);
433 $res = $dbr->select( 'interwiki',
434 array( 'iw_url', 'iw_local', 'iw_trans' ),
435 array( 'iw_prefix' => $key ), $fname );
440 $s = $dbr->fetchObject( $res );
442 # Cache non-existence: create a blank object and save it to memcached
448 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
449 Title
::$interwikiCache[$k] = $s;
455 * Fetch interwiki prefix data from local cache in constant database
457 * More logic is explained in DefaultSettings
459 * @return string URL of interwiki site
461 public static function getInterwikiCached( $key ) {
462 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
466 $db=dba_open($wgInterwikiCache,'r','cdb');
467 /* Resolve site name */
468 if ($wgInterwikiScopes>=3 and !$site) {
469 $site = dba_fetch('__sites:' . wfWikiID(), $db);
471 $site = $wgInterwikiFallbackSite;
473 $value = dba_fetch( wfMemcKey( $key ), $db);
474 if ($value=='' and $wgInterwikiScopes>=3) {
476 $value = dba_fetch("_{$site}:{$key}", $db);
478 if ($value=='' and $wgInterwikiScopes>=2) {
480 $value = dba_fetch("__global:{$key}", $db);
489 list($local,$url)=explode(' ',$value,2);
491 $s->iw_local
=(int)$local;
493 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
497 * Determine whether the object refers to a page within
500 * @return bool TRUE if this is an in-project interwiki link
501 * or a wikilink, FALSE otherwise
503 public function isLocal() {
504 if ( $this->mInterwiki
!= '' ) {
505 # Make sure key is loaded into cache
506 $this->getInterwikiLink( $this->mInterwiki
);
507 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
508 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
515 * Determine whether the object refers to a page within
516 * this project and is transcludable.
518 * @return bool TRUE if this is transcludable
520 public function isTrans() {
521 if ($this->mInterwiki
== '')
523 # Make sure key is loaded into cache
524 $this->getInterwikiLink( $this->mInterwiki
);
525 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
526 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
530 * Escape a text fragment, say from a link, for a URL
532 static function escapeFragmentForURL( $fragment ) {
533 $fragment = str_replace( ' ', '_', $fragment );
534 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
535 $replaceArray = array(
539 return strtr( $fragment, $replaceArray );
542 #----------------------------------------------------------------------------
544 #----------------------------------------------------------------------------
546 /** Simple accessors */
548 * Get the text form (spaces not underscores) of the main part
551 public function getText() { return $this->mTextform
; }
553 * Get the URL-encoded form of the main part
556 public function getPartialURL() { return $this->mUrlform
; }
558 * Get the main part with underscores
561 public function getDBkey() { return $this->mDbkeyform
; }
563 * Get the namespace index, i.e. one of the NS_xxxx constants
566 public function getNamespace() { return $this->mNamespace
; }
568 * Get the namespace text
571 public function getNsText() {
572 global $wgContLang, $wgCanonicalNamespaceNames;
574 if ( '' != $this->mInterwiki
) {
575 // This probably shouldn't even happen. ohh man, oh yuck.
576 // But for interwiki transclusion it sometimes does.
577 // Shit. Shit shit shit.
579 // Use the canonical namespaces if possible to try to
580 // resolve a foreign namespace.
581 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
582 return $wgCanonicalNamespaceNames[$this->mNamespace
];
585 return $wgContLang->getNsText( $this->mNamespace
);
588 * Get the DB key with the initial letter case as specified by the user
590 function getUserCaseDBKey() {
591 return $this->mUserCaseDBKey
;
594 * Get the namespace text of the subject (rather than talk) page
597 public function getSubjectNsText() {
599 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
603 * Get the namespace text of the talk page
606 public function getTalkNsText() {
608 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
612 * Could this title have a corresponding talk page?
615 public function canTalk() {
616 return( MWNamespace
::canTalk( $this->mNamespace
) );
620 * Get the interwiki prefix (or null string)
623 public function getInterwiki() { return $this->mInterwiki
; }
625 * Get the Title fragment (i.e. the bit after the #) in text form
628 public function getFragment() { return $this->mFragment
; }
630 * Get the fragment in URL form, including the "#" character if there is one
633 public function getFragmentForURL() {
634 if ( $this->mFragment
== '' ) {
637 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
641 * Get the default namespace index, for when there is no namespace
644 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
647 * Get title for search index
648 * @return string a stripped-down title string ready for the
651 public function getIndexTitle() {
652 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
656 * Get the prefixed database key form
657 * @return string the prefixed title, with underscores and
658 * any interwiki and namespace prefixes
660 public function getPrefixedDBkey() {
661 $s = $this->prefix( $this->mDbkeyform
);
662 $s = str_replace( ' ', '_', $s );
667 * Get the prefixed title with spaces.
668 * This is the form usually used for display
669 * @return string the prefixed title, with spaces
671 public function getPrefixedText() {
672 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
673 $s = $this->prefix( $this->mTextform
);
674 $s = str_replace( '_', ' ', $s );
675 $this->mPrefixedText
= $s;
677 return $this->mPrefixedText
;
681 * Get the prefixed title with spaces, plus any fragment
682 * (part beginning with '#')
683 * @return string the prefixed title, with spaces and
684 * the fragment, including '#'
686 public function getFullText() {
687 $text = $this->getPrefixedText();
688 if( '' != $this->mFragment
) {
689 $text .= '#' . $this->mFragment
;
695 * Get the base name, i.e. the leftmost parts before the /
696 * @return string Base name
698 public function getBaseText() {
699 global $wgNamespacesWithSubpages;
700 if( !empty( $wgNamespacesWithSubpages[$this->mNamespace
] ) ) {
701 $parts = explode( '/', $this->getText() );
702 # Don't discard the real title if there's no subpage involved
703 if( count( $parts ) > 1 )
704 unset( $parts[ count( $parts ) - 1 ] );
705 return implode( '/', $parts );
707 return $this->getText();
712 * Get the lowest-level subpage name, i.e. the rightmost part after /
713 * @return string Subpage name
715 public function getSubpageText() {
716 global $wgNamespacesWithSubpages;
717 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
718 $parts = explode( '/', $this->mTextform
);
719 return( $parts[ count( $parts ) - 1 ] );
721 return( $this->mTextform
);
726 * Get a URL-encoded form of the subpage text
727 * @return string URL-encoded subpage name
729 public function getSubpageUrlForm() {
730 $text = $this->getSubpageText();
731 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
732 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
737 * Get a URL-encoded title (not an actual URL) including interwiki
738 * @return string the URL-encoded form
740 public function getPrefixedURL() {
741 $s = $this->prefix( $this->mDbkeyform
);
742 $s = str_replace( ' ', '_', $s );
744 $s = wfUrlencode ( $s ) ;
746 # Cleaning up URL to make it look nice -- is this safe?
747 $s = str_replace( '%28', '(', $s );
748 $s = str_replace( '%29', ')', $s );
754 * Get a real URL referring to this title, with interwiki link and
757 * @param string $query an optional query string, not used
758 * for interwiki links
759 * @param string $variant language variant of url (for sr, zh..)
760 * @return string the URL
762 public function getFullURL( $query = '', $variant = false ) {
763 global $wgContLang, $wgServer, $wgRequest;
765 if ( '' == $this->mInterwiki
) {
766 $url = $this->getLocalUrl( $query, $variant );
768 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
769 // Correct fix would be to move the prepending elsewhere.
770 if ($wgRequest->getVal('action') != 'render') {
771 $url = $wgServer . $url;
774 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
776 $namespace = wfUrlencode( $this->getNsText() );
777 if ( '' != $namespace ) {
778 # Can this actually happen? Interwikis shouldn't be parsed.
779 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
782 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
783 $url = wfAppendQuery( $url, $query );
786 # Finally, add the fragment.
787 $url .= $this->getFragmentForURL();
789 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
794 * Get a URL with no fragment or server name. If this page is generated
795 * with action=render, $wgServer is prepended.
796 * @param string $query an optional query string; if not specified,
797 * $wgArticlePath will be used.
798 * @param string $variant language variant of url (for sr, zh..)
799 * @return string the URL
801 public function getLocalURL( $query = '', $variant = false ) {
802 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
803 global $wgVariantArticlePath, $wgContLang, $wgUser;
805 // internal links should point to same variant as current page (only anonymous users)
806 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
807 $pref = $wgContLang->getPreferredVariant(false);
808 if($pref != $wgContLang->getCode())
812 if ( $this->isExternal() ) {
813 $url = $this->getFullURL();
815 // This is currently only used for edit section links in the
816 // context of interwiki transclusion. In theory we should
817 // append the query to the end of any existing query string,
818 // but interwiki transclusion is already broken in that case.
822 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
823 if ( $query == '' ) {
824 if( $variant != false && $wgContLang->hasVariants() ) {
825 if( $wgVariantArticlePath == false ) {
826 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
828 $variantArticlePath = $wgVariantArticlePath;
830 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
831 $url = str_replace( '$1', $dbkey, $url );
833 $url = str_replace( '$1', $dbkey, $wgArticlePath );
836 global $wgActionPaths;
839 if( !empty( $wgActionPaths ) &&
840 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
842 $action = urldecode( $matches[2] );
843 if( isset( $wgActionPaths[$action] ) ) {
844 $query = $matches[1];
845 if( isset( $matches[4] ) ) $query .= $matches[4];
846 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
847 if( $query != '' ) $url .= '?' . $query;
850 if ( $url === false ) {
851 if ( $query == '-' ) {
854 $url = "{$wgScript}?title={$dbkey}&{$query}";
858 // FIXME: this causes breakage in various places when we
859 // actually expected a local URL and end up with dupe prefixes.
860 if ($wgRequest->getVal('action') == 'render') {
861 $url = $wgServer . $url;
864 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
869 * Get an HTML-escaped version of the URL form, suitable for
870 * using in a link, without a server name or fragment
871 * @param string $query an optional query string
872 * @return string the URL
874 public function escapeLocalURL( $query = '' ) {
875 return htmlspecialchars( $this->getLocalURL( $query ) );
879 * Get an HTML-escaped version of the URL form, suitable for
880 * using in a link, including the server name and fragment
882 * @return string the URL
883 * @param string $query an optional query string
885 public function escapeFullURL( $query = '' ) {
886 return htmlspecialchars( $this->getFullURL( $query ) );
890 * Get the URL form for an internal link.
891 * - Used in various Squid-related code, in case we have a different
892 * internal hostname for the server from the exposed one.
894 * @param string $query an optional query string
895 * @param string $variant language variant of url (for sr, zh..)
896 * @return string the URL
898 public function getInternalURL( $query = '', $variant = false ) {
899 global $wgInternalServer;
900 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
901 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
906 * Get the edit URL for this Title
907 * @return string the URL, or a null string if this is an
910 public function getEditURL() {
911 if ( '' != $this->mInterwiki
) { return ''; }
912 $s = $this->getLocalURL( 'action=edit' );
918 * Get the HTML-escaped displayable text form.
919 * Used for the title field in <a> tags.
920 * @return string the text, including any prefixes
922 public function getEscapedText() {
923 return htmlspecialchars( $this->getPrefixedText() );
927 * Is this Title interwiki?
930 public function isExternal() { return ( '' != $this->mInterwiki
); }
933 * Is this page "semi-protected" - the *only* protection is autoconfirm?
935 * @param string Action to check (default: edit)
938 public function isSemiProtected( $action = 'edit' ) {
939 if( $this->exists() ) {
940 $restrictions = $this->getRestrictions( $action );
941 if( count( $restrictions ) > 0 ) {
942 foreach( $restrictions as $restriction ) {
943 if( strtolower( $restriction ) != 'autoconfirmed' )
952 # If it doesn't exist, it can't be protected
958 * Does the title correspond to a protected article?
959 * @param string $what the action the page is protected from,
960 * by default checks move and edit
963 public function isProtected( $action = '' ) {
964 global $wgRestrictionLevels, $wgRestrictionTypes;
966 # Special pages have inherent protection
967 if( $this->getNamespace() == NS_SPECIAL
)
970 # Check regular protection levels
971 foreach( $wgRestrictionTypes as $type ){
972 if( $action == $type ||
$action == '' ) {
973 $r = $this->getRestrictions( $type );
974 foreach( $wgRestrictionLevels as $level ) {
975 if( in_array( $level, $r ) && $level != '' ) {
986 * Is $wgUser watching this page?
989 public function userIsWatching() {
992 if ( is_null( $this->mWatched
) ) {
993 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
994 $this->mWatched
= false;
996 $this->mWatched
= $wgUser->isWatched( $this );
999 return $this->mWatched
;
1003 * Can $wgUser perform $action on this page?
1004 * This skips potentially expensive cascading permission checks.
1006 * Suitable for use for nonessential UI controls in common cases, but
1007 * _not_ for functional access control.
1009 * May provide false positives, but should never provide a false negative.
1011 * @param string $action action that permission needs to be checked for
1014 public function quickUserCan( $action ) {
1015 return $this->userCan( $action, false );
1019 * Determines if $wgUser is unable to edit this page because it has been protected
1020 * by $wgNamespaceProtection.
1024 public function isNamespaceProtected() {
1025 global $wgNamespaceProtection, $wgUser;
1026 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1027 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1028 if( $right != '' && !$wgUser->isAllowed( $right ) )
1036 * Can $wgUser perform $action on this page?
1037 * @param string $action action that permission needs to be checked for
1038 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1041 public function userCan( $action, $doExpensiveQueries = true ) {
1043 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1047 * Can $user perform $action on this page?
1049 * FIXME: This *does not* check throttles (User::pingLimiter()).
1051 * @param string $action action that permission needs to be checked for
1052 * @param User $user user to check
1053 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1054 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1056 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1057 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1061 global $wgEmailConfirmToEdit;
1063 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1064 $errors[] = array( 'confirmedittext' );
1067 if ( $user->isBlockedFrom( $this ) ) {
1068 $block = $user->mBlock
;
1070 // This is from OutputPage::blockedPage
1071 // Copied at r23888 by werdna
1073 $id = $user->blockedBy();
1074 $reason = $user->blockedFor();
1075 if( $reason == '' ) {
1076 $reason = wfMsg( 'blockednoreason' );
1080 if ( is_numeric( $id ) ) {
1081 $name = User
::whoIs( $id );
1086 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1087 $blockid = $block->mId
;
1088 $blockExpiry = $user->mBlock
->mExpiry
;
1089 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1091 if ( $blockExpiry == 'infinity' ) {
1092 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1093 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1095 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1096 if ( strpos( $option, ':' ) == false )
1099 list ($show, $value) = explode( ":", $option );
1101 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1102 $blockExpiry = $show;
1107 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1110 $intended = $user->mBlock
->mAddress
;
1112 $errors[] = array ( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1119 * Can $user perform $action on this page? This is an internal function,
1120 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1121 * checks on wfReadOnly() and blocks)
1123 * @param string $action action that permission needs to be checked for
1124 * @param User $user user to check
1125 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1126 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1128 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1129 wfProfileIn( __METHOD__
);
1133 // Use getUserPermissionsErrors instead
1134 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1135 return $result ?
array() : array( array( 'badaccess-group0' ) );
1138 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1139 if ($result != array() && is_array($result) && !is_array($result[0]))
1140 $errors[] = $result; # A single array representing an error
1141 else if (is_array($result) && is_array($result[0]))
1142 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1143 else if ($result != '' && $result != null && $result !== true && $result !== false)
1144 $errors[] = array($result); # A string representing a message-id
1145 else if ($result === false )
1146 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1148 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1149 if ($result != array() && is_array($result) && !is_array($result[0]))
1150 $errors[] = $result; # A single array representing an error
1151 else if (is_array($result) && is_array($result[0]))
1152 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1153 else if ($result != '' && $result != null && $result !== true && $result !== false)
1154 $errors[] = array($result); # A string representing a message-id
1155 else if ($result === false )
1156 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1159 if( NS_SPECIAL
== $this->mNamespace
) {
1160 $errors[] = array('ns-specialprotected');
1163 if ( $this->isNamespaceProtected() ) {
1164 $ns = $this->getNamespace() == NS_MAIN
1165 ?
wfMsg( 'nstab-main' )
1166 : $this->getNsText();
1167 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1168 ?
array('protectedinterface')
1169 : array( 'namespaceprotected', $ns ) );
1172 if( $this->mDbkeyform
== '_' ) {
1173 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1174 $errors[] = array('badaccess-group0');
1177 # protect css/js subpages of user pages
1178 # XXX: this might be better using restrictions
1179 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1180 if( $this->isCssJsSubpage()
1181 && !$user->isAllowed('editusercssjs')
1182 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1183 $errors[] = array('customcssjsprotected');
1186 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1187 # We /could/ use the protection level on the source page, but it's fairly ugly
1188 # as we have to establish a precedence hierarchy for pages included by multiple
1189 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1190 # as they could remove the protection anyway.
1191 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1192 # Cascading protection depends on more than this page...
1193 # Several cascading protected pages may include this page...
1194 # Check each cascading level
1195 # This is only for protection restrictions, not for all actions
1196 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1197 foreach( $restrictions[$action] as $right ) {
1198 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1199 if( '' != $right && !$user->isAllowed( $right ) ) {
1201 foreach( $cascadingSources as $page )
1202 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1203 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1209 foreach( $this->getRestrictions($action) as $right ) {
1210 // Backwards compatibility, rewrite sysop -> protect
1211 if ( $right == 'sysop' ) {
1214 if( '' != $right && !$user->isAllowed( $right ) ) {
1215 //Users with 'editprotected' permission can edit protected pages
1216 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1217 //Users with 'editprotected' permission cannot edit protected pages
1218 //with cascading option turned on.
1219 if($this->mCascadeRestriction
) {
1220 $errors[] = array( 'protectedpagetext', $right );
1222 //Nothing, user can edit!
1225 $errors[] = array( 'protectedpagetext', $right );
1230 if ($action == 'protect') {
1231 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1232 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1236 if ($action == 'create') {
1237 $title_protection = $this->getTitleProtection();
1239 if (is_array($title_protection)) {
1240 extract($title_protection);
1242 if ($pt_create_perm == 'sysop')
1243 $pt_create_perm = 'protect';
1245 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1246 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1250 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1251 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1252 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1254 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1255 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1256 } elseif ( !$user->isAllowed( $action ) ) {
1259 global $wgGroupPermissions;
1260 foreach( $wgGroupPermissions as $key => $value ) {
1261 if( isset( $value[$action] ) && $value[$action] == true ) {
1262 $groupName = User
::getGroupName( $key );
1263 $groupPage = User
::getGroupPage( $key );
1265 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1267 $groups[] = $groupName;
1271 $n = count( $groups );
1272 $groups = implode( ', ', $groups );
1277 $return = array( "badaccess-group$n", $groups );
1280 $return = array( 'badaccess-groups', $groups );
1282 $errors[] = $return;
1285 wfProfileOut( __METHOD__
);
1290 * Is this title subject to title protection?
1291 * @return mixed An associative array representing any existent title
1292 * protection, or false if there's none.
1294 private function getTitleProtection() {
1295 // Can't protect pages in special namespaces
1296 if ( $this->getNamespace() < 0 ) {
1300 $dbr = wfGetDB( DB_SLAVE
);
1301 $res = $dbr->select( 'protected_titles', '*',
1302 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1304 if ($row = $dbr->fetchRow( $res )) {
1311 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1312 global $wgGroupPermissions,$wgUser,$wgContLang;
1314 if ($create_perm == implode(',',$this->getRestrictions('create'))
1315 && $expiry == $this->mRestrictionsExpiry
) {
1320 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1322 $dbw = wfGetDB( DB_MASTER
);
1324 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1326 $expiry_description = '';
1327 if ( $encodedExpiry != 'infinity' ) {
1328 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1331 # Update protection table
1332 if ($create_perm != '' ) {
1333 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1334 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1335 , 'pt_create_perm' => $create_perm
1336 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1337 , 'pt_expiry' => $encodedExpiry
1338 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1340 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1341 'pt_title' => $title ), __METHOD__
);
1343 # Update the protection log
1344 $log = new LogPage( 'protect' );
1346 if( $create_perm ) {
1347 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1349 $log->addEntry( 'unprotect', $this, $reason );
1356 * Remove any title protection (due to page existing
1358 public function deleteTitleProtection() {
1359 $dbw = wfGetDB( DB_MASTER
);
1361 $dbw->delete( 'protected_titles',
1362 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1366 * Can $wgUser edit this page?
1368 * @deprecated use userCan('edit')
1370 public function userCanEdit( $doExpensiveQueries = true ) {
1371 return $this->userCan( 'edit', $doExpensiveQueries );
1375 * Can $wgUser create this page?
1377 * @deprecated use userCan('create')
1379 public function userCanCreate( $doExpensiveQueries = true ) {
1380 return $this->userCan( 'create', $doExpensiveQueries );
1384 * Can $wgUser move this page?
1386 * @deprecated use userCan('move')
1388 public function userCanMove( $doExpensiveQueries = true ) {
1389 return $this->userCan( 'move', $doExpensiveQueries );
1393 * Would anybody with sufficient privileges be able to move this page?
1394 * Some pages just aren't movable.
1398 public function isMovable() {
1399 return MWNamespace
::isMovable( $this->getNamespace() )
1400 && $this->getInterwiki() == '';
1404 * Can $wgUser read this page?
1406 * @todo fold these checks into userCan()
1408 public function userCanRead() {
1409 global $wgUser, $wgGroupPermissions;
1412 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1413 if ( $result !== null ) {
1417 # Shortcut for public wikis, allows skipping quite a bit of code
1418 if ($wgGroupPermissions['*']['read'])
1421 if( $wgUser->isAllowed( 'read' ) ) {
1424 global $wgWhitelistRead;
1427 * Always grant access to the login page.
1428 * Even anons need to be able to log in.
1430 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1435 * Bail out if there isn't whitelist
1437 if( !is_array($wgWhitelistRead) ) {
1442 * Check for explicit whitelisting
1444 $name = $this->getPrefixedText();
1445 if( in_array( $name, $wgWhitelistRead, true ) )
1449 * Old settings might have the title prefixed with
1450 * a colon for main-namespace pages
1452 if( $this->getNamespace() == NS_MAIN
) {
1453 if( in_array( ':' . $name, $wgWhitelistRead ) )
1458 * If it's a special page, ditch the subpage bit
1461 if( $this->getNamespace() == NS_SPECIAL
) {
1462 $name = $this->getDBkey();
1463 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1464 if ( $name === false ) {
1465 # Invalid special page, but we show standard login required message
1469 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1470 if( in_array( $pure, $wgWhitelistRead, true ) )
1479 * Is this a talk page of some sort?
1482 public function isTalkPage() {
1483 return MWNamespace
::isTalk( $this->getNamespace() );
1487 * Is this an article that is a redirect page?
1490 public function isRedirect() {
1491 if( $this->mRedirect
!== null )
1492 return $this->mRedirect
;
1493 # Zero for special pages
1494 if( $this->getNamespace() == NS_SPECIAL
)
1497 $dbr = wfGetDB( DB_SLAVE
);
1498 $redir = $dbr->selectField( 'page', 'page_is_redirect',
1499 array( 'page_id' => $this->getArticleId() ),
1502 $this->mRedirect
= (bool)$redir;
1504 return $this->mRedirect
;
1508 * What is the length of this page?
1511 public function getLength() {
1512 if( $this->mLength
!= -1 ||
$this->mArticleID
== 0 )
1513 return $this->mLength
;
1514 # Zero for special pages
1515 if( $this->getNamespace() == NS_SPECIAL
)
1518 $dbr = wfGetDB( DB_SLAVE
);
1519 $len = $dbr->selectField( 'page', 'page_len',
1520 array( 'page_id' => $this->getArticleId() ),
1522 $this->mLength
= intval($len);
1524 return $this->mLength
;
1528 * Is this a subpage?
1531 public function isSubpage() {
1532 global $wgNamespacesWithSubpages;
1534 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) ) {
1535 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace
] == true );
1542 * Could this page contain custom CSS or JavaScript, based
1547 public function isCssOrJsPage() {
1548 return $this->mNamespace
== NS_MEDIAWIKI
1549 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1553 * Is this a .css or .js subpage of a user page?
1556 public function isCssJsSubpage() {
1557 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1560 * Is this a *valid* .css or .js subpage of a user page?
1561 * Check that the corresponding skin exists
1563 public function isValidCssJsSubpage() {
1564 if ( $this->isCssJsSubpage() ) {
1565 $skinNames = Skin
::getSkinNames();
1566 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1572 * Trim down a .css or .js subpage title to get the corresponding skin name
1574 public function getSkinFromCssJsSubpage() {
1575 $subpage = explode( '/', $this->mTextform
);
1576 $subpage = $subpage[ count( $subpage ) - 1 ];
1577 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1580 * Is this a .css subpage of a user page?
1583 public function isCssSubpage() {
1584 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1587 * Is this a .js subpage of a user page?
1590 public function isJsSubpage() {
1591 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1594 * Protect css/js subpages of user pages: can $wgUser edit
1598 * @todo XXX: this might be better using restrictions
1600 public function userCanEditCssJsSubpage() {
1602 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1606 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1608 * @return bool If the page is subject to cascading restrictions.
1610 public function isCascadeProtected() {
1611 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1612 return ( $sources > 0 );
1616 * Cascading protection: Get the source of any cascading restrictions on this page.
1618 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1619 * @return array( mixed title array, restriction array)
1620 * 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.
1621 * The restriction array is an array of each type, each of which contains an array of unique groups
1623 public function getCascadeProtectionSources( $get_pages = true ) {
1624 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1626 # Define our dimension of restrictions types
1627 $pagerestrictions = array();
1628 foreach( $wgRestrictionTypes as $action )
1629 $pagerestrictions[$action] = array();
1631 if (!$wgEnableCascadingProtection)
1632 return array( false, $pagerestrictions );
1634 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1635 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1636 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1637 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1640 wfProfileIn( __METHOD__
);
1642 $dbr = wfGetDb( DB_SLAVE
);
1644 if ( $this->getNamespace() == NS_IMAGE
) {
1645 $tables = array ('imagelinks', 'page_restrictions');
1646 $where_clauses = array(
1647 'il_to' => $this->getDBkey(),
1649 'pr_cascade' => 1 );
1651 $tables = array ('templatelinks', 'page_restrictions');
1652 $where_clauses = array(
1653 'tl_namespace' => $this->getNamespace(),
1654 'tl_title' => $this->getDBkey(),
1656 'pr_cascade' => 1 );
1660 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1661 $where_clauses[] = 'page_id=pr_page';
1664 $cols = array( 'pr_expiry' );
1667 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1669 $sources = $get_pages ?
array() : false;
1670 $now = wfTimestampNow();
1671 $purgeExpired = false;
1673 while( $row = $dbr->fetchObject( $res ) ) {
1674 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1675 if( $expiry > $now ) {
1677 $page_id = $row->pr_page
;
1678 $page_ns = $row->page_namespace
;
1679 $page_title = $row->page_title
;
1680 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1681 # Add groups needed for each restriction type if its not already there
1682 # Make sure this restriction type still exists
1683 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1684 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1690 // Trigger lazy purge of expired restrictions from the db
1691 $purgeExpired = true;
1694 if( $purgeExpired ) {
1695 Title
::purgeExpiredRestrictions();
1698 wfProfileOut( __METHOD__
);
1701 $this->mCascadeSources
= $sources;
1702 $this->mCascadingRestrictions
= $pagerestrictions;
1704 $this->mHasCascadingRestrictions
= $sources;
1707 return array( $sources, $pagerestrictions );
1710 function areRestrictionsCascading() {
1711 if (!$this->mRestrictionsLoaded
) {
1712 $this->loadRestrictions();
1715 return $this->mCascadeRestriction
;
1719 * Loads a string into mRestrictions array
1720 * @param resource $res restrictions as an SQL result.
1722 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1723 global $wgRestrictionTypes;
1724 $dbr = wfGetDB( DB_SLAVE
);
1726 foreach( $wgRestrictionTypes as $type ){
1727 $this->mRestrictions
[$type] = array();
1730 $this->mCascadeRestriction
= false;
1731 $this->mRestrictionsExpiry
= Block
::decodeExpiry('');
1733 # Backwards-compatibility: also load the restrictions from the page record (old format).
1735 if ( $oldFashionedRestrictions == NULL ) {
1736 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1739 if ($oldFashionedRestrictions != '') {
1741 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1742 $temp = explode( '=', trim( $restrict ) );
1743 if(count($temp) == 1) {
1744 // old old format should be treated as edit/move restriction
1745 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1746 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1748 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1752 $this->mOldRestrictions
= true;
1756 if( $dbr->numRows( $res ) ) {
1757 # Current system - load second to make them override.
1758 $now = wfTimestampNow();
1759 $purgeExpired = false;
1761 while ($row = $dbr->fetchObject( $res ) ) {
1762 # Cycle through all the restrictions.
1764 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1765 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1768 // This code should be refactored, now that it's being used more generally,
1769 // But I don't really see any harm in leaving it in Block for now -werdna
1770 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1772 // Only apply the restrictions if they haven't expired!
1773 if ( !$expiry ||
$expiry > $now ) {
1774 $this->mRestrictionsExpiry
= $expiry;
1775 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1777 $this->mCascadeRestriction |
= $row->pr_cascade
;
1779 // Trigger a lazy purge of expired restrictions
1780 $purgeExpired = true;
1784 if( $purgeExpired ) {
1785 Title
::purgeExpiredRestrictions();
1789 $this->mRestrictionsLoaded
= true;
1792 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1793 if( !$this->mRestrictionsLoaded
) {
1794 if ($this->exists()) {
1795 $dbr = wfGetDB( DB_SLAVE
);
1797 $res = $dbr->select( 'page_restrictions', '*',
1798 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1800 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1802 $title_protection = $this->getTitleProtection();
1804 if (is_array($title_protection)) {
1805 extract($title_protection);
1807 $now = wfTimestampNow();
1808 $expiry = Block
::decodeExpiry($pt_expiry);
1810 if (!$expiry ||
$expiry > $now) {
1811 // Apply the restrictions
1812 $this->mRestrictionsExpiry
= $expiry;
1813 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1814 } else { // Get rid of the old restrictions
1815 Title
::purgeExpiredRestrictions();
1818 $this->mRestrictionsLoaded
= true;
1824 * Purge expired restrictions from the page_restrictions table
1826 static function purgeExpiredRestrictions() {
1827 $dbw = wfGetDB( DB_MASTER
);
1828 $dbw->delete( 'page_restrictions',
1829 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1832 $dbw->delete( 'protected_titles',
1833 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1838 * Accessor/initialisation for mRestrictions
1840 * @param string $action action that permission needs to be checked for
1841 * @return array the array of groups allowed to edit this article
1843 public function getRestrictions( $action ) {
1844 if( !$this->mRestrictionsLoaded
) {
1845 $this->loadRestrictions();
1847 return isset( $this->mRestrictions
[$action] )
1848 ?
$this->mRestrictions
[$action]
1853 * Is there a version of this page in the deletion archive?
1854 * @return int the number of archived revisions
1856 public function isDeleted() {
1857 $fname = 'Title::isDeleted';
1858 if ( $this->getNamespace() < 0 ) {
1861 $dbr = wfGetDB( DB_SLAVE
);
1862 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1863 'ar_title' => $this->getDBkey() ), $fname );
1864 if( $this->getNamespace() == NS_IMAGE
) {
1865 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1866 array( 'fa_name' => $this->getDBkey() ), $fname );
1873 * Get the article ID for this Title from the link cache,
1874 * adding it if necessary
1875 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1877 * @return int the ID
1879 public function getArticleID( $flags = 0 ) {
1880 $linkCache =& LinkCache
::singleton();
1881 if ( $flags & GAID_FOR_UPDATE
) {
1882 $oldUpdate = $linkCache->forUpdate( true );
1883 $this->mArticleID
= $linkCache->addLinkObj( $this );
1884 $linkCache->forUpdate( $oldUpdate );
1886 if ( -1 == $this->mArticleID
) {
1887 $this->mArticleID
= $linkCache->addLinkObj( $this );
1890 return $this->mArticleID
;
1893 public function getLatestRevID() {
1894 if ($this->mLatestID
!== false)
1895 return $this->mLatestID
;
1897 $db = wfGetDB(DB_SLAVE
);
1898 return $this->mLatestID
= $db->selectField( 'revision',
1900 array('rev_page' => $this->getArticleID()),
1901 'Title::getLatestRevID' );
1905 * This clears some fields in this object, and clears any associated
1906 * keys in the "bad links" section of the link cache.
1908 * - This is called from Article::insertNewArticle() to allow
1909 * loading of the new page_id. It's also called from
1910 * Article::doDeleteArticle()
1912 * @param int $newid the new Article ID
1914 public function resetArticleID( $newid ) {
1915 $linkCache =& LinkCache
::singleton();
1916 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1918 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1919 else { $this->mArticleID
= $newid; }
1920 $this->mRestrictionsLoaded
= false;
1921 $this->mRestrictions
= array();
1925 * Updates page_touched for this page; called from LinksUpdate.php
1926 * @return bool true if the update succeded
1928 public function invalidateCache() {
1929 global $wgUseFileCache;
1931 if ( wfReadOnly() ) {
1935 $dbw = wfGetDB( DB_MASTER
);
1936 $success = $dbw->update( 'page',
1938 'page_touched' => $dbw->timestamp()
1939 ), array( /* WHERE */
1940 'page_namespace' => $this->getNamespace() ,
1941 'page_title' => $this->getDBkey()
1942 ), 'Title::invalidateCache'
1945 if ($wgUseFileCache) {
1946 $cache = new HTMLFileCache($this);
1947 @unlink
($cache->fileCacheName());
1954 * Prefix some arbitrary text with the namespace or interwiki prefix
1957 * @param string $name the text
1958 * @return string the prefixed text
1961 /* private */ function prefix( $name ) {
1963 if ( '' != $this->mInterwiki
) {
1964 $p = $this->mInterwiki
. ':';
1966 if ( 0 != $this->mNamespace
) {
1967 $p .= $this->getNsText() . ':';
1973 * Secure and split - main initialisation function for this object
1975 * Assumes that mDbkeyform has been set, and is urldecoded
1976 * and uses underscores, but not otherwise munged. This function
1977 * removes illegal characters, splits off the interwiki and
1978 * namespace prefixes, sets the other forms, and canonicalizes
1980 * @return bool true on success
1982 private function secureAndSplit() {
1983 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1986 static $rxTc = false;
1988 # Matching titles will be held as illegal.
1990 # Any character not allowed is forbidden...
1991 '[^' . Title
::legalChars() . ']' .
1992 # URL percent encoding sequences interfere with the ability
1993 # to round-trip titles -- you can't link to them consistently.
1994 '|%[0-9A-Fa-f]{2}' .
1995 # XML/HTML character references produce similar issues.
1996 '|&[A-Za-z0-9\x80-\xff]+;' .
1998 '|&#x[0-9A-Fa-f]+;' .
2002 $this->mInterwiki
= $this->mFragment
= '';
2003 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2005 $dbkey = $this->mDbkeyform
;
2007 # Strip Unicode bidi override characters.
2008 # Sometimes they slip into cut-n-pasted page titles, where the
2009 # override chars get included in list displays.
2010 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2011 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2013 # Clean up whitespace
2015 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2016 $dbkey = trim( $dbkey, '_' );
2018 if ( '' == $dbkey ) {
2022 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2023 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2027 $this->mDbkeyform
= $dbkey;
2029 # Initial colon indicates main namespace rather than specified default
2030 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2031 if ( ':' == $dbkey{0} ) {
2032 $this->mNamespace
= NS_MAIN
;
2033 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2034 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2037 # Namespace or interwiki prefix
2041 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2043 if ( $ns = $wgContLang->getNsIndex( $p )) {
2044 # Ordinary namespace
2046 $this->mNamespace
= $ns;
2047 } elseif( $this->getInterwikiLink( $p ) ) {
2049 # Can't make a local interwiki link to an interwiki link.
2050 # That's just crazy!
2056 $this->mInterwiki
= $wgContLang->lc( $p );
2058 # Redundant interwiki prefix to the local wiki
2059 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2060 if( $dbkey == '' ) {
2061 # Can't have an empty self-link
2064 $this->mInterwiki
= '';
2066 # Do another namespace split...
2070 # If there's an initial colon after the interwiki, that also
2071 # resets the default namespace
2072 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2073 $this->mNamespace
= NS_MAIN
;
2074 $dbkey = substr( $dbkey, 1 );
2077 # If there's no recognized interwiki or namespace,
2078 # then let the colon expression be part of the title.
2083 # We already know that some pages won't be in the database!
2085 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2086 $this->mArticleID
= 0;
2088 $fragment = strstr( $dbkey, '#' );
2089 if ( false !== $fragment ) {
2090 $this->setFragment( $fragment );
2091 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2092 # remove whitespace again: prevents "Foo_bar_#"
2093 # becoming "Foo_bar_"
2094 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2097 # Reject illegal characters.
2099 if( preg_match( $rxTc, $dbkey ) ) {
2104 * Pages with "/./" or "/../" appearing in the URLs will
2105 * often be unreachable due to the way web browsers deal
2106 * with 'relative' URLs. Forbid them explicitly.
2108 if ( strpos( $dbkey, '.' ) !== false &&
2109 ( $dbkey === '.' ||
$dbkey === '..' ||
2110 strpos( $dbkey, './' ) === 0 ||
2111 strpos( $dbkey, '../' ) === 0 ||
2112 strpos( $dbkey, '/./' ) !== false ||
2113 strpos( $dbkey, '/../' ) !== false ||
2114 substr( $dbkey, -2 ) == '/.' ||
2115 substr( $dbkey, -3 ) == '/..' ) )
2121 * Magic tilde sequences? Nu-uh!
2123 if( strpos( $dbkey, '~~~' ) !== false ) {
2128 * Limit the size of titles to 255 bytes.
2129 * This is typically the size of the underlying database field.
2130 * We make an exception for special pages, which don't need to be stored
2131 * in the database, and may edge over 255 bytes due to subpage syntax
2132 * for long titles, e.g. [[Special:Block/Long name]]
2134 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2135 strlen( $dbkey ) > 512 )
2141 * Normally, all wiki links are forced to have
2142 * an initial capital letter so [[foo]] and [[Foo]]
2143 * point to the same place.
2145 * Don't force it for interwikis, since the other
2146 * site might be case-sensitive.
2148 $this->mUserCaseDBKey
= $dbkey;
2149 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2150 $dbkey = $wgContLang->ucfirst( $dbkey );
2154 * Can't make a link to a namespace alone...
2155 * "empty" local links can only be self-links
2156 * with a fragment identifier.
2159 $this->mInterwiki
== '' &&
2160 $this->mNamespace
!= NS_MAIN
) {
2163 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2164 // IP names are not allowed for accounts, and can only be referring to
2165 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2166 // there are numerous ways to present the same IP. Having sp:contribs scan
2167 // them all is silly and having some show the edits and others not is
2168 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2169 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2170 IP
::sanitizeIP( $dbkey ) : $dbkey;
2171 // Any remaining initial :s are illegal.
2172 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2177 $this->mDbkeyform
= $dbkey;
2178 $this->mUrlform
= wfUrlencode( $dbkey );
2180 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2186 * Set the fragment for this title
2187 * This is kind of bad, since except for this rarely-used function, Title objects
2188 * are immutable. The reason this is here is because it's better than setting the
2189 * members directly, which is what Linker::formatComment was doing previously.
2191 * @param string $fragment text
2192 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2194 public function setFragment( $fragment ) {
2195 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2199 * Get a Title object associated with the talk page of this article
2200 * @return Title the object for the talk page
2202 public function getTalkPage() {
2203 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2207 * Get a title object associated with the subject page of this
2210 * @return Title the object for the subject page
2212 public function getSubjectPage() {
2213 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2217 * Get an array of Title objects linking to this Title
2218 * Also stores the IDs in the link cache.
2220 * WARNING: do not use this function on arbitrary user-supplied titles!
2221 * On heavily-used templates it will max out the memory.
2223 * @param string $options may be FOR UPDATE
2224 * @return array the Title objects linking here
2226 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2227 $linkCache =& LinkCache
::singleton();
2230 $db = wfGetDB( DB_MASTER
);
2232 $db = wfGetDB( DB_SLAVE
);
2235 $res = $db->select( array( 'page', $table ),
2236 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2238 "{$prefix}_from=page_id",
2239 "{$prefix}_namespace" => $this->getNamespace(),
2240 "{$prefix}_title" => $this->getDBkey() ),
2241 'Title::getLinksTo',
2245 if ( $db->numRows( $res ) ) {
2246 while ( $row = $db->fetchObject( $res ) ) {
2247 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2248 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
2249 $retVal[] = $titleObj;
2253 $db->freeResult( $res );
2258 * Get an array of Title objects using this Title as a template
2259 * Also stores the IDs in the link cache.
2261 * WARNING: do not use this function on arbitrary user-supplied titles!
2262 * On heavily-used templates it will max out the memory.
2264 * @param string $options may be FOR UPDATE
2265 * @return array the Title objects linking here
2267 public function getTemplateLinksTo( $options = '' ) {
2268 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2272 * Get an array of Title objects referring to non-existent articles linked from this page
2274 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2275 * @param string $options may be FOR UPDATE
2276 * @return array the Title objects
2278 public function getBrokenLinksFrom( $options = '' ) {
2279 if ( $this->getArticleId() == 0 ) {
2280 # All links from article ID 0 are false positives
2285 $db = wfGetDB( DB_MASTER
);
2287 $db = wfGetDB( DB_SLAVE
);
2290 $res = $db->safeQuery(
2291 "SELECT pl_namespace, pl_title
2294 ON pl_namespace=page_namespace
2295 AND pl_title=page_title
2297 AND page_namespace IS NULL
2299 $db->tableName( 'pagelinks' ),
2300 $db->tableName( 'page' ),
2301 $this->getArticleId(),
2305 if ( $db->numRows( $res ) ) {
2306 while ( $row = $db->fetchObject( $res ) ) {
2307 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2310 $db->freeResult( $res );
2316 * Get a list of URLs to purge from the Squid cache when this
2319 * @return array the URLs
2321 public function getSquidURLs() {
2325 $this->getInternalURL(),
2326 $this->getInternalURL( 'action=history' )
2329 // purge variant urls as well
2330 if($wgContLang->hasVariants()){
2331 $variants = $wgContLang->getVariants();
2332 foreach($variants as $vCode){
2333 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2334 $urls[] = $this->getInternalURL('',$vCode);
2341 public function purgeSquid() {
2343 if ( $wgUseSquid ) {
2344 $urls = $this->getSquidURLs();
2345 $u = new SquidUpdate( $urls );
2351 * Move this page without authentication
2352 * @param Title &$nt the new page Title
2354 public function moveNoAuth( &$nt ) {
2355 return $this->moveTo( $nt, false );
2359 * Check whether a given move operation would be valid.
2360 * Returns true if ok, or a message key string for an error message
2361 * if invalid. (Scarrrrry ugly interface this.)
2362 * @param Title &$nt the new title
2363 * @param bool $auth indicates whether $wgUser's permissions
2365 * @return mixed true on success, message name on failure
2367 public function isValidMoveOperation( &$nt, $auth = true ) {
2368 if( !$this or !$nt ) {
2369 return 'badtitletext';
2371 if( $this->equals( $nt ) ) {
2374 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2375 return 'immobile_namespace';
2378 $oldid = $this->getArticleID();
2379 $newid = $nt->getArticleID();
2381 if ( strlen( $nt->getDBkey() ) < 1 ) {
2382 return 'articleexists';
2384 if ( ( '' == $this->getDBkey() ) ||
2386 ( '' == $nt->getDBkey() ) ) {
2387 return 'badarticleerror';
2392 $errors = array_merge($this->getUserPermissionsErrors('move', $wgUser),
2393 $this->getUserPermissionsErrors('edit', $wgUser),
2394 $nt->getUserPermissionsErrors('move', $wgUser),
2395 $nt->getUserPermissionsErrors('edit', $wgUser));
2396 if($errors !== array())
2397 return $errors[0][0];
2402 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
2403 return 'hookaborted';
2406 # The move is allowed only if (1) the target doesn't exist, or
2407 # (2) the target is a redirect to the source, and has no history
2408 # (so we can undo bad moves right after they're done).
2410 if ( 0 != $newid ) { # Target exists; check for validity
2411 if ( ! $this->isValidMoveTarget( $nt ) ) {
2412 return 'articleexists';
2415 $tp = $nt->getTitleProtection();
2416 if ( $tp and !$wgUser->isAllowed( $tp['pt_create_perm'] ) ) {
2417 return 'cantmove-titleprotected';
2424 * Move a title to a new location
2425 * @param Title &$nt the new title
2426 * @param bool $auth indicates whether $wgUser's permissions
2428 * @param string $reason The reason for the move
2429 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2430 * Ignored if the user doesn't have the suppressredirect right.
2431 * @return mixed true on success, message name on failure
2433 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2434 $err = $this->isValidMoveOperation( $nt, $auth );
2435 if( is_string( $err ) ) {
2439 $pageid = $this->getArticleID();
2440 if( $nt->exists() ) {
2441 $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2442 $pageCountChange = ($createRedirect ?
0 : -1);
2443 } else { # Target didn't exist, do normal move.
2444 $this->moveToNewTitle( $nt, $reason, $createRedirect );
2445 $pageCountChange = ($createRedirect ?
1 : 0);
2447 $redirid = $this->getArticleID();
2449 // Category memberships include a sort key which may be customized.
2450 // If it's left as the default (the page title), we need to update
2451 // the sort key to match the new title.
2453 // Be careful to avoid resetting cl_timestamp, which may disturb
2454 // time-based lists on some sites.
2456 // Warning -- if the sort key is *explicitly* set to the old title,
2457 // we can't actually distinguish it from a default here, and it'll
2458 // be set to the new title even though it really shouldn't.
2459 // It'll get corrected on the next edit, but resetting cl_timestamp.
2460 $dbw = wfGetDB( DB_MASTER
);
2461 $dbw->update( 'categorylinks',
2463 'cl_sortkey' => $nt->getPrefixedText(),
2464 'cl_timestamp=cl_timestamp' ),
2466 'cl_from' => $pageid,
2467 'cl_sortkey' => $this->getPrefixedText() ),
2472 $oldnamespace = $this->getNamespace() & ~
1;
2473 $newnamespace = $nt->getNamespace() & ~
1;
2474 $oldtitle = $this->getDBkey();
2475 $newtitle = $nt->getDBkey();
2477 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2478 WatchedItem
::duplicateEntries( $this, $nt );
2481 # Update search engine
2482 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2484 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2488 if( $this->isContentPage() && !$nt->isContentPage() ) {
2489 # No longer a content page
2490 # Not viewed, edited, removing
2491 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2492 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2493 # Now a content page
2494 # Not viewed, edited, adding
2495 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2496 } elseif( $pageCountChange ) {
2498 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2505 # Update message cache for interface messages
2506 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2507 global $wgMessageCache;
2508 $oldarticle = new Article( $this );
2509 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2510 $newarticle = new Article( $nt );
2511 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2515 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2520 * Move page to a title which is at present a redirect to the
2523 * @param Title &$nt the page to move to, which should currently
2525 * @param string $reason The reason for the move
2526 * @param bool $createRedirect Whether to leave a redirect at the old title.
2527 * Ignored if the user doesn't have the suppressredirect right
2529 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2530 global $wgUseSquid, $wgUser;
2531 $fname = 'Title::moveOverExistingRedirect';
2532 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2535 $comment .= ": $reason";
2538 $now = wfTimestampNow();
2539 $newid = $nt->getArticleID();
2540 $oldid = $this->getArticleID();
2541 $dbw = wfGetDB( DB_MASTER
);
2543 # Delete the old redirect. We don't save it to history since
2544 # by definition if we've got here it's rather uninteresting.
2545 # We have to remove it so that the next step doesn't trigger
2546 # a conflict on the unique namespace+title index...
2547 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2548 if ( !$dbw->cascadingDeletes() ) {
2549 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2550 global $wgUseTrackbacks;
2551 if ($wgUseTrackbacks)
2552 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2553 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2554 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2555 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2556 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2557 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2558 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2559 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2562 # Save a null revision in the page's history notifying of the move
2563 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2564 $nullRevId = $nullRevision->insertOn( $dbw );
2566 # Change the name of the target page:
2567 $dbw->update( 'page',
2569 'page_touched' => $dbw->timestamp($now),
2570 'page_namespace' => $nt->getNamespace(),
2571 'page_title' => $nt->getDBkey(),
2572 'page_latest' => $nullRevId,
2574 /* WHERE */ array( 'page_id' => $oldid ),
2577 $nt->resetArticleID( $oldid );
2579 # Recreate the redirect, this time in the other direction.
2580 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2582 $mwRedir = MagicWord
::get( 'redirect' );
2583 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2584 $redirectArticle = new Article( $this );
2585 $newid = $redirectArticle->insertOn( $dbw );
2586 $redirectRevision = new Revision( array(
2588 'comment' => $comment,
2589 'text' => $redirectText ) );
2590 $redirectRevision->insertOn( $dbw );
2591 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2593 # Now, we record the link from the redirect to the new title.
2594 # It should have no other outgoing links...
2595 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2596 $dbw->insert( 'pagelinks',
2598 'pl_from' => $newid,
2599 'pl_namespace' => $nt->getNamespace(),
2600 'pl_title' => $nt->getDBkey() ),
2603 $this->resetArticleID( 0 );
2607 $log = new LogPage( 'move' );
2608 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2611 if ( $wgUseSquid ) {
2612 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2613 $u = new SquidUpdate( $urls );
2619 * Move page to non-existing title.
2620 * @param Title &$nt the new Title
2621 * @param string $reason The reason for the move
2622 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2623 * Ignored if the user doesn't have the suppressredirect right
2625 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2626 global $wgUseSquid, $wgUser;
2627 $fname = 'MovePageForm::moveToNewTitle';
2628 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2630 $comment .= ": $reason";
2633 $newid = $nt->getArticleID();
2634 $oldid = $this->getArticleID();
2635 $dbw = wfGetDB( DB_MASTER
);
2636 $now = $dbw->timestamp();
2638 # Save a null revision in the page's history notifying of the move
2639 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2640 $nullRevId = $nullRevision->insertOn( $dbw );
2643 $dbw->update( 'page',
2645 'page_touched' => $now,
2646 'page_namespace' => $nt->getNamespace(),
2647 'page_title' => $nt->getDBkey(),
2648 'page_latest' => $nullRevId,
2650 /* WHERE */ array( 'page_id' => $oldid ),
2653 $nt->resetArticleID( $oldid );
2655 if($createRedirect ||
!$wgUser->isAllowed('suppressredirect'))
2658 $mwRedir = MagicWord
::get( 'redirect' );
2659 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2660 $redirectArticle = new Article( $this );
2661 $newid = $redirectArticle->insertOn( $dbw );
2662 $redirectRevision = new Revision( array(
2664 'comment' => $comment,
2665 'text' => $redirectText ) );
2666 $redirectRevision->insertOn( $dbw );
2667 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2669 # Record the just-created redirect's linking to the page
2670 $dbw->insert( 'pagelinks',
2672 'pl_from' => $newid,
2673 'pl_namespace' => $nt->getNamespace(),
2674 'pl_title' => $nt->getDBkey() ),
2677 $this->resetArticleID( 0 );
2681 $log = new LogPage( 'move' );
2682 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2684 # Purge caches as per article creation
2685 Article
::onArticleCreate( $nt );
2687 # Purge old title from squid
2688 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2689 $this->purgeSquid();
2693 * Checks if $this can be moved to a given Title
2694 * - Selects for update, so don't call it unless you mean business
2696 * @param Title &$nt the new title to check
2698 public function isValidMoveTarget( $nt ) {
2700 $fname = 'Title::isValidMoveTarget';
2701 $dbw = wfGetDB( DB_MASTER
);
2704 $id = $nt->getArticleID();
2705 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2706 array( 'page_is_redirect','old_text','old_flags' ),
2707 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2708 $fname, 'FOR UPDATE' );
2710 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2712 wfDebug( __METHOD__
. ": not a redirect\n" );
2715 $text = Revision
::getRevisionText( $obj );
2717 # Does the redirect point to the source?
2718 # Or is it a broken self-redirect, usually caused by namespace collisions?
2720 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2721 $redirTitle = Title
::newFromText( $m[1] );
2722 if( !is_object( $redirTitle ) ||
2723 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2724 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2725 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2730 wfDebug( __METHOD__
. ": failsafe\n" );
2734 # Does the article have a history?
2735 $row = $dbw->selectRow( array( 'page', 'revision'),
2737 array( 'page_namespace' => $nt->getNamespace(),
2738 'page_title' => $nt->getDBkey(),
2739 'page_id=rev_page AND page_latest != rev_id'
2740 ), $fname, 'FOR UPDATE'
2743 # Return true if there was no history
2744 return $row === false;
2748 * Can this title be added to a user's watchlist?
2752 public function isWatchable() {
2753 return !$this->isExternal()
2754 && MWNamespace
::isWatchable( $this->getNamespace() );
2758 * Get categories to which this Title belongs and return an array of
2759 * categories' names.
2761 * @return array an array of parents in the form:
2762 * $parent => $currentarticle
2764 public function getParentCategories() {
2767 $titlekey = $this->getArticleId();
2768 $dbr = wfGetDB( DB_SLAVE
);
2769 $categorylinks = $dbr->tableName( 'categorylinks' );
2772 $sql = "SELECT * FROM $categorylinks"
2773 ." WHERE cl_from='$titlekey'"
2774 ." AND cl_from <> '0'"
2775 ." ORDER BY cl_sortkey";
2777 $res = $dbr->query ( $sql ) ;
2779 if($dbr->numRows($res) > 0) {
2780 while ( $x = $dbr->fetchObject ( $res ) )
2781 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2782 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2783 $dbr->freeResult ( $res ) ;
2791 * Get a tree of parent categories
2792 * @param array $children an array with the children in the keys, to check for circular refs
2795 public function getParentCategoryTree( $children = array() ) {
2797 $parents = $this->getParentCategories();
2799 if($parents != '') {
2800 foreach($parents as $parent => $current) {
2801 if ( array_key_exists( $parent, $children ) ) {
2802 # Circular reference
2803 $stack[$parent] = array();
2805 $nt = Title
::newFromText($parent);
2807 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2819 * Get an associative array for selecting this title from
2824 public function pageCond() {
2825 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2829 * Get the revision ID of the previous revision
2831 * @param integer $revision Revision ID. Get the revision that was before this one.
2832 * @return integer $oldrevision|false
2834 public function getPreviousRevisionID( $revision ) {
2835 $dbr = wfGetDB( DB_SLAVE
);
2836 return $dbr->selectField( 'revision', 'rev_id',
2837 'rev_page=' . intval( $this->getArticleId() ) .
2838 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2842 * Get the revision ID of the next revision
2844 * @param integer $revision Revision ID. Get the revision that was after this one.
2845 * @return integer $oldrevision|false
2847 public function getNextRevisionID( $revision ) {
2848 $dbr = wfGetDB( DB_SLAVE
);
2849 return $dbr->selectField( 'revision', 'rev_id',
2850 'rev_page=' . intval( $this->getArticleId() ) .
2851 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2855 * Get the number of revisions between the given revision IDs.
2857 * @param integer $old Revision ID.
2858 * @param integer $new Revision ID.
2859 * @return integer Number of revisions between these IDs.
2861 public function countRevisionsBetween( $old, $new ) {
2862 $dbr = wfGetDB( DB_SLAVE
);
2863 return $dbr->selectField( 'revision', 'count(*)',
2864 'rev_page = ' . intval( $this->getArticleId() ) .
2865 ' AND rev_id > ' . intval( $old ) .
2866 ' AND rev_id < ' . intval( $new ) );
2870 * Compare with another title.
2872 * @param Title $title
2875 public function equals( $title ) {
2876 // Note: === is necessary for proper matching of number-like titles.
2877 return $this->getInterwiki() === $title->getInterwiki()
2878 && $this->getNamespace() == $title->getNamespace()
2879 && $this->getDBkey() === $title->getDBkey();
2883 * Return a string representation of this title
2887 public function __toString() {
2888 return $this->getPrefixedText();
2892 * Check if page exists
2895 public function exists() {
2896 return $this->getArticleId() != 0;
2900 * Do we know that this title definitely exists, or should we otherwise
2901 * consider that it exists?
2905 public function isAlwaysKnown() {
2906 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
2907 // the full l10n of that language to be loaded. That takes much memory and
2908 // isn't needed. So we strip the language part away.
2909 // Also, extension messages which are not loaded, are shown as red, because
2910 // we don't call MessageCache::loadAllMessages.
2911 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
2912 return $this->isExternal()
2913 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
2914 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
2918 * Update page_touched timestamps and send squid purge messages for
2919 * pages linking to this title. May be sent to the job queue depending
2920 * on the number of links. Typically called on create and delete.
2922 public function touchLinks() {
2923 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2926 if ( $this->getNamespace() == NS_CATEGORY
) {
2927 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2933 * Get the last touched timestamp
2935 public function getTouched() {
2936 $dbr = wfGetDB( DB_SLAVE
);
2937 $touched = $dbr->selectField( 'page', 'page_touched',
2939 'page_namespace' => $this->getNamespace(),
2940 'page_title' => $this->getDBkey()
2946 public function trackbackURL() {
2947 global $wgTitle, $wgScriptPath, $wgServer;
2949 return "$wgServer$wgScriptPath/trackback.php?article="
2950 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2953 public function trackbackRDF() {
2954 $url = htmlspecialchars($this->getFullURL());
2955 $title = htmlspecialchars($this->getText());
2956 $tburl = $this->trackbackURL();
2958 // Autodiscovery RDF is placed in comments so HTML validator
2959 // won't barf. This is a rather icky workaround, but seems
2960 // frequently used by this kind of RDF thingy.
2962 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
2964 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2965 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2966 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2969 dc:identifier=\"$url\"
2971 trackback:ping=\"$tburl\" />
2977 * Generate strings used for xml 'id' names in monobook tabs
2980 public function getNamespaceKey() {
2982 switch ($this->getNamespace()) {
2985 return 'nstab-main';
2988 return 'nstab-user';
2990 return 'nstab-media';
2992 return 'nstab-special';
2994 case NS_PROJECT_TALK
:
2995 return 'nstab-project';
2998 return 'nstab-image';
3000 case NS_MEDIAWIKI_TALK
:
3001 return 'nstab-mediawiki';
3003 case NS_TEMPLATE_TALK
:
3004 return 'nstab-template';
3007 return 'nstab-help';
3009 case NS_CATEGORY_TALK
:
3010 return 'nstab-category';
3012 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3017 * Returns true if this title resolves to the named special page
3018 * @param string $name The special page name
3020 public function isSpecial( $name ) {
3021 if ( $this->getNamespace() == NS_SPECIAL
) {
3022 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3023 if ( $name == $thisName ) {
3031 * If the Title refers to a special page alias which is not the local default,
3032 * returns a new Title which points to the local default. Otherwise, returns $this.
3034 public function fixSpecialName() {
3035 if ( $this->getNamespace() == NS_SPECIAL
) {
3036 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3037 if ( $canonicalName ) {
3038 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3039 if ( $localName != $this->mDbkeyform
) {
3040 return Title
::makeTitle( NS_SPECIAL
, $localName );
3048 * Is this Title in a namespace which contains content?
3049 * In other words, is this a content page, for the purposes of calculating
3054 public function isContentPage() {
3055 return MWNamespace
::isContent( $this->getNamespace() );