* AuthPlugin added strictUserAuth() method to allow per-user override
[mediawiki.git] / includes / Title.php
blobdc4a763cf3c9efa45003755cb3dc7b1c57a47a5c
1 <?php
2 /**
3 * See title.txt
5 */
7 /** */
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,
18 # reset the cache.
19 define( 'MW_TITLECACHE_MAX', 1000 );
21 # Constants for pr_cascade bitfield
22 define( 'CASCADE', 1 );
24 /**
25 * Title class
26 * - Represents a title, which may contain an interwiki designation or namespace
27 * - Can fetch various kinds of data from the database, albeit inefficiently.
30 class Title {
31 /**
32 * Static cache variables
34 static private $titleCache=array();
35 static private $interwikiCache=array();
38 /**
39 * All member variables should be considered private
40 * Please use the accessor functions
43 /**#@+
44 * @private
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 /**#@-*/
69 /**
70 * Constructor
71 * @private
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
81 # See bug #696
82 $this->mDefaultNamespace = NS_MAIN;
83 $this->mWatched = NULL;
84 $this->mLatestID = false;
85 $this->mOldRestrictions = false;
88 /**
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
92 * interwiki prefixes
93 * @return Title the new object, or NULL on an error
95 public static function newFromDBkey( $key ) {
96 $t = new Title();
97 $t->mDbkeyform = $key;
98 if( $t->secureAndSplit() )
99 return $t;
100 else
101 return NULL;
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
110 * are accepted
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
124 * caching them.
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 &eacute; &#257; or &#x3017; into real text...
135 $filteredText = Sanitizer::decodeCharReferences( $text );
137 $t = new Title();
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();
147 $cachedcount=0;
149 $cachedcount++;
150 Title::$titleCache[$text] =& $t;
152 return $t;
153 } else {
154 $ret = NULL;
155 return $ret;
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;
167 $t = new Title();
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() ) {
178 return $t;
179 } else {
180 return NULL;
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 );
200 } else {
201 $title = NULL;
203 return $title;
207 * Make an array of titles from an array of IDs
209 public static function newFromIDs( $ids ) {
210 $dbr = wfGetDB( DB_SLAVE );
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
214 $titles = array();
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
218 return $titles;
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
232 public static function &makeTitle( $ns, $title ) {
233 $t = new Title();
234 $t->mInterwiki = '';
235 $t->mFragment = '';
236 $t->mNamespace = $ns = intval( $ns );
237 $t->mDbkeyform = str_replace( ' ', '_', $title );
238 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
239 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
240 $t->mTextform = str_replace( '_', ' ', $title );
241 return $t;
245 * Create a new Title from a namespace index and a DB key.
246 * The parameters will be checked for validity, which is a bit slower
247 * than makeTitle() but safer for user-provided data.
249 * @param int $ns the namespace of the article
250 * @param string $title the database key form
251 * @return Title the new object, or NULL on an error
253 public static function makeTitleSafe( $ns, $title ) {
254 $t = new Title();
255 $t->mDbkeyform = Title::makeName( $ns, $title );
256 if( $t->secureAndSplit() ) {
257 return $t;
258 } else {
259 return NULL;
264 * Create a new Title for the Main Page
265 * @return Title the new object
267 public static function newMainPage() {
268 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
272 * Extract a redirect destination from a string and return the
273 * Title, or null if the text doesn't contain a valid redirect
275 * @param string $text Text with possible redirect
276 * @return Title
278 public static function newFromRedirect( $text ) {
279 $redir = MagicWord::get( 'redirect' );
280 if( $redir->matchStart( $text ) ) {
281 // Extract the first link and see if it's usable
282 $m = array();
283 if( preg_match( '!\[{2}(.*?)(?:\||\]{2})!', $text, $m ) ) {
284 // Strip preceding colon used to "escape" categories, etc.
285 // and URL-decode links
286 if( strpos( $m[1], '%' ) !== false ) {
287 // Match behavior of inline link parsing here;
288 // don't interpret + as " " most of the time!
289 // It might be safe to just use rawurldecode instead, though.
290 $m[1] = urldecode( ltrim( $m[1], ':' ) );
292 $title = Title::newFromText( $m[1] );
293 // Redirects to Special:Userlogout are not permitted
294 if( $title instanceof Title && !$title->isSpecial( 'Userlogout' ) )
295 return $title;
298 return null;
301 #----------------------------------------------------------------------------
302 # Static functions
303 #----------------------------------------------------------------------------
306 * Get the prefixed DB key associated with an ID
307 * @param int $id the page_id of the article
308 * @return Title an object representing the article, or NULL
309 * if no such article was found
310 * @static
311 * @access public
313 function nameOf( $id ) {
314 $fname = 'Title::nameOf';
315 $dbr = wfGetDB( DB_SLAVE );
317 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
318 if ( $s === false ) { return NULL; }
320 $n = Title::makeName( $s->page_namespace, $s->page_title );
321 return $n;
325 * Get a regex character class describing the legal characters in a link
326 * @return string the list of characters, not delimited
328 public static function legalChars() {
329 global $wgLegalTitleChars;
330 return $wgLegalTitleChars;
334 * Get a string representation of a title suitable for
335 * including in a search index
337 * @param int $ns a namespace index
338 * @param string $title text-form main part
339 * @return string a stripped-down title string ready for the
340 * search index
342 public static function indexTitle( $ns, $title ) {
343 global $wgContLang;
345 $lc = SearchEngine::legalSearchChars() . '&#;';
346 $t = $wgContLang->stripForSearch( $title );
347 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
348 $t = $wgContLang->lc( $t );
350 # Handle 's, s'
351 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
352 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
354 $t = preg_replace( "/\\s+/", ' ', $t );
356 if ( $ns == NS_IMAGE ) {
357 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
359 return trim( $t );
363 * Make a prefixed DB key from a DB key and a namespace index
364 * @param int $ns numerical representation of the namespace
365 * @param string $title the DB key form the title
366 * @return string the prefixed form of the title
368 public static function makeName( $ns, $title ) {
369 global $wgContLang;
371 $n = $wgContLang->getNsText( $ns );
372 return $n == '' ? $title : "$n:$title";
376 * Returns the URL associated with an interwiki prefix
377 * @param string $key the interwiki prefix (e.g. "MeatBall")
378 * @return the associated URL, containing "$1", which should be
379 * replaced by an article title
380 * @static (arguably)
382 public function getInterwikiLink( $key ) {
383 global $wgMemc, $wgInterwikiExpiry;
384 global $wgInterwikiCache, $wgContLang;
385 $fname = 'Title::getInterwikiLink';
387 $key = $wgContLang->lc( $key );
389 $k = wfMemcKey( 'interwiki', $key );
390 if( array_key_exists( $k, Title::$interwikiCache ) ) {
391 return Title::$interwikiCache[$k]->iw_url;
394 if ($wgInterwikiCache) {
395 return Title::getInterwikiCached( $key );
398 $s = $wgMemc->get( $k );
399 # Ignore old keys with no iw_local
400 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
401 Title::$interwikiCache[$k] = $s;
402 return $s->iw_url;
405 $dbr = wfGetDB( DB_SLAVE );
406 $res = $dbr->select( 'interwiki',
407 array( 'iw_url', 'iw_local', 'iw_trans' ),
408 array( 'iw_prefix' => $key ), $fname );
409 if( !$res ) {
410 return '';
413 $s = $dbr->fetchObject( $res );
414 if( !$s ) {
415 # Cache non-existence: create a blank object and save it to memcached
416 $s = (object)false;
417 $s->iw_url = '';
418 $s->iw_local = 0;
419 $s->iw_trans = 0;
421 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
422 Title::$interwikiCache[$k] = $s;
424 return $s->iw_url;
428 * Fetch interwiki prefix data from local cache in constant database
430 * More logic is explained in DefaultSettings
432 * @return string URL of interwiki site
434 public static function getInterwikiCached( $key ) {
435 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
436 static $db, $site;
438 if (!$db)
439 $db=dba_open($wgInterwikiCache,'r','cdb');
440 /* Resolve site name */
441 if ($wgInterwikiScopes>=3 and !$site) {
442 $site = dba_fetch('__sites:' . wfWikiID(), $db);
443 if ($site=="")
444 $site = $wgInterwikiFallbackSite;
446 $value = dba_fetch( wfMemcKey( $key ), $db);
447 if ($value=='' and $wgInterwikiScopes>=3) {
448 /* try site-level */
449 $value = dba_fetch("_{$site}:{$key}", $db);
451 if ($value=='' and $wgInterwikiScopes>=2) {
452 /* try globals */
453 $value = dba_fetch("__global:{$key}", $db);
455 if ($value=='undef')
456 $value='';
457 $s = (object)false;
458 $s->iw_url = '';
459 $s->iw_local = 0;
460 $s->iw_trans = 0;
461 if ($value!='') {
462 list($local,$url)=explode(' ',$value,2);
463 $s->iw_url=$url;
464 $s->iw_local=(int)$local;
466 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
467 return $s->iw_url;
470 * Determine whether the object refers to a page within
471 * this project.
473 * @return bool TRUE if this is an in-project interwiki link
474 * or a wikilink, FALSE otherwise
476 public function isLocal() {
477 if ( $this->mInterwiki != '' ) {
478 # Make sure key is loaded into cache
479 $this->getInterwikiLink( $this->mInterwiki );
480 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
481 return (bool)(Title::$interwikiCache[$k]->iw_local);
482 } else {
483 return true;
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return bool TRUE if this is transcludable
493 public function isTrans() {
494 if ($this->mInterwiki == '')
495 return false;
496 # Make sure key is loaded into cache
497 $this->getInterwikiLink( $this->mInterwiki );
498 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
499 return (bool)(Title::$interwikiCache[$k]->iw_trans);
503 * Escape a text fragment, say from a link, for a URL
505 static function escapeFragmentForURL( $fragment ) {
506 $fragment = str_replace( ' ', '_', $fragment );
507 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
508 $replaceArray = array(
509 '%3A' => ':',
510 '%' => '.'
512 return strtr( $fragment, $replaceArray );
515 #----------------------------------------------------------------------------
516 # Other stuff
517 #----------------------------------------------------------------------------
519 /** Simple accessors */
521 * Get the text form (spaces not underscores) of the main part
522 * @return string
524 public function getText() { return $this->mTextform; }
526 * Get the URL-encoded form of the main part
527 * @return string
529 public function getPartialURL() { return $this->mUrlform; }
531 * Get the main part with underscores
532 * @return string
534 public function getDBkey() { return $this->mDbkeyform; }
536 * Get the namespace index, i.e. one of the NS_xxxx constants
537 * @return int
539 public function getNamespace() { return $this->mNamespace; }
541 * Get the namespace text
542 * @return string
544 public function getNsText() {
545 global $wgContLang, $wgCanonicalNamespaceNames;
547 if ( '' != $this->mInterwiki ) {
548 // This probably shouldn't even happen. ohh man, oh yuck.
549 // But for interwiki transclusion it sometimes does.
550 // Shit. Shit shit shit.
552 // Use the canonical namespaces if possible to try to
553 // resolve a foreign namespace.
554 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
555 return $wgCanonicalNamespaceNames[$this->mNamespace];
558 return $wgContLang->getNsText( $this->mNamespace );
561 * Get the DB key with the initial letter case as specified by the user
563 function getUserCaseDBKey() {
564 return $this->mUserCaseDBKey;
567 * Get the namespace text of the subject (rather than talk) page
568 * @return string
570 public function getSubjectNsText() {
571 global $wgContLang;
572 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
576 * Get the namespace text of the talk page
577 * @return string
579 public function getTalkNsText() {
580 global $wgContLang;
581 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
585 * Could this title have a corresponding talk page?
586 * @return bool
588 public function canTalk() {
589 return( Namespace::canTalk( $this->mNamespace ) );
593 * Get the interwiki prefix (or null string)
594 * @return string
596 public function getInterwiki() { return $this->mInterwiki; }
598 * Get the Title fragment (i.e. the bit after the #) in text form
599 * @return string
601 public function getFragment() { return $this->mFragment; }
603 * Get the fragment in URL form, including the "#" character if there is one
604 * @return string
606 public function getFragmentForURL() {
607 if ( $this->mFragment == '' ) {
608 return '';
609 } else {
610 return '#' . Title::escapeFragmentForURL( $this->mFragment );
614 * Get the default namespace index, for when there is no namespace
615 * @return int
617 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
620 * Get title for search index
621 * @return string a stripped-down title string ready for the
622 * search index
624 public function getIndexTitle() {
625 return Title::indexTitle( $this->mNamespace, $this->mTextform );
629 * Get the prefixed database key form
630 * @return string the prefixed title, with underscores and
631 * any interwiki and namespace prefixes
633 public function getPrefixedDBkey() {
634 $s = $this->prefix( $this->mDbkeyform );
635 $s = str_replace( ' ', '_', $s );
636 return $s;
640 * Get the prefixed title with spaces.
641 * This is the form usually used for display
642 * @return string the prefixed title, with spaces
644 public function getPrefixedText() {
645 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
646 $s = $this->prefix( $this->mTextform );
647 $s = str_replace( '_', ' ', $s );
648 $this->mPrefixedText = $s;
650 return $this->mPrefixedText;
654 * Get the prefixed title with spaces, plus any fragment
655 * (part beginning with '#')
656 * @return string the prefixed title, with spaces and
657 * the fragment, including '#'
659 public function getFullText() {
660 $text = $this->getPrefixedText();
661 if( '' != $this->mFragment ) {
662 $text .= '#' . $this->mFragment;
664 return $text;
668 * Get the base name, i.e. the leftmost parts before the /
669 * @return string Base name
671 public function getBaseText() {
672 global $wgNamespacesWithSubpages;
673 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
674 $parts = explode( '/', $this->getText() );
675 # Don't discard the real title if there's no subpage involved
676 if( count( $parts ) > 1 )
677 unset( $parts[ count( $parts ) - 1 ] );
678 return implode( '/', $parts );
679 } else {
680 return $this->getText();
685 * Get the lowest-level subpage name, i.e. the rightmost part after /
686 * @return string Subpage name
688 public function getSubpageText() {
689 global $wgNamespacesWithSubpages;
690 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
691 $parts = explode( '/', $this->mTextform );
692 return( $parts[ count( $parts ) - 1 ] );
693 } else {
694 return( $this->mTextform );
699 * Get a URL-encoded form of the subpage text
700 * @return string URL-encoded subpage name
702 public function getSubpageUrlForm() {
703 $text = $this->getSubpageText();
704 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
705 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
706 return( $text );
710 * Get a URL-encoded title (not an actual URL) including interwiki
711 * @return string the URL-encoded form
713 public function getPrefixedURL() {
714 $s = $this->prefix( $this->mDbkeyform );
715 $s = str_replace( ' ', '_', $s );
717 $s = wfUrlencode ( $s ) ;
719 # Cleaning up URL to make it look nice -- is this safe?
720 $s = str_replace( '%28', '(', $s );
721 $s = str_replace( '%29', ')', $s );
723 return $s;
727 * Get a real URL referring to this title, with interwiki link and
728 * fragment
730 * @param string $query an optional query string, not used
731 * for interwiki links
732 * @param string $variant language variant of url (for sr, zh..)
733 * @return string the URL
735 public function getFullURL( $query = '', $variant = false ) {
736 global $wgContLang, $wgServer, $wgRequest;
738 if ( '' == $this->mInterwiki ) {
739 $url = $this->getLocalUrl( $query, $variant );
741 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
742 // Correct fix would be to move the prepending elsewhere.
743 if ($wgRequest->getVal('action') != 'render') {
744 $url = $wgServer . $url;
746 } else {
747 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
749 $namespace = wfUrlencode( $this->getNsText() );
750 if ( '' != $namespace ) {
751 # Can this actually happen? Interwikis shouldn't be parsed.
752 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
753 $namespace .= ':';
755 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
756 $url = wfAppendQuery( $url, $query );
759 # Finally, add the fragment.
760 $url .= $this->getFragmentForURL();
762 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
763 return $url;
767 * Get a URL with no fragment or server name. If this page is generated
768 * with action=render, $wgServer is prepended.
769 * @param string $query an optional query string; if not specified,
770 * $wgArticlePath will be used.
771 * @param string $variant language variant of url (for sr, zh..)
772 * @return string the URL
774 public function getLocalURL( $query = '', $variant = false ) {
775 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
776 global $wgVariantArticlePath, $wgContLang, $wgUser;
778 // internal links should point to same variant as current page (only anonymous users)
779 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
780 $pref = $wgContLang->getPreferredVariant(false);
781 if($pref != $wgContLang->getCode())
782 $variant = $pref;
785 if ( $this->isExternal() ) {
786 $url = $this->getFullURL();
787 if ( $query ) {
788 // This is currently only used for edit section links in the
789 // context of interwiki transclusion. In theory we should
790 // append the query to the end of any existing query string,
791 // but interwiki transclusion is already broken in that case.
792 $url .= "?$query";
794 } else {
795 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
796 if ( $query == '' ) {
797 if($variant!=false && $wgContLang->hasVariants()){
798 if($wgVariantArticlePath==false) {
799 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
800 } else {
801 $variantArticlePath = $wgVariantArticlePath;
803 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
804 $url = str_replace( '$1', $dbkey, $url );
806 else {
807 $url = str_replace( '$1', $dbkey, $wgArticlePath );
809 } else {
810 global $wgActionPaths;
811 $url = false;
812 $matches = array();
813 if( !empty( $wgActionPaths ) &&
814 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
816 $action = urldecode( $matches[2] );
817 if( isset( $wgActionPaths[$action] ) ) {
818 $query = $matches[1];
819 if( isset( $matches[4] ) ) $query .= $matches[4];
820 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
821 if( $query != '' ) $url .= '?' . $query;
824 if ( $url === false ) {
825 if ( $query == '-' ) {
826 $query = '';
828 $url = "{$wgScript}?title={$dbkey}&{$query}";
832 // FIXME: this causes breakage in various places when we
833 // actually expected a local URL and end up with dupe prefixes.
834 if ($wgRequest->getVal('action') == 'render') {
835 $url = $wgServer . $url;
838 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
839 return $url;
843 * Get an HTML-escaped version of the URL form, suitable for
844 * using in a link, without a server name or fragment
845 * @param string $query an optional query string
846 * @return string the URL
848 public function escapeLocalURL( $query = '' ) {
849 return htmlspecialchars( $this->getLocalURL( $query ) );
853 * Get an HTML-escaped version of the URL form, suitable for
854 * using in a link, including the server name and fragment
856 * @return string the URL
857 * @param string $query an optional query string
859 public function escapeFullURL( $query = '' ) {
860 return htmlspecialchars( $this->getFullURL( $query ) );
864 * Get the URL form for an internal link.
865 * - Used in various Squid-related code, in case we have a different
866 * internal hostname for the server from the exposed one.
868 * @param string $query an optional query string
869 * @param string $variant language variant of url (for sr, zh..)
870 * @return string the URL
872 public function getInternalURL( $query = '', $variant = false ) {
873 global $wgInternalServer;
874 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
875 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
876 return $url;
880 * Get the edit URL for this Title
881 * @return string the URL, or a null string if this is an
882 * interwiki link
884 public function getEditURL() {
885 if ( '' != $this->mInterwiki ) { return ''; }
886 $s = $this->getLocalURL( 'action=edit' );
888 return $s;
892 * Get the HTML-escaped displayable text form.
893 * Used for the title field in <a> tags.
894 * @return string the text, including any prefixes
896 public function getEscapedText() {
897 return htmlspecialchars( $this->getPrefixedText() );
901 * Is this Title interwiki?
902 * @return boolean
904 public function isExternal() { return ( '' != $this->mInterwiki ); }
907 * Is this page "semi-protected" - the *only* protection is autoconfirm?
909 * @param string Action to check (default: edit)
910 * @return bool
912 public function isSemiProtected( $action = 'edit' ) {
913 if( $this->exists() ) {
914 $restrictions = $this->getRestrictions( $action );
915 if( count( $restrictions ) > 0 ) {
916 foreach( $restrictions as $restriction ) {
917 if( strtolower( $restriction ) != 'autoconfirmed' )
918 return false;
920 } else {
921 # Not protected
922 return false;
924 return true;
925 } else {
926 # If it doesn't exist, it can't be protected
927 return false;
932 * Does the title correspond to a protected article?
933 * @param string $what the action the page is protected from,
934 * by default checks move and edit
935 * @return boolean
937 public function isProtected( $action = '' ) {
938 global $wgRestrictionLevels;
940 # Special pages have inherent protection
941 if( $this->getNamespace() == NS_SPECIAL )
942 return true;
944 # Check regular protection levels
945 if( $action == 'edit' || $action == '' ) {
946 $r = $this->getRestrictions( 'edit' );
947 foreach( $wgRestrictionLevels as $level ) {
948 if( in_array( $level, $r ) && $level != '' ) {
949 return( true );
954 if( $action == 'move' || $action == '' ) {
955 $r = $this->getRestrictions( 'move' );
956 foreach( $wgRestrictionLevels as $level ) {
957 if( in_array( $level, $r ) && $level != '' ) {
958 return( true );
963 return false;
967 * Is $wgUser is watching this page?
968 * @return boolean
970 public function userIsWatching() {
971 global $wgUser;
973 if ( is_null( $this->mWatched ) ) {
974 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
975 $this->mWatched = false;
976 } else {
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
993 * @return boolean
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.
1003 * @return boolean
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 ) )
1010 return true;
1013 return false;
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.
1020 * @return boolean
1022 public function userCan( $action, $doExpensiveQueries = true ) {
1023 global $wgUser;
1024 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1028 * Can $user perform $action on this page?
1029 * @param string $action action that permission needs to be checked for
1030 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1031 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1033 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1034 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1036 global $wgContLang;
1037 global $wgLang;
1039 if ( wfReadOnly() && $action != 'read' ) {
1040 global $wgReadOnly;
1041 $errors[] = array( 'readonlytext', $wgReadOnly );
1044 global $wgEmailConfirmToEdit, $wgUser;
1046 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() )
1048 $errors[] = array( 'confirmedittext' );
1051 if ( $user->isBlockedFrom( $this ) ) {
1052 $block = $user->mBlock;
1054 // This is from OutputPage::blockedPage
1055 // Copied at r23888 by werdna
1057 $id = $user->blockedBy();
1058 $reason = $user->blockedFor();
1059 $ip = wfGetIP();
1061 if ( is_numeric( $id ) ) {
1062 $name = User::whoIs( $id );
1063 } else {
1064 $name = $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 )
1078 continue;
1080 list ($show, $value) = explode( ":", $option );
1082 if ( $value == 'infinite' || $value == 'indefinite' ) {
1083 $blockExpiry = $show;
1084 break;
1087 } else {
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 );
1096 return $errors;
1100 * Can $user perform $action on this page?
1101 * This is an internal function, which checks ONLY that previously checked by userCan (i.e. it leaves out checks on wfReadOnly() and blocks)
1102 * @param string $action action that permission needs to be checked for
1103 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1104 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1106 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1107 $fname = 'Title::userCan';
1108 wfProfileIn( $fname );
1110 $errors = array();
1112 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1113 return $result ? array() : array( array( 'badaccess-group0' ) );
1116 if( NS_SPECIAL == $this->mNamespace ) {
1117 $errors[] = array('ns-specialprotected');
1120 if ( $this->isNamespaceProtected() ) {
1121 $ns = $this->getNamespace() == NS_MAIN
1122 ? wfMsg( 'nstab-main' )
1123 : $this->getNsText();
1124 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1125 ? array('protectedinterface')
1126 : array( 'namespaceprotected', $ns ) );
1129 if( $this->mDbkeyform == '_' ) {
1130 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1131 $errors[] = array('badaccess-group0');
1134 # protect css/js subpages of user pages
1135 # XXX: this might be better using restrictions
1136 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1137 if( $this->isCssJsSubpage()
1138 && !$user->isAllowed('editusercssjs')
1139 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1140 $errors[] = array('customcssjsprotected');
1143 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1144 # We /could/ use the protection level on the source page, but it's fairly ugly
1145 # as we have to establish a precedence hierarchy for pages included by multiple
1146 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1147 # as they could remove the protection anyway.
1148 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1149 # Cascading protection depends on more than this page...
1150 # Several cascading protected pages may include this page...
1151 # Check each cascading level
1152 # This is only for protection restrictions, not for all actions
1153 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1154 foreach( $restrictions[$action] as $right ) {
1155 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1156 if( '' != $right && !$user->isAllowed( $right ) ) {
1157 $pages = '';
1158 foreach( $cascadingSources as $page )
1159 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1160 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1166 foreach( $this->getRestrictions($action) as $right ) {
1167 // Backwards compatibility, rewrite sysop -> protect
1168 if ( $right == 'sysop' ) {
1169 $right = 'protect';
1171 if( '' != $right && !$user->isAllowed( $right ) ) {
1172 $errors[] = array( 'protectedpagetext', $right );
1176 if( $action == 'create' ) {
1177 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1178 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1179 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1181 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1182 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1183 } else if ( !$user->isAllowed( $action ) ) {
1184 $return = null;
1185 $groups = array();
1186 global $wgGroupPermissions;
1187 foreach( $wgGroupPermissions as $key => $value ) {
1188 if( isset( $value[$action] ) && $value[$action] == true ) {
1189 $groupName = User::getGroupName( $key );
1190 $groupPage = User::getGroupPage( $key );
1191 if( $groupPage ) {
1192 $skin = $user->getSkin();
1193 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1194 } else {
1195 $groups[] = $groupName;
1199 $n = count( $groups );
1200 $groups = implode( ', ', $groups );
1201 switch( $n ) {
1202 case 0:
1203 case 1:
1204 case 2:
1205 $return = array( "badaccess-group$n", $groups );
1206 break;
1207 default:
1208 $return = array( 'badaccess-groups', $groups );
1210 $errors[] = $return;
1213 wfProfileOut( $fname );
1214 return $errors;
1218 * Can $wgUser edit this page?
1219 * @return boolean
1220 * @deprecated use userCan('edit')
1222 public function userCanEdit( $doExpensiveQueries = true ) {
1223 return $this->userCan( 'edit', $doExpensiveQueries );
1227 * Can $wgUser create this page?
1228 * @return boolean
1229 * @deprecated use userCan('create')
1231 public function userCanCreate( $doExpensiveQueries = true ) {
1232 return $this->userCan( 'create', $doExpensiveQueries );
1236 * Can $wgUser move this page?
1237 * @return boolean
1238 * @deprecated use userCan('move')
1240 public function userCanMove( $doExpensiveQueries = true ) {
1241 return $this->userCan( 'move', $doExpensiveQueries );
1245 * Would anybody with sufficient privileges be able to move this page?
1246 * Some pages just aren't movable.
1248 * @return boolean
1250 public function isMovable() {
1251 return Namespace::isMovable( $this->getNamespace() )
1252 && $this->getInterwiki() == '';
1256 * Can $wgUser read this page?
1257 * @return boolean
1258 * @todo fold these checks into userCan()
1260 public function userCanRead() {
1261 global $wgUser;
1263 $result = null;
1264 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1265 if ( $result !== null ) {
1266 return $result;
1269 if( $wgUser->isAllowed( 'read' ) ) {
1270 return true;
1271 } else {
1272 global $wgWhitelistRead;
1274 /**
1275 * Always grant access to the login page.
1276 * Even anons need to be able to log in.
1278 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1279 return true;
1283 * Bail out if there isn't whitelist
1285 if( !is_array($wgWhitelistRead) ) {
1286 return false;
1290 * Check for explicit whitelisting
1292 $name = $this->getPrefixedText();
1293 if( in_array( $name, $wgWhitelistRead, true ) )
1294 return true;
1297 * Old settings might have the title prefixed with
1298 * a colon for main-namespace pages
1300 if( $this->getNamespace() == NS_MAIN ) {
1301 if( in_array( ':' . $name, $wgWhitelistRead ) )
1302 return true;
1306 * If it's a special page, ditch the subpage bit
1307 * and check again
1309 if( $this->getNamespace() == NS_SPECIAL ) {
1310 $name = $this->getText();
1311 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1312 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1313 if( in_array( $pure, $wgWhitelistRead, true ) )
1314 return true;
1318 return false;
1322 * Is this a talk page of some sort?
1323 * @return bool
1325 public function isTalkPage() {
1326 return Namespace::isTalk( $this->getNamespace() );
1330 * Is this a subpage?
1331 * @return bool
1333 public function isSubpage() {
1334 global $wgNamespacesWithSubpages;
1336 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1337 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1338 } else {
1339 return false;
1344 * Could this page contain custom CSS or JavaScript, based
1345 * on the title?
1347 * @return bool
1349 public function isCssOrJsPage() {
1350 return $this->mNamespace == NS_MEDIAWIKI
1351 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1355 * Is this a .css or .js subpage of a user page?
1356 * @return bool
1358 public function isCssJsSubpage() {
1359 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1362 * Is this a *valid* .css or .js subpage of a user page?
1363 * Check that the corresponding skin exists
1365 public function isValidCssJsSubpage() {
1366 if ( $this->isCssJsSubpage() ) {
1367 $skinNames = Skin::getSkinNames();
1368 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1369 } else {
1370 return false;
1374 * Trim down a .css or .js subpage title to get the corresponding skin name
1376 public function getSkinFromCssJsSubpage() {
1377 $subpage = explode( '/', $this->mTextform );
1378 $subpage = $subpage[ count( $subpage ) - 1 ];
1379 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1382 * Is this a .css subpage of a user page?
1383 * @return bool
1385 public function isCssSubpage() {
1386 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1389 * Is this a .js subpage of a user page?
1390 * @return bool
1392 public function isJsSubpage() {
1393 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1396 * Protect css/js subpages of user pages: can $wgUser edit
1397 * this page?
1399 * @return boolean
1400 * @todo XXX: this might be better using restrictions
1402 public function userCanEditCssJsSubpage() {
1403 global $wgUser;
1404 return ( $wgUser->isAllowed('editusercssjs') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1408 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1410 * @return bool If the page is subject to cascading restrictions.
1412 public function isCascadeProtected() {
1413 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1414 return ( $sources > 0 );
1418 * Cascading protection: Get the source of any cascading restrictions on this page.
1420 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1421 * @return array( mixed title array, restriction array)
1422 * 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.
1423 * The restriction array is an array of each type, each of which contains an array of unique groups
1425 public function getCascadeProtectionSources( $get_pages = true ) {
1426 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1428 # Define our dimension of restrictions types
1429 $pagerestrictions = array();
1430 foreach( $wgRestrictionTypes as $action )
1431 $pagerestrictions[$action] = array();
1433 if (!$wgEnableCascadingProtection)
1434 return array( false, $pagerestrictions );
1436 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1437 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1438 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1439 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1442 wfProfileIn( __METHOD__ );
1444 $dbr = wfGetDb( DB_SLAVE );
1446 if ( $this->getNamespace() == NS_IMAGE ) {
1447 $tables = array ('imagelinks', 'page_restrictions');
1448 $where_clauses = array(
1449 'il_to' => $this->getDBkey(),
1450 'il_from=pr_page',
1451 'pr_cascade' => 1 );
1452 } else {
1453 $tables = array ('templatelinks', 'page_restrictions');
1454 $where_clauses = array(
1455 'tl_namespace' => $this->getNamespace(),
1456 'tl_title' => $this->getDBkey(),
1457 'tl_from=pr_page',
1458 'pr_cascade' => 1 );
1461 if ( $get_pages ) {
1462 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1463 $where_clauses[] = 'page_id=pr_page';
1464 $tables[] = 'page';
1465 } else {
1466 $cols = array( 'pr_expiry' );
1469 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1471 $sources = $get_pages ? array() : false;
1472 $now = wfTimestampNow();
1473 $purgeExpired = false;
1475 while( $row = $dbr->fetchObject( $res ) ) {
1476 $expiry = Block::decodeExpiry( $row->pr_expiry );
1477 if( $expiry > $now ) {
1478 if ($get_pages) {
1479 $page_id = $row->pr_page;
1480 $page_ns = $row->page_namespace;
1481 $page_title = $row->page_title;
1482 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1483 # Add groups needed for each restriction type if its not already there
1484 # Make sure this restriction type still exists
1485 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1486 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1488 } else {
1489 $sources = true;
1491 } else {
1492 // Trigger lazy purge of expired restrictions from the db
1493 $purgeExpired = true;
1496 if( $purgeExpired ) {
1497 Title::purgeExpiredRestrictions();
1500 wfProfileOut( __METHOD__ );
1502 if ( $get_pages ) {
1503 $this->mCascadeSources = $sources;
1504 $this->mCascadingRestrictions = $pagerestrictions;
1505 } else {
1506 $this->mHasCascadingRestrictions = $sources;
1509 return array( $sources, $pagerestrictions );
1512 function areRestrictionsCascading() {
1513 if (!$this->mRestrictionsLoaded) {
1514 $this->loadRestrictions();
1517 return $this->mCascadeRestriction;
1521 * Loads a string into mRestrictions array
1522 * @param resource $res restrictions as an SQL result.
1524 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1525 $dbr = wfGetDb( DB_SLAVE );
1527 $this->mRestrictions['edit'] = array();
1528 $this->mRestrictions['move'] = array();
1530 # Backwards-compatibility: also load the restrictions from the page record (old format).
1532 if ( $oldFashionedRestrictions == NULL ) {
1533 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1536 if ($oldFashionedRestrictions != '') {
1538 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1539 $temp = explode( '=', trim( $restrict ) );
1540 if(count($temp) == 1) {
1541 // old old format should be treated as edit/move restriction
1542 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1543 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1544 } else {
1545 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1549 $this->mOldRestrictions = true;
1550 $this->mCascadeRestriction = false;
1551 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1555 if( $dbr->numRows( $res ) ) {
1556 # Current system - load second to make them override.
1557 $now = wfTimestampNow();
1558 $purgeExpired = false;
1560 while ($row = $dbr->fetchObject( $res ) ) {
1561 # Cycle through all the restrictions.
1563 // This code should be refactored, now that it's being used more generally,
1564 // But I don't really see any harm in leaving it in Block for now -werdna
1565 $expiry = Block::decodeExpiry( $row->pr_expiry );
1567 // Only apply the restrictions if they haven't expired!
1568 if ( !$expiry || $expiry > $now ) {
1569 $this->mRestrictionsExpiry = $expiry;
1570 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1572 $this->mCascadeRestriction |= $row->pr_cascade;
1573 } else {
1574 // Trigger a lazy purge of expired restrictions
1575 $purgeExpired = true;
1579 if( $purgeExpired ) {
1580 Title::purgeExpiredRestrictions();
1584 $this->mRestrictionsLoaded = true;
1587 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1588 if( !$this->mRestrictionsLoaded ) {
1589 $dbr = wfGetDB( DB_SLAVE );
1591 $res = $dbr->select( 'page_restrictions', '*',
1592 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1594 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1599 * Purge expired restrictions from the page_restrictions table
1601 static function purgeExpiredRestrictions() {
1602 $dbw = wfGetDB( DB_MASTER );
1603 $dbw->delete( 'page_restrictions',
1604 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1605 __METHOD__ );
1609 * Accessor/initialisation for mRestrictions
1611 * @param string $action action that permission needs to be checked for
1612 * @return array the array of groups allowed to edit this article
1614 public function getRestrictions( $action ) {
1615 if( $this->exists() ) {
1616 if( !$this->mRestrictionsLoaded ) {
1617 $this->loadRestrictions();
1619 return isset( $this->mRestrictions[$action] )
1620 ? $this->mRestrictions[$action]
1621 : array();
1622 } else {
1623 return array();
1628 * Is there a version of this page in the deletion archive?
1629 * @return int the number of archived revisions
1631 public function isDeleted() {
1632 $fname = 'Title::isDeleted';
1633 if ( $this->getNamespace() < 0 ) {
1634 $n = 0;
1635 } else {
1636 $dbr = wfGetDB( DB_SLAVE );
1637 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1638 'ar_title' => $this->getDBkey() ), $fname );
1639 if( $this->getNamespace() == NS_IMAGE ) {
1640 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1641 array( 'fa_name' => $this->getDBkey() ), $fname );
1644 return (int)$n;
1648 * Get the article ID for this Title from the link cache,
1649 * adding it if necessary
1650 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1651 * for update
1652 * @return int the ID
1654 public function getArticleID( $flags = 0 ) {
1655 $linkCache =& LinkCache::singleton();
1656 if ( $flags & GAID_FOR_UPDATE ) {
1657 $oldUpdate = $linkCache->forUpdate( true );
1658 $this->mArticleID = $linkCache->addLinkObj( $this );
1659 $linkCache->forUpdate( $oldUpdate );
1660 } else {
1661 if ( -1 == $this->mArticleID ) {
1662 $this->mArticleID = $linkCache->addLinkObj( $this );
1665 return $this->mArticleID;
1668 public function getLatestRevID() {
1669 if ($this->mLatestID !== false)
1670 return $this->mLatestID;
1672 $db = wfGetDB(DB_SLAVE);
1673 return $this->mLatestID = $db->selectField( 'revision',
1674 "max(rev_id)",
1675 array('rev_page' => $this->getArticleID()),
1676 'Title::getLatestRevID' );
1680 * This clears some fields in this object, and clears any associated
1681 * keys in the "bad links" section of the link cache.
1683 * - This is called from Article::insertNewArticle() to allow
1684 * loading of the new page_id. It's also called from
1685 * Article::doDeleteArticle()
1687 * @param int $newid the new Article ID
1689 public function resetArticleID( $newid ) {
1690 $linkCache =& LinkCache::singleton();
1691 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1693 if ( 0 == $newid ) { $this->mArticleID = -1; }
1694 else { $this->mArticleID = $newid; }
1695 $this->mRestrictionsLoaded = false;
1696 $this->mRestrictions = array();
1700 * Updates page_touched for this page; called from LinksUpdate.php
1701 * @return bool true if the update succeded
1703 public function invalidateCache() {
1704 global $wgUseFileCache;
1706 if ( wfReadOnly() ) {
1707 return;
1710 $dbw = wfGetDB( DB_MASTER );
1711 $success = $dbw->update( 'page',
1712 array( /* SET */
1713 'page_touched' => $dbw->timestamp()
1714 ), array( /* WHERE */
1715 'page_namespace' => $this->getNamespace() ,
1716 'page_title' => $this->getDBkey()
1717 ), 'Title::invalidateCache'
1720 if ($wgUseFileCache) {
1721 $cache = new HTMLFileCache($this);
1722 @unlink($cache->fileCacheName());
1725 return $success;
1729 * Prefix some arbitrary text with the namespace or interwiki prefix
1730 * of this object
1732 * @param string $name the text
1733 * @return string the prefixed text
1734 * @private
1736 /* private */ function prefix( $name ) {
1737 $p = '';
1738 if ( '' != $this->mInterwiki ) {
1739 $p = $this->mInterwiki . ':';
1741 if ( 0 != $this->mNamespace ) {
1742 $p .= $this->getNsText() . ':';
1744 return $p . $name;
1748 * Secure and split - main initialisation function for this object
1750 * Assumes that mDbkeyform has been set, and is urldecoded
1751 * and uses underscores, but not otherwise munged. This function
1752 * removes illegal characters, splits off the interwiki and
1753 * namespace prefixes, sets the other forms, and canonicalizes
1754 * everything.
1755 * @return bool true on success
1757 private function secureAndSplit() {
1758 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1760 # Initialisation
1761 static $rxTc = false;
1762 if( !$rxTc ) {
1763 # % is needed as well
1764 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1767 $this->mInterwiki = $this->mFragment = '';
1768 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1770 $dbkey = $this->mDbkeyform;
1772 # Strip Unicode bidi override characters.
1773 # Sometimes they slip into cut-n-pasted page titles, where the
1774 # override chars get included in list displays.
1775 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1776 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1778 # Clean up whitespace
1780 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1781 $dbkey = trim( $dbkey, '_' );
1783 if ( '' == $dbkey ) {
1784 return false;
1787 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1788 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1789 return false;
1792 $this->mDbkeyform = $dbkey;
1794 # Initial colon indicates main namespace rather than specified default
1795 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1796 if ( ':' == $dbkey{0} ) {
1797 $this->mNamespace = NS_MAIN;
1798 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1799 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1802 # Namespace or interwiki prefix
1803 $firstPass = true;
1804 do {
1805 $m = array();
1806 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1807 $p = $m[1];
1808 if ( $ns = $wgContLang->getNsIndex( $p )) {
1809 # Ordinary namespace
1810 $dbkey = $m[2];
1811 $this->mNamespace = $ns;
1812 } elseif( $this->getInterwikiLink( $p ) ) {
1813 if( !$firstPass ) {
1814 # Can't make a local interwiki link to an interwiki link.
1815 # That's just crazy!
1816 return false;
1819 # Interwiki link
1820 $dbkey = $m[2];
1821 $this->mInterwiki = $wgContLang->lc( $p );
1823 # Redundant interwiki prefix to the local wiki
1824 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1825 if( $dbkey == '' ) {
1826 # Can't have an empty self-link
1827 return false;
1829 $this->mInterwiki = '';
1830 $firstPass = false;
1831 # Do another namespace split...
1832 continue;
1835 # If there's an initial colon after the interwiki, that also
1836 # resets the default namespace
1837 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1838 $this->mNamespace = NS_MAIN;
1839 $dbkey = substr( $dbkey, 1 );
1842 # If there's no recognized interwiki or namespace,
1843 # then let the colon expression be part of the title.
1845 break;
1846 } while( true );
1848 # We already know that some pages won't be in the database!
1850 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1851 $this->mArticleID = 0;
1853 $fragment = strstr( $dbkey, '#' );
1854 if ( false !== $fragment ) {
1855 $this->setFragment( $fragment );
1856 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1857 # remove whitespace again: prevents "Foo_bar_#"
1858 # becoming "Foo_bar_"
1859 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1862 # Reject illegal characters.
1864 if( preg_match( $rxTc, $dbkey ) ) {
1865 return false;
1869 * Pages with "/./" or "/../" appearing in the URLs will
1870 * often be unreachable due to the way web browsers deal
1871 * with 'relative' URLs. Forbid them explicitly.
1873 if ( strpos( $dbkey, '.' ) !== false &&
1874 ( $dbkey === '.' || $dbkey === '..' ||
1875 strpos( $dbkey, './' ) === 0 ||
1876 strpos( $dbkey, '../' ) === 0 ||
1877 strpos( $dbkey, '/./' ) !== false ||
1878 strpos( $dbkey, '/../' ) !== false ) )
1880 return false;
1884 * Magic tilde sequences? Nu-uh!
1886 if( strpos( $dbkey, '~~~' ) !== false ) {
1887 return false;
1891 * Limit the size of titles to 255 bytes.
1892 * This is typically the size of the underlying database field.
1893 * We make an exception for special pages, which don't need to be stored
1894 * in the database, and may edge over 255 bytes due to subpage syntax
1895 * for long titles, e.g. [[Special:Block/Long name]]
1897 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1898 strlen( $dbkey ) > 512 )
1900 return false;
1904 * Normally, all wiki links are forced to have
1905 * an initial capital letter so [[foo]] and [[Foo]]
1906 * point to the same place.
1908 * Don't force it for interwikis, since the other
1909 * site might be case-sensitive.
1911 $this->mUserCaseDBKey = $dbkey;
1912 if( $wgCapitalLinks && $this->mInterwiki == '') {
1913 $dbkey = $wgContLang->ucfirst( $dbkey );
1917 * Can't make a link to a namespace alone...
1918 * "empty" local links can only be self-links
1919 * with a fragment identifier.
1921 if( $dbkey == '' &&
1922 $this->mInterwiki == '' &&
1923 $this->mNamespace != NS_MAIN ) {
1924 return false;
1926 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
1927 // IP names are not allowed for accounts, and can only be referring to
1928 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
1929 // there are numerous ways to present the same IP. Having sp:contribs scan
1930 // them all is silly and having some show the edits and others not is
1931 // inconsistent. Same for talk/userpages. Keep them normalized instead.
1932 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
1933 IP::sanitizeIP( $dbkey ) : $dbkey;
1934 // Any remaining initial :s are illegal.
1935 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1936 return false;
1939 # Fill fields
1940 $this->mDbkeyform = $dbkey;
1941 $this->mUrlform = wfUrlencode( $dbkey );
1943 $this->mTextform = str_replace( '_', ' ', $dbkey );
1945 return true;
1949 * Set the fragment for this title
1950 * This is kind of bad, since except for this rarely-used function, Title objects
1951 * are immutable. The reason this is here is because it's better than setting the
1952 * members directly, which is what Linker::formatComment was doing previously.
1954 * @param string $fragment text
1955 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1957 public function setFragment( $fragment ) {
1958 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1962 * Get a Title object associated with the talk page of this article
1963 * @return Title the object for the talk page
1965 public function getTalkPage() {
1966 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1970 * Get a title object associated with the subject page of this
1971 * talk page
1973 * @return Title the object for the subject page
1975 public function getSubjectPage() {
1976 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1980 * Get an array of Title objects linking to this Title
1981 * Also stores the IDs in the link cache.
1983 * WARNING: do not use this function on arbitrary user-supplied titles!
1984 * On heavily-used templates it will max out the memory.
1986 * @param string $options may be FOR UPDATE
1987 * @return array the Title objects linking here
1989 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1990 $linkCache =& LinkCache::singleton();
1992 if ( $options ) {
1993 $db = wfGetDB( DB_MASTER );
1994 } else {
1995 $db = wfGetDB( DB_SLAVE );
1998 $res = $db->select( array( 'page', $table ),
1999 array( 'page_namespace', 'page_title', 'page_id' ),
2000 array(
2001 "{$prefix}_from=page_id",
2002 "{$prefix}_namespace" => $this->getNamespace(),
2003 "{$prefix}_title" => $this->getDbKey() ),
2004 'Title::getLinksTo',
2005 $options );
2007 $retVal = array();
2008 if ( $db->numRows( $res ) ) {
2009 while ( $row = $db->fetchObject( $res ) ) {
2010 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2011 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
2012 $retVal[] = $titleObj;
2016 $db->freeResult( $res );
2017 return $retVal;
2021 * Get an array of Title objects using this Title as a template
2022 * Also stores the IDs in the link cache.
2024 * WARNING: do not use this function on arbitrary user-supplied titles!
2025 * On heavily-used templates it will max out the memory.
2027 * @param string $options may be FOR UPDATE
2028 * @return array the Title objects linking here
2030 public function getTemplateLinksTo( $options = '' ) {
2031 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2035 * Get an array of Title objects referring to non-existent articles linked from this page
2037 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2038 * @param string $options may be FOR UPDATE
2039 * @return array the Title objects
2041 public function getBrokenLinksFrom( $options = '' ) {
2042 if ( $this->getArticleId() == 0 ) {
2043 # All links from article ID 0 are false positives
2044 return array();
2047 if ( $options ) {
2048 $db = wfGetDB( DB_MASTER );
2049 } else {
2050 $db = wfGetDB( DB_SLAVE );
2053 $res = $db->safeQuery(
2054 "SELECT pl_namespace, pl_title
2055 FROM !
2056 LEFT JOIN !
2057 ON pl_namespace=page_namespace
2058 AND pl_title=page_title
2059 WHERE pl_from=?
2060 AND page_namespace IS NULL
2062 $db->tableName( 'pagelinks' ),
2063 $db->tableName( 'page' ),
2064 $this->getArticleId(),
2065 $options );
2067 $retVal = array();
2068 if ( $db->numRows( $res ) ) {
2069 while ( $row = $db->fetchObject( $res ) ) {
2070 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2073 $db->freeResult( $res );
2074 return $retVal;
2079 * Get a list of URLs to purge from the Squid cache when this
2080 * page changes
2082 * @return array the URLs
2084 public function getSquidURLs() {
2085 global $wgContLang;
2087 $urls = array(
2088 $this->getInternalURL(),
2089 $this->getInternalURL( 'action=history' )
2092 // purge variant urls as well
2093 if($wgContLang->hasVariants()){
2094 $variants = $wgContLang->getVariants();
2095 foreach($variants as $vCode){
2096 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2097 $urls[] = $this->getInternalURL('',$vCode);
2101 return $urls;
2104 public function purgeSquid() {
2105 global $wgUseSquid;
2106 if ( $wgUseSquid ) {
2107 $urls = $this->getSquidURLs();
2108 $u = new SquidUpdate( $urls );
2109 $u->doUpdate();
2114 * Move this page without authentication
2115 * @param Title &$nt the new page Title
2117 public function moveNoAuth( &$nt ) {
2118 return $this->moveTo( $nt, false );
2122 * Check whether a given move operation would be valid.
2123 * Returns true if ok, or a message key string for an error message
2124 * if invalid. (Scarrrrry ugly interface this.)
2125 * @param Title &$nt the new title
2126 * @param bool $auth indicates whether $wgUser's permissions
2127 * should be checked
2128 * @return mixed true on success, message name on failure
2130 public function isValidMoveOperation( &$nt, $auth = true ) {
2131 if( !$this or !$nt ) {
2132 return 'badtitletext';
2134 if( $this->equals( $nt ) ) {
2135 return 'selfmove';
2137 if( !$this->isMovable() || !$nt->isMovable() ) {
2138 return 'immobile_namespace';
2141 $oldid = $this->getArticleID();
2142 $newid = $nt->getArticleID();
2144 if ( strlen( $nt->getDBkey() ) < 1 ) {
2145 return 'articleexists';
2147 if ( ( '' == $this->getDBkey() ) ||
2148 ( !$oldid ) ||
2149 ( '' == $nt->getDBkey() ) ) {
2150 return 'badarticleerror';
2153 if ( $auth && (
2154 !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
2155 !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
2156 return 'protectedpage';
2159 # The move is allowed only if (1) the target doesn't exist, or
2160 # (2) the target is a redirect to the source, and has no history
2161 # (so we can undo bad moves right after they're done).
2163 if ( 0 != $newid ) { # Target exists; check for validity
2164 if ( ! $this->isValidMoveTarget( $nt ) ) {
2165 return 'articleexists';
2168 return true;
2172 * Move a title to a new location
2173 * @param Title &$nt the new title
2174 * @param bool $auth indicates whether $wgUser's permissions
2175 * should be checked
2176 * @return mixed true on success, message name on failure
2178 public function moveTo( &$nt, $auth = true, $reason = '' ) {
2179 $err = $this->isValidMoveOperation( $nt, $auth );
2180 if( is_string( $err ) ) {
2181 return $err;
2184 $pageid = $this->getArticleID();
2185 if( $nt->exists() ) {
2186 $this->moveOverExistingRedirect( $nt, $reason );
2187 $pageCountChange = 0;
2188 } else { # Target didn't exist, do normal move.
2189 $this->moveToNewTitle( $nt, $reason );
2190 $pageCountChange = 1;
2192 $redirid = $this->getArticleID();
2194 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2195 $dbw = wfGetDB( DB_MASTER );
2196 $categorylinks = $dbw->tableName( 'categorylinks' );
2197 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2198 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2199 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2200 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2202 # Update watchlists
2204 $oldnamespace = $this->getNamespace() & ~1;
2205 $newnamespace = $nt->getNamespace() & ~1;
2206 $oldtitle = $this->getDBkey();
2207 $newtitle = $nt->getDBkey();
2209 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2210 WatchedItem::duplicateEntries( $this, $nt );
2213 # Update search engine
2214 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2215 $u->doUpdate();
2216 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2217 $u->doUpdate();
2219 # Update site_stats
2220 if( $this->isContentPage() && !$nt->isContentPage() ) {
2221 # No longer a content page
2222 # Not viewed, edited, removing
2223 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2224 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2225 # Now a content page
2226 # Not viewed, edited, adding
2227 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2228 } elseif( $pageCountChange ) {
2229 # Redirect added
2230 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2231 } else {
2232 # Nothing special
2233 $u = false;
2235 if( $u )
2236 $u->doUpdate();
2238 global $wgUser;
2239 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2240 return true;
2244 * Move page to a title which is at present a redirect to the
2245 * source page
2247 * @param Title &$nt the page to move to, which should currently
2248 * be a redirect
2250 private function moveOverExistingRedirect( &$nt, $reason = '' ) {
2251 global $wgUseSquid;
2252 $fname = 'Title::moveOverExistingRedirect';
2253 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2255 if ( $reason ) {
2256 $comment .= ": $reason";
2259 $now = wfTimestampNow();
2260 $newid = $nt->getArticleID();
2261 $oldid = $this->getArticleID();
2262 $dbw = wfGetDB( DB_MASTER );
2263 $linkCache =& LinkCache::singleton();
2265 # Delete the old redirect. We don't save it to history since
2266 # by definition if we've got here it's rather uninteresting.
2267 # We have to remove it so that the next step doesn't trigger
2268 # a conflict on the unique namespace+title index...
2269 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2271 # Save a null revision in the page's history notifying of the move
2272 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2273 $nullRevId = $nullRevision->insertOn( $dbw );
2275 # Change the name of the target page:
2276 $dbw->update( 'page',
2277 /* SET */ array(
2278 'page_touched' => $dbw->timestamp($now),
2279 'page_namespace' => $nt->getNamespace(),
2280 'page_title' => $nt->getDBkey(),
2281 'page_latest' => $nullRevId,
2283 /* WHERE */ array( 'page_id' => $oldid ),
2284 $fname
2286 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2288 # Recreate the redirect, this time in the other direction.
2289 $mwRedir = MagicWord::get( 'redirect' );
2290 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2291 $redirectArticle = new Article( $this );
2292 $newid = $redirectArticle->insertOn( $dbw );
2293 $redirectRevision = new Revision( array(
2294 'page' => $newid,
2295 'comment' => $comment,
2296 'text' => $redirectText ) );
2297 $redirectRevision->insertOn( $dbw );
2298 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2299 $linkCache->clearLink( $this->getPrefixedDBkey() );
2301 # Log the move
2302 $log = new LogPage( 'move' );
2303 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2305 # Now, we record the link from the redirect to the new title.
2306 # It should have no other outgoing links...
2307 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2308 $dbw->insert( 'pagelinks',
2309 array(
2310 'pl_from' => $newid,
2311 'pl_namespace' => $nt->getNamespace(),
2312 'pl_title' => $nt->getDbKey() ),
2313 $fname );
2315 # Purge squid
2316 if ( $wgUseSquid ) {
2317 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2318 $u = new SquidUpdate( $urls );
2319 $u->doUpdate();
2324 * Move page to non-existing title.
2325 * @param Title &$nt the new Title
2327 private function moveToNewTitle( &$nt, $reason = '' ) {
2328 global $wgUseSquid;
2329 $fname = 'MovePageForm::moveToNewTitle';
2330 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2331 if ( $reason ) {
2332 $comment .= ": $reason";
2335 $newid = $nt->getArticleID();
2336 $oldid = $this->getArticleID();
2337 $dbw = wfGetDB( DB_MASTER );
2338 $now = $dbw->timestamp();
2339 $linkCache =& LinkCache::singleton();
2341 # Save a null revision in the page's history notifying of the move
2342 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2343 $nullRevId = $nullRevision->insertOn( $dbw );
2345 # Rename cur entry
2346 $dbw->update( 'page',
2347 /* SET */ array(
2348 'page_touched' => $now,
2349 'page_namespace' => $nt->getNamespace(),
2350 'page_title' => $nt->getDBkey(),
2351 'page_latest' => $nullRevId,
2353 /* WHERE */ array( 'page_id' => $oldid ),
2354 $fname
2357 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2359 # Insert redirect
2360 $mwRedir = MagicWord::get( 'redirect' );
2361 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2362 $redirectArticle = new Article( $this );
2363 $newid = $redirectArticle->insertOn( $dbw );
2364 $redirectRevision = new Revision( array(
2365 'page' => $newid,
2366 'comment' => $comment,
2367 'text' => $redirectText ) );
2368 $redirectRevision->insertOn( $dbw );
2369 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2370 $linkCache->clearLink( $this->getPrefixedDBkey() );
2372 # Log the move
2373 $log = new LogPage( 'move' );
2374 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2376 # Purge caches as per article creation
2377 Article::onArticleCreate( $nt );
2379 # Record the just-created redirect's linking to the page
2380 $dbw->insert( 'pagelinks',
2381 array(
2382 'pl_from' => $newid,
2383 'pl_namespace' => $nt->getNamespace(),
2384 'pl_title' => $nt->getDBkey() ),
2385 $fname );
2387 # Purge old title from squid
2388 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2389 $this->purgeSquid();
2393 * Checks if $this can be moved to a given Title
2394 * - Selects for update, so don't call it unless you mean business
2396 * @param Title &$nt the new title to check
2398 public function isValidMoveTarget( $nt ) {
2400 $fname = 'Title::isValidMoveTarget';
2401 $dbw = wfGetDB( DB_MASTER );
2403 # Is it a redirect?
2404 $id = $nt->getArticleID();
2405 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2406 array( 'page_is_redirect','old_text','old_flags' ),
2407 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2408 $fname, 'FOR UPDATE' );
2410 if ( !$obj || 0 == $obj->page_is_redirect ) {
2411 # Not a redirect
2412 wfDebug( __METHOD__ . ": not a redirect\n" );
2413 return false;
2415 $text = Revision::getRevisionText( $obj );
2417 # Does the redirect point to the source?
2418 # Or is it a broken self-redirect, usually caused by namespace collisions?
2419 $m = array();
2420 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2421 $redirTitle = Title::newFromText( $m[1] );
2422 if( !is_object( $redirTitle ) ||
2423 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2424 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2425 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2426 return false;
2428 } else {
2429 # Fail safe
2430 wfDebug( __METHOD__ . ": failsafe\n" );
2431 return false;
2434 # Does the article have a history?
2435 $row = $dbw->selectRow( array( 'page', 'revision'),
2436 array( 'rev_id' ),
2437 array( 'page_namespace' => $nt->getNamespace(),
2438 'page_title' => $nt->getDBkey(),
2439 'page_id=rev_page AND page_latest != rev_id'
2440 ), $fname, 'FOR UPDATE'
2443 # Return true if there was no history
2444 return $row === false;
2448 * Can this title be added to a user's watchlist?
2450 * @return bool
2452 public function isWatchable() {
2453 return !$this->isExternal()
2454 && Namespace::isWatchable( $this->getNamespace() );
2458 * Get categories to which this Title belongs and return an array of
2459 * categories' names.
2461 * @return array an array of parents in the form:
2462 * $parent => $currentarticle
2464 public function getParentCategories() {
2465 global $wgContLang;
2467 $titlekey = $this->getArticleId();
2468 $dbr = wfGetDB( DB_SLAVE );
2469 $categorylinks = $dbr->tableName( 'categorylinks' );
2471 # NEW SQL
2472 $sql = "SELECT * FROM $categorylinks"
2473 ." WHERE cl_from='$titlekey'"
2474 ." AND cl_from <> '0'"
2475 ." ORDER BY cl_sortkey";
2477 $res = $dbr->query ( $sql ) ;
2479 if($dbr->numRows($res) > 0) {
2480 while ( $x = $dbr->fetchObject ( $res ) )
2481 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2482 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2483 $dbr->freeResult ( $res ) ;
2484 } else {
2485 $data = '';
2487 return $data;
2491 * Get a tree of parent categories
2492 * @param array $children an array with the children in the keys, to check for circular refs
2493 * @return array
2495 public function getParentCategoryTree( $children = array() ) {
2496 $parents = $this->getParentCategories();
2498 if($parents != '') {
2499 foreach($parents as $parent => $current) {
2500 if ( array_key_exists( $parent, $children ) ) {
2501 # Circular reference
2502 $stack[$parent] = array();
2503 } else {
2504 $nt = Title::newFromText($parent);
2505 if ( $nt ) {
2506 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2510 return $stack;
2511 } else {
2512 return array();
2518 * Get an associative array for selecting this title from
2519 * the "page" table
2521 * @return array
2523 public function pageCond() {
2524 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2528 * Get the revision ID of the previous revision
2530 * @param integer $revision Revision ID. Get the revision that was before this one.
2531 * @return integer $oldrevision|false
2533 public function getPreviousRevisionID( $revision ) {
2534 $dbr = wfGetDB( DB_SLAVE );
2535 return $dbr->selectField( 'revision', 'rev_id',
2536 'rev_page=' . intval( $this->getArticleId() ) .
2537 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2541 * Get the revision ID of the next revision
2543 * @param integer $revision Revision ID. Get the revision that was after this one.
2544 * @return integer $oldrevision|false
2546 public function getNextRevisionID( $revision ) {
2547 $dbr = wfGetDB( DB_SLAVE );
2548 return $dbr->selectField( 'revision', 'rev_id',
2549 'rev_page=' . intval( $this->getArticleId() ) .
2550 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2554 * Get the number of revisions between the given revision IDs.
2556 * @param integer $old Revision ID.
2557 * @param integer $new Revision ID.
2558 * @return integer Number of revisions between these IDs.
2560 public function countRevisionsBetween( $old, $new ) {
2561 $dbr = wfGetDB( DB_SLAVE );
2562 return $dbr->selectField( 'revision', 'count(*)',
2563 'rev_page = ' . intval( $this->getArticleId() ) .
2564 ' AND rev_id > ' . intval( $old ) .
2565 ' AND rev_id < ' . intval( $new ) );
2569 * Compare with another title.
2571 * @param Title $title
2572 * @return bool
2574 public function equals( $title ) {
2575 // Note: === is necessary for proper matching of number-like titles.
2576 return $this->getInterwiki() === $title->getInterwiki()
2577 && $this->getNamespace() == $title->getNamespace()
2578 && $this->getDbkey() === $title->getDbkey();
2582 * Return a string representation of this title
2584 * @return string
2586 public function __toString() {
2587 return $this->getPrefixedText();
2591 * Check if page exists
2592 * @return bool
2594 public function exists() {
2595 return $this->getArticleId() != 0;
2599 * Do we know that this title definitely exists, or should we otherwise
2600 * consider that it exists?
2602 * @return bool
2604 public function isAlwaysKnown() {
2605 return $this->isExternal()
2606 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
2607 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $this->mDbkeyform ) );
2611 * Update page_touched timestamps and send squid purge messages for
2612 * pages linking to this title. May be sent to the job queue depending
2613 * on the number of links. Typically called on create and delete.
2615 public function touchLinks() {
2616 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2617 $u->doUpdate();
2619 if ( $this->getNamespace() == NS_CATEGORY ) {
2620 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2621 $u->doUpdate();
2626 * Get the last touched timestamp
2628 public function getTouched() {
2629 $dbr = wfGetDB( DB_SLAVE );
2630 $touched = $dbr->selectField( 'page', 'page_touched',
2631 array(
2632 'page_namespace' => $this->getNamespace(),
2633 'page_title' => $this->getDBkey()
2634 ), __METHOD__
2636 return $touched;
2639 public function trackbackURL() {
2640 global $wgTitle, $wgScriptPath, $wgServer;
2642 return "$wgServer$wgScriptPath/trackback.php?article="
2643 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2646 public function trackbackRDF() {
2647 $url = htmlspecialchars($this->getFullURL());
2648 $title = htmlspecialchars($this->getText());
2649 $tburl = $this->trackbackURL();
2651 return "
2652 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2653 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2654 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2655 <rdf:Description
2656 rdf:about=\"$url\"
2657 dc:identifier=\"$url\"
2658 dc:title=\"$title\"
2659 trackback:ping=\"$tburl\" />
2660 </rdf:RDF>";
2664 * Generate strings used for xml 'id' names in monobook tabs
2665 * @return string
2667 public function getNamespaceKey() {
2668 global $wgContLang;
2669 switch ($this->getNamespace()) {
2670 case NS_MAIN:
2671 case NS_TALK:
2672 return 'nstab-main';
2673 case NS_USER:
2674 case NS_USER_TALK:
2675 return 'nstab-user';
2676 case NS_MEDIA:
2677 return 'nstab-media';
2678 case NS_SPECIAL:
2679 return 'nstab-special';
2680 case NS_PROJECT:
2681 case NS_PROJECT_TALK:
2682 return 'nstab-project';
2683 case NS_IMAGE:
2684 case NS_IMAGE_TALK:
2685 return 'nstab-image';
2686 case NS_MEDIAWIKI:
2687 case NS_MEDIAWIKI_TALK:
2688 return 'nstab-mediawiki';
2689 case NS_TEMPLATE:
2690 case NS_TEMPLATE_TALK:
2691 return 'nstab-template';
2692 case NS_HELP:
2693 case NS_HELP_TALK:
2694 return 'nstab-help';
2695 case NS_CATEGORY:
2696 case NS_CATEGORY_TALK:
2697 return 'nstab-category';
2698 default:
2699 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2704 * Returns true if this title resolves to the named special page
2705 * @param string $name The special page name
2707 public function isSpecial( $name ) {
2708 if ( $this->getNamespace() == NS_SPECIAL ) {
2709 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2710 if ( $name == $thisName ) {
2711 return true;
2714 return false;
2718 * If the Title refers to a special page alias which is not the local default,
2719 * returns a new Title which points to the local default. Otherwise, returns $this.
2721 public function fixSpecialName() {
2722 if ( $this->getNamespace() == NS_SPECIAL ) {
2723 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2724 if ( $canonicalName ) {
2725 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2726 if ( $localName != $this->mDbkeyform ) {
2727 return Title::makeTitle( NS_SPECIAL, $localName );
2731 return $this;
2735 * Is this Title in a namespace which contains content?
2736 * In other words, is this a content page, for the purposes of calculating
2737 * statistics, etc?
2739 * @return bool
2741 public function isContentPage() {
2742 return Namespace::isContent( $this->getNamespace() );