* (bug 13815) In the comment for page moves, use the colon-separator message instead...
[mediawiki.git] / includes / Title.php
blobd0b593ca72f1366f9a75fa88951bdb5399255e10
1 <?php
2 /**
3 * See title.txt
4 * @file
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 var $mLength; # The page length, 0 for special pages
67 var $mRedirect; # Is the article at this title a redirect?
68 /**#@-*/
71 /**
72 * Constructor
73 * @private
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
83 # See bug #696
84 $this->mDefaultNamespace = NS_MAIN;
85 $this->mWatched = NULL;
86 $this->mLatestID = false;
87 $this->mOldRestrictions = false;
88 $this->mLength = -1;
89 $this->mRedirect = NULL;
92 /**
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
96 * interwiki prefixes
97 * @return Title the new object, or NULL on an error
99 public static function newFromDBkey( $key ) {
100 $t = new Title();
101 $t->mDbkeyform = $key;
102 if( $t->secureAndSplit() )
103 return $t;
104 else
105 return NULL;
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
114 * are accepted
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
128 * caching them.
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 &eacute; &#257; or &#x3017; into real text...
139 $filteredText = Sanitizer::decodeCharReferences( $text );
141 $t = new Title();
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();
151 $cachedcount=0;
153 $cachedcount++;
154 Title::$titleCache[$text] =& $t;
156 return $t;
157 } else {
158 $ret = NULL;
159 return $ret;
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;
171 $t = new Title();
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() ) {
182 return $t;
183 } else {
184 return NULL;
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 * @param int $flags, use GAID_FOR_UPDATE to use master
196 * @return Title the new object, or NULL on an error
198 public static function newFromID( $id, $flags = 0 ) {
199 $fname = 'Title::newFromID';
200 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
201 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
202 array( 'page_id' => $id ), $fname );
203 if ( $row !== false ) {
204 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
205 } else {
206 $title = NULL;
208 return $title;
212 * Make an array of titles from an array of IDs
214 public static function newFromIDs( $ids ) {
215 if ( !count( $ids ) ) {
216 return array();
218 $dbr = wfGetDB( DB_SLAVE );
219 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
220 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
222 $titles = array();
223 while ( $row = $dbr->fetchObject( $res ) ) {
224 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
226 return $titles;
230 * Make a Title object from a DB row
231 * @param Row $row (needs at least page_title,page_namespace)
233 public static function newFromRow( $row ) {
234 $t = self::makeTitle( $row->page_namespace, $row->page_title );
236 $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1;
237 $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1;
238 $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL;
239 $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false;
241 return $t;
245 * Create a new Title from a namespace index and a DB key.
246 * It's assumed that $ns and $title are *valid*, for instance when
247 * they came directly from the database or a special page name.
248 * For convenience, spaces are converted to underscores so that
249 * eg user_text fields can be used directly.
251 * @param int $ns the namespace of the article
252 * @param string $title the unprefixed database key form
253 * @return Title the new object
255 public static function &makeTitle( $ns, $title ) {
256 $t = new Title();
257 $t->mInterwiki = '';
258 $t->mFragment = '';
259 $t->mNamespace = $ns = intval( $ns );
260 $t->mDbkeyform = str_replace( ' ', '_', $title );
261 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
262 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
263 $t->mTextform = str_replace( '_', ' ', $title );
264 return $t;
268 * Create a new Title from a namespace index and a DB key.
269 * The parameters will be checked for validity, which is a bit slower
270 * than makeTitle() but safer for user-provided data.
272 * @param int $ns the namespace of the article
273 * @param string $title the database key form
274 * @return Title the new object, or NULL on an error
276 public static function makeTitleSafe( $ns, $title ) {
277 $t = new Title();
278 $t->mDbkeyform = Title::makeName( $ns, $title );
279 if( $t->secureAndSplit() ) {
280 return $t;
281 } else {
282 return NULL;
287 * Create a new Title for the Main Page
288 * @return Title the new object
290 public static function newMainPage() {
291 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
292 // Don't give fatal errors if the message is broken
293 if ( !$title ) {
294 $title = Title::newFromText( 'Main Page' );
296 return $title;
300 * Extract a redirect destination from a string and return the
301 * Title, or null if the text doesn't contain a valid redirect
303 * @param string $text Text with possible redirect
304 * @return Title
306 public static function newFromRedirect( $text ) {
307 $redir = MagicWord::get( 'redirect' );
308 if( $redir->matchStart( trim($text) ) ) {
309 // Extract the first link and see if it's usable
310 $m = array();
311 if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
312 // Strip preceding colon used to "escape" categories, etc.
313 // and URL-decode links
314 if( strpos( $m[1], '%' ) !== false ) {
315 // Match behavior of inline link parsing here;
316 // don't interpret + as " " most of the time!
317 // It might be safe to just use rawurldecode instead, though.
318 $m[1] = urldecode( ltrim( $m[1], ':' ) );
320 $title = Title::newFromText( $m[1] );
321 // Redirects to Special:Userlogout are not permitted
322 if( $title instanceof Title && !$title->isSpecial( 'Userlogout' ) )
323 return $title;
326 return null;
329 #----------------------------------------------------------------------------
330 # Static functions
331 #----------------------------------------------------------------------------
334 * Get the prefixed DB key associated with an ID
335 * @param int $id the page_id of the article
336 * @return Title an object representing the article, or NULL
337 * if no such article was found
338 * @static
339 * @access public
341 function nameOf( $id ) {
342 $fname = 'Title::nameOf';
343 $dbr = wfGetDB( DB_SLAVE );
345 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
346 if ( $s === false ) { return NULL; }
348 $n = Title::makeName( $s->page_namespace, $s->page_title );
349 return $n;
353 * Get a regex character class describing the legal characters in a link
354 * @return string the list of characters, not delimited
356 public static function legalChars() {
357 global $wgLegalTitleChars;
358 return $wgLegalTitleChars;
362 * Get a string representation of a title suitable for
363 * including in a search index
365 * @param int $ns a namespace index
366 * @param string $title text-form main part
367 * @return string a stripped-down title string ready for the
368 * search index
370 public static function indexTitle( $ns, $title ) {
371 global $wgContLang;
373 $lc = SearchEngine::legalSearchChars() . '&#;';
374 $t = $wgContLang->stripForSearch( $title );
375 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
376 $t = $wgContLang->lc( $t );
378 # Handle 's, s'
379 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
380 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
382 $t = preg_replace( "/\\s+/", ' ', $t );
384 if ( $ns == NS_IMAGE ) {
385 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
387 return trim( $t );
391 * Make a prefixed DB key from a DB key and a namespace index
392 * @param int $ns numerical representation of the namespace
393 * @param string $title the DB key form the title
394 * @return string the prefixed form of the title
396 public static function makeName( $ns, $title ) {
397 global $wgContLang;
399 $n = $wgContLang->getNsText( $ns );
400 return $n == '' ? $title : "$n:$title";
404 * Returns the URL associated with an interwiki prefix
405 * @param string $key the interwiki prefix (e.g. "MeatBall")
406 * @return the associated URL, containing "$1", which should be
407 * replaced by an article title
408 * @static (arguably)
410 public function getInterwikiLink( $key ) {
411 global $wgMemc, $wgInterwikiExpiry;
412 global $wgInterwikiCache, $wgContLang;
413 $fname = 'Title::getInterwikiLink';
415 $key = $wgContLang->lc( $key );
417 $k = wfMemcKey( 'interwiki', $key );
418 if( array_key_exists( $k, Title::$interwikiCache ) ) {
419 return Title::$interwikiCache[$k]->iw_url;
422 if ($wgInterwikiCache) {
423 return Title::getInterwikiCached( $key );
426 $s = $wgMemc->get( $k );
427 # Ignore old keys with no iw_local
428 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
429 Title::$interwikiCache[$k] = $s;
430 return $s->iw_url;
433 $dbr = wfGetDB( DB_SLAVE );
434 $res = $dbr->select( 'interwiki',
435 array( 'iw_url', 'iw_local', 'iw_trans' ),
436 array( 'iw_prefix' => $key ), $fname );
437 if( !$res ) {
438 return '';
441 $s = $dbr->fetchObject( $res );
442 if( !$s ) {
443 # Cache non-existence: create a blank object and save it to memcached
444 $s = (object)false;
445 $s->iw_url = '';
446 $s->iw_local = 0;
447 $s->iw_trans = 0;
449 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
450 Title::$interwikiCache[$k] = $s;
452 return $s->iw_url;
456 * Fetch interwiki prefix data from local cache in constant database
458 * More logic is explained in DefaultSettings
460 * @return string URL of interwiki site
462 public static function getInterwikiCached( $key ) {
463 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
464 static $db, $site;
466 if (!$db)
467 $db=dba_open($wgInterwikiCache,'r','cdb');
468 /* Resolve site name */
469 if ($wgInterwikiScopes>=3 and !$site) {
470 $site = dba_fetch('__sites:' . wfWikiID(), $db);
471 if ($site=="")
472 $site = $wgInterwikiFallbackSite;
474 $value = dba_fetch( wfMemcKey( $key ), $db);
475 if ($value=='' and $wgInterwikiScopes>=3) {
476 /* try site-level */
477 $value = dba_fetch("_{$site}:{$key}", $db);
479 if ($value=='' and $wgInterwikiScopes>=2) {
480 /* try globals */
481 $value = dba_fetch("__global:{$key}", $db);
483 if ($value=='undef')
484 $value='';
485 $s = (object)false;
486 $s->iw_url = '';
487 $s->iw_local = 0;
488 $s->iw_trans = 0;
489 if ($value!='') {
490 list($local,$url)=explode(' ',$value,2);
491 $s->iw_url=$url;
492 $s->iw_local=(int)$local;
494 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
495 return $s->iw_url;
498 * Determine whether the object refers to a page within
499 * this project.
501 * @return bool TRUE if this is an in-project interwiki link
502 * or a wikilink, FALSE otherwise
504 public function isLocal() {
505 if ( $this->mInterwiki != '' ) {
506 # Make sure key is loaded into cache
507 $this->getInterwikiLink( $this->mInterwiki );
508 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
509 return (bool)(Title::$interwikiCache[$k]->iw_local);
510 } else {
511 return true;
516 * Determine whether the object refers to a page within
517 * this project and is transcludable.
519 * @return bool TRUE if this is transcludable
521 public function isTrans() {
522 if ($this->mInterwiki == '')
523 return false;
524 # Make sure key is loaded into cache
525 $this->getInterwikiLink( $this->mInterwiki );
526 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
527 return (bool)(Title::$interwikiCache[$k]->iw_trans);
531 * Escape a text fragment, say from a link, for a URL
533 static function escapeFragmentForURL( $fragment ) {
534 $fragment = str_replace( ' ', '_', $fragment );
535 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
536 $replaceArray = array(
537 '%3A' => ':',
538 '%' => '.'
540 return strtr( $fragment, $replaceArray );
543 #----------------------------------------------------------------------------
544 # Other stuff
545 #----------------------------------------------------------------------------
547 /** Simple accessors */
549 * Get the text form (spaces not underscores) of the main part
550 * @return string
552 public function getText() { return $this->mTextform; }
554 * Get the URL-encoded form of the main part
555 * @return string
557 public function getPartialURL() { return $this->mUrlform; }
559 * Get the main part with underscores
560 * @return string
562 public function getDBkey() { return $this->mDbkeyform; }
564 * Get the namespace index, i.e. one of the NS_xxxx constants
565 * @return int
567 public function getNamespace() { return $this->mNamespace; }
569 * Get the namespace text
570 * @return string
572 public function getNsText() {
573 global $wgContLang, $wgCanonicalNamespaceNames;
575 if ( '' != $this->mInterwiki ) {
576 // This probably shouldn't even happen. ohh man, oh yuck.
577 // But for interwiki transclusion it sometimes does.
578 // Shit. Shit shit shit.
580 // Use the canonical namespaces if possible to try to
581 // resolve a foreign namespace.
582 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
583 return $wgCanonicalNamespaceNames[$this->mNamespace];
586 return $wgContLang->getNsText( $this->mNamespace );
589 * Get the DB key with the initial letter case as specified by the user
591 function getUserCaseDBKey() {
592 return $this->mUserCaseDBKey;
595 * Get the namespace text of the subject (rather than talk) page
596 * @return string
598 public function getSubjectNsText() {
599 global $wgContLang;
600 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
604 * Get the namespace text of the talk page
605 * @return string
607 public function getTalkNsText() {
608 global $wgContLang;
609 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
613 * Could this title have a corresponding talk page?
614 * @return bool
616 public function canTalk() {
617 return( MWNamespace::canTalk( $this->mNamespace ) );
621 * Get the interwiki prefix (or null string)
622 * @return string
624 public function getInterwiki() { return $this->mInterwiki; }
626 * Get the Title fragment (i.e. the bit after the #) in text form
627 * @return string
629 public function getFragment() { return $this->mFragment; }
631 * Get the fragment in URL form, including the "#" character if there is one
632 * @return string
634 public function getFragmentForURL() {
635 if ( $this->mFragment == '' ) {
636 return '';
637 } else {
638 return '#' . Title::escapeFragmentForURL( $this->mFragment );
642 * Get the default namespace index, for when there is no namespace
643 * @return int
645 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
648 * Get title for search index
649 * @return string a stripped-down title string ready for the
650 * search index
652 public function getIndexTitle() {
653 return Title::indexTitle( $this->mNamespace, $this->mTextform );
657 * Get the prefixed database key form
658 * @return string the prefixed title, with underscores and
659 * any interwiki and namespace prefixes
661 public function getPrefixedDBkey() {
662 $s = $this->prefix( $this->mDbkeyform );
663 $s = str_replace( ' ', '_', $s );
664 return $s;
668 * Get the prefixed title with spaces.
669 * This is the form usually used for display
670 * @return string the prefixed title, with spaces
672 public function getPrefixedText() {
673 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
674 $s = $this->prefix( $this->mTextform );
675 $s = str_replace( '_', ' ', $s );
676 $this->mPrefixedText = $s;
678 return $this->mPrefixedText;
682 * Get the prefixed title with spaces, plus any fragment
683 * (part beginning with '#')
684 * @return string the prefixed title, with spaces and
685 * the fragment, including '#'
687 public function getFullText() {
688 $text = $this->getPrefixedText();
689 if( '' != $this->mFragment ) {
690 $text .= '#' . $this->mFragment;
692 return $text;
696 * Get the base name, i.e. the leftmost parts before the /
697 * @return string Base name
699 public function getBaseText() {
700 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
701 return $this->getText();
704 $parts = explode( '/', $this->getText() );
705 # Don't discard the real title if there's no subpage involved
706 if( count( $parts ) > 1 )
707 unset( $parts[ count( $parts ) - 1 ] );
708 return implode( '/', $parts );
712 * Get the lowest-level subpage name, i.e. the rightmost part after /
713 * @return string Subpage name
715 public function getSubpageText() {
716 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
717 return( $this->mTextform );
719 $parts = explode( '/', $this->mTextform );
720 return( $parts[ count( $parts ) - 1 ] );
724 * Get a URL-encoded form of the subpage text
725 * @return string URL-encoded subpage name
727 public function getSubpageUrlForm() {
728 $text = $this->getSubpageText();
729 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
730 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
731 return( $text );
735 * Get a URL-encoded title (not an actual URL) including interwiki
736 * @return string the URL-encoded form
738 public function getPrefixedURL() {
739 $s = $this->prefix( $this->mDbkeyform );
740 $s = str_replace( ' ', '_', $s );
742 $s = wfUrlencode ( $s ) ;
744 # Cleaning up URL to make it look nice -- is this safe?
745 $s = str_replace( '%28', '(', $s );
746 $s = str_replace( '%29', ')', $s );
748 return $s;
752 * Get a real URL referring to this title, with interwiki link and
753 * fragment
755 * @param string $query an optional query string, not used
756 * for interwiki links
757 * @param string $variant language variant of url (for sr, zh..)
758 * @return string the URL
760 public function getFullURL( $query = '', $variant = false ) {
761 global $wgContLang, $wgServer, $wgRequest;
763 if ( '' == $this->mInterwiki ) {
764 $url = $this->getLocalUrl( $query, $variant );
766 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
767 // Correct fix would be to move the prepending elsewhere.
768 if ($wgRequest->getVal('action') != 'render') {
769 $url = $wgServer . $url;
771 } else {
772 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
774 $namespace = wfUrlencode( $this->getNsText() );
775 if ( '' != $namespace ) {
776 # Can this actually happen? Interwikis shouldn't be parsed.
777 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
778 $namespace .= ':';
780 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
781 $url = wfAppendQuery( $url, $query );
784 # Finally, add the fragment.
785 $url .= $this->getFragmentForURL();
787 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
788 return $url;
792 * Get a URL with no fragment or server name. If this page is generated
793 * with action=render, $wgServer is prepended.
794 * @param string $query an optional query string; if not specified,
795 * $wgArticlePath will be used.
796 * @param string $variant language variant of url (for sr, zh..)
797 * @return string the URL
799 public function getLocalURL( $query = '', $variant = false ) {
800 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
801 global $wgVariantArticlePath, $wgContLang, $wgUser;
803 // internal links should point to same variant as current page (only anonymous users)
804 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
805 $pref = $wgContLang->getPreferredVariant(false);
806 if($pref != $wgContLang->getCode())
807 $variant = $pref;
810 if ( $this->isExternal() ) {
811 $url = $this->getFullURL();
812 if ( $query ) {
813 // This is currently only used for edit section links in the
814 // context of interwiki transclusion. In theory we should
815 // append the query to the end of any existing query string,
816 // but interwiki transclusion is already broken in that case.
817 $url .= "?$query";
819 } else {
820 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
821 if ( $query == '' ) {
822 if( $variant != false && $wgContLang->hasVariants() ) {
823 if( $wgVariantArticlePath == false ) {
824 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
825 } else {
826 $variantArticlePath = $wgVariantArticlePath;
828 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
829 $url = str_replace( '$1', $dbkey, $url );
830 } else {
831 $url = str_replace( '$1', $dbkey, $wgArticlePath );
833 } else {
834 global $wgActionPaths;
835 $url = false;
836 $matches = array();
837 if( !empty( $wgActionPaths ) &&
838 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
840 $action = urldecode( $matches[2] );
841 if( isset( $wgActionPaths[$action] ) ) {
842 $query = $matches[1];
843 if( isset( $matches[4] ) ) $query .= $matches[4];
844 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
845 if( $query != '' ) $url .= '?' . $query;
848 if ( $url === false ) {
849 if ( $query == '-' ) {
850 $query = '';
852 $url = "{$wgScript}?title={$dbkey}&{$query}";
856 // FIXME: this causes breakage in various places when we
857 // actually expected a local URL and end up with dupe prefixes.
858 if ($wgRequest->getVal('action') == 'render') {
859 $url = $wgServer . $url;
862 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
863 return $url;
867 * Get an HTML-escaped version of the URL form, suitable for
868 * using in a link, without a server name or fragment
869 * @param string $query an optional query string
870 * @return string the URL
872 public function escapeLocalURL( $query = '' ) {
873 return htmlspecialchars( $this->getLocalURL( $query ) );
877 * Get an HTML-escaped version of the URL form, suitable for
878 * using in a link, including the server name and fragment
880 * @return string the URL
881 * @param string $query an optional query string
883 public function escapeFullURL( $query = '' ) {
884 return htmlspecialchars( $this->getFullURL( $query ) );
888 * Get the URL form for an internal link.
889 * - Used in various Squid-related code, in case we have a different
890 * internal hostname for the server from the exposed one.
892 * @param string $query an optional query string
893 * @param string $variant language variant of url (for sr, zh..)
894 * @return string the URL
896 public function getInternalURL( $query = '', $variant = false ) {
897 global $wgInternalServer;
898 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
899 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
900 return $url;
904 * Get the edit URL for this Title
905 * @return string the URL, or a null string if this is an
906 * interwiki link
908 public function getEditURL() {
909 if ( '' != $this->mInterwiki ) { return ''; }
910 $s = $this->getLocalURL( 'action=edit' );
912 return $s;
916 * Get the HTML-escaped displayable text form.
917 * Used for the title field in <a> tags.
918 * @return string the text, including any prefixes
920 public function getEscapedText() {
921 return htmlspecialchars( $this->getPrefixedText() );
925 * Is this Title interwiki?
926 * @return boolean
928 public function isExternal() { return ( '' != $this->mInterwiki ); }
931 * Is this page "semi-protected" - the *only* protection is autoconfirm?
933 * @param string Action to check (default: edit)
934 * @return bool
936 public function isSemiProtected( $action = 'edit' ) {
937 if( $this->exists() ) {
938 $restrictions = $this->getRestrictions( $action );
939 if( count( $restrictions ) > 0 ) {
940 foreach( $restrictions as $restriction ) {
941 if( strtolower( $restriction ) != 'autoconfirmed' )
942 return false;
944 } else {
945 # Not protected
946 return false;
948 return true;
949 } else {
950 # If it doesn't exist, it can't be protected
951 return false;
956 * Does the title correspond to a protected article?
957 * @param string $what the action the page is protected from,
958 * by default checks move and edit
959 * @return boolean
961 public function isProtected( $action = '' ) {
962 global $wgRestrictionLevels, $wgRestrictionTypes;
964 # Special pages have inherent protection
965 if( $this->getNamespace() == NS_SPECIAL )
966 return true;
968 # Check regular protection levels
969 foreach( $wgRestrictionTypes as $type ){
970 if( $action == $type || $action == '' ) {
971 $r = $this->getRestrictions( $type );
972 foreach( $wgRestrictionLevels as $level ) {
973 if( in_array( $level, $r ) && $level != '' ) {
974 return true;
980 return false;
984 * Is $wgUser watching this page?
985 * @return boolean
987 public function userIsWatching() {
988 global $wgUser;
990 if ( is_null( $this->mWatched ) ) {
991 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
992 $this->mWatched = false;
993 } else {
994 $this->mWatched = $wgUser->isWatched( $this );
997 return $this->mWatched;
1001 * Can $wgUser perform $action on this page?
1002 * This skips potentially expensive cascading permission checks.
1004 * Suitable for use for nonessential UI controls in common cases, but
1005 * _not_ for functional access control.
1007 * May provide false positives, but should never provide a false negative.
1009 * @param string $action action that permission needs to be checked for
1010 * @return boolean
1012 public function quickUserCan( $action ) {
1013 return $this->userCan( $action, false );
1017 * Determines if $wgUser is unable to edit this page because it has been protected
1018 * by $wgNamespaceProtection.
1020 * @return boolean
1022 public function isNamespaceProtected() {
1023 global $wgNamespaceProtection, $wgUser;
1024 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
1025 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
1026 if( $right != '' && !$wgUser->isAllowed( $right ) )
1027 return true;
1030 return false;
1034 * Can $wgUser perform $action on this page?
1035 * @param string $action action that permission needs to be checked for
1036 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1037 * @return boolean
1039 public function userCan( $action, $doExpensiveQueries = true ) {
1040 global $wgUser;
1041 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1045 * Can $user perform $action on this page?
1047 * FIXME: This *does not* check throttles (User::pingLimiter()).
1049 * @param string $action action that permission needs to be checked for
1050 * @param User $user user to check
1051 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1052 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1053 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1055 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1056 if( !StubObject::isRealObject( $user ) ) {
1057 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1058 global $wgUser;
1059 $wgUser->_unstub( '', 5 );
1060 $user = $wgUser;
1062 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1064 global $wgContLang;
1065 global $wgLang;
1066 global $wgEmailConfirmToEdit;
1068 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1069 $errors[] = array( 'confirmedittext' );
1072 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1073 $block = $user->mBlock;
1075 // This is from OutputPage::blockedPage
1076 // Copied at r23888 by werdna
1078 $id = $user->blockedBy();
1079 $reason = $user->blockedFor();
1080 if( $reason == '' ) {
1081 $reason = wfMsg( 'blockednoreason' );
1083 $ip = wfGetIP();
1085 if ( is_numeric( $id ) ) {
1086 $name = User::whoIs( $id );
1087 } else {
1088 $name = $id;
1091 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1092 $blockid = $block->mId;
1093 $blockExpiry = $user->mBlock->mExpiry;
1094 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1096 if ( $blockExpiry == 'infinity' ) {
1097 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1098 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1100 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1101 if ( strpos( $option, ':' ) == false )
1102 continue;
1104 list ($show, $value) = explode( ":", $option );
1106 if ( $value == 'infinite' || $value == 'indefinite' ) {
1107 $blockExpiry = $show;
1108 break;
1111 } else {
1112 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1115 $intended = $user->mBlock->mAddress;
1117 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1118 $blockid, $blockExpiry, $intended, $blockTimestamp );
1121 // Remove the errors being ignored.
1123 foreach( $errors as $index => $error ) {
1124 $error_key = is_array($error) ? $error[0] : $error;
1126 if (in_array( $error_key, $ignoreErrors )) {
1127 unset($errors[$index]);
1131 return $errors;
1135 * Can $user perform $action on this page? This is an internal function,
1136 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1137 * checks on wfReadOnly() and blocks)
1139 * @param string $action action that permission needs to be checked for
1140 * @param User $user user to check
1141 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1142 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1144 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1145 wfProfileIn( __METHOD__ );
1147 $errors = array();
1149 // Use getUserPermissionsErrors instead
1150 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1151 wfProfileOut( __METHOD__ );
1152 return $result ? array() : array( array( 'badaccess-group0' ) );
1155 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1156 if ($result != array() && is_array($result) && !is_array($result[0]))
1157 $errors[] = $result; # A single array representing an error
1158 else if (is_array($result) && is_array($result[0]))
1159 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1160 else if ($result != '' && $result != null && $result !== true && $result !== false)
1161 $errors[] = array($result); # A string representing a message-id
1162 else if ($result === false )
1163 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1165 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1166 if ($result != array() && is_array($result) && !is_array($result[0]))
1167 $errors[] = $result; # A single array representing an error
1168 else if (is_array($result) && is_array($result[0]))
1169 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1170 else if ($result != '' && $result != null && $result !== true && $result !== false)
1171 $errors[] = array($result); # A string representing a message-id
1172 else if ($result === false )
1173 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1176 $specialOKActions = array( 'createaccount', 'execute' );
1177 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1178 $errors[] = array('ns-specialprotected');
1181 if ( $this->isNamespaceProtected() ) {
1182 $ns = $this->getNamespace() == NS_MAIN
1183 ? wfMsg( 'nstab-main' )
1184 : $this->getNsText();
1185 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1186 ? array('protectedinterface')
1187 : array( 'namespaceprotected', $ns ) );
1190 if( $this->mDbkeyform == '_' ) {
1191 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1192 $errors[] = array('badaccess-group0');
1195 # protect css/js subpages of user pages
1196 # XXX: this might be better using restrictions
1197 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1198 if( $this->isCssJsSubpage()
1199 && !$user->isAllowed('editusercssjs')
1200 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1201 $errors[] = array('customcssjsprotected');
1204 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1205 # We /could/ use the protection level on the source page, but it's fairly ugly
1206 # as we have to establish a precedence hierarchy for pages included by multiple
1207 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1208 # as they could remove the protection anyway.
1209 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1210 # Cascading protection depends on more than this page...
1211 # Several cascading protected pages may include this page...
1212 # Check each cascading level
1213 # This is only for protection restrictions, not for all actions
1214 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1215 foreach( $restrictions[$action] as $right ) {
1216 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1217 if( '' != $right && !$user->isAllowed( $right ) ) {
1218 $pages = '';
1219 foreach( $cascadingSources as $page )
1220 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1221 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1227 foreach( $this->getRestrictions($action) as $right ) {
1228 // Backwards compatibility, rewrite sysop -> protect
1229 if ( $right == 'sysop' ) {
1230 $right = 'protect';
1232 if( '' != $right && !$user->isAllowed( $right ) ) {
1233 //Users with 'editprotected' permission can edit protected pages
1234 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1235 //Users with 'editprotected' permission cannot edit protected pages
1236 //with cascading option turned on.
1237 if($this->mCascadeRestriction) {
1238 $errors[] = array( 'protectedpagetext', $right );
1239 } else {
1240 //Nothing, user can edit!
1242 } else {
1243 $errors[] = array( 'protectedpagetext', $right );
1248 if ($action == 'protect') {
1249 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1250 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1254 if ($action == 'create') {
1255 $title_protection = $this->getTitleProtection();
1257 if (is_array($title_protection)) {
1258 extract($title_protection);
1260 if ($pt_create_perm == 'sysop')
1261 $pt_create_perm = 'protect';
1263 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1264 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1268 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1269 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1270 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1272 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1273 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1274 } elseif ( !$user->isAllowed( $action ) ) {
1275 $return = null;
1276 $groups = array();
1277 global $wgGroupPermissions;
1278 foreach( $wgGroupPermissions as $key => $value ) {
1279 if( isset( $value[$action] ) && $value[$action] == true ) {
1280 $groupName = User::getGroupName( $key );
1281 $groupPage = User::getGroupPage( $key );
1282 if( $groupPage ) {
1283 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1284 } else {
1285 $groups[] = $groupName;
1289 $n = count( $groups );
1290 $groups = implode( ', ', $groups );
1291 switch( $n ) {
1292 case 0:
1293 case 1:
1294 case 2:
1295 $return = array( "badaccess-group$n", $groups );
1296 break;
1297 default:
1298 $return = array( 'badaccess-groups', $groups );
1300 $errors[] = $return;
1303 wfProfileOut( __METHOD__ );
1304 return $errors;
1308 * Is this title subject to title protection?
1309 * @return mixed An associative array representing any existent title
1310 * protection, or false if there's none.
1312 private function getTitleProtection() {
1313 // Can't protect pages in special namespaces
1314 if ( $this->getNamespace() < 0 ) {
1315 return false;
1318 $dbr = wfGetDB( DB_SLAVE );
1319 $res = $dbr->select( 'protected_titles', '*',
1320 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1322 if ($row = $dbr->fetchRow( $res )) {
1323 return $row;
1324 } else {
1325 return false;
1329 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1330 global $wgGroupPermissions,$wgUser,$wgContLang;
1332 if ($create_perm == implode(',',$this->getRestrictions('create'))
1333 && $expiry == $this->mRestrictionsExpiry) {
1334 // No change
1335 return true;
1338 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1340 $dbw = wfGetDB( DB_MASTER );
1342 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1344 $expiry_description = '';
1345 if ( $encodedExpiry != 'infinity' ) {
1346 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1349 # Update protection table
1350 if ($create_perm != '' ) {
1351 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1352 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1353 , 'pt_create_perm' => $create_perm
1354 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1355 , 'pt_expiry' => $encodedExpiry
1356 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1357 } else {
1358 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1359 'pt_title' => $title ), __METHOD__ );
1361 # Update the protection log
1362 $log = new LogPage( 'protect' );
1364 if( $create_perm ) {
1365 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1366 } else {
1367 $log->addEntry( 'unprotect', $this, $reason );
1370 return true;
1374 * Remove any title protection (due to page existing
1376 public function deleteTitleProtection() {
1377 $dbw = wfGetDB( DB_MASTER );
1379 $dbw->delete( 'protected_titles',
1380 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1384 * Can $wgUser edit this page?
1385 * @return boolean
1386 * @deprecated use userCan('edit')
1388 public function userCanEdit( $doExpensiveQueries = true ) {
1389 return $this->userCan( 'edit', $doExpensiveQueries );
1393 * Can $wgUser create this page?
1394 * @return boolean
1395 * @deprecated use userCan('create')
1397 public function userCanCreate( $doExpensiveQueries = true ) {
1398 return $this->userCan( 'create', $doExpensiveQueries );
1402 * Can $wgUser move this page?
1403 * @return boolean
1404 * @deprecated use userCan('move')
1406 public function userCanMove( $doExpensiveQueries = true ) {
1407 return $this->userCan( 'move', $doExpensiveQueries );
1411 * Would anybody with sufficient privileges be able to move this page?
1412 * Some pages just aren't movable.
1414 * @return boolean
1416 public function isMovable() {
1417 return MWNamespace::isMovable( $this->getNamespace() )
1418 && $this->getInterwiki() == '';
1422 * Can $wgUser read this page?
1423 * @return boolean
1424 * @todo fold these checks into userCan()
1426 public function userCanRead() {
1427 global $wgUser, $wgGroupPermissions;
1429 $result = null;
1430 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1431 if ( $result !== null ) {
1432 return $result;
1435 # Shortcut for public wikis, allows skipping quite a bit of code
1436 if ($wgGroupPermissions['*']['read'])
1437 return true;
1439 if( $wgUser->isAllowed( 'read' ) ) {
1440 return true;
1441 } else {
1442 global $wgWhitelistRead;
1445 * Always grant access to the login page.
1446 * Even anons need to be able to log in.
1448 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1449 return true;
1453 * Bail out if there isn't whitelist
1455 if( !is_array($wgWhitelistRead) ) {
1456 return false;
1460 * Check for explicit whitelisting
1462 $name = $this->getPrefixedText();
1463 $dbName = $this->getPrefixedDBKey();
1464 // Check with and without underscores
1465 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1466 return true;
1469 * Old settings might have the title prefixed with
1470 * a colon for main-namespace pages
1472 if( $this->getNamespace() == NS_MAIN ) {
1473 if( in_array( ':' . $name, $wgWhitelistRead ) )
1474 return true;
1478 * If it's a special page, ditch the subpage bit
1479 * and check again
1481 if( $this->getNamespace() == NS_SPECIAL ) {
1482 $name = $this->getDBkey();
1483 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1484 if ( $name === false ) {
1485 # Invalid special page, but we show standard login required message
1486 return false;
1489 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1490 if( in_array( $pure, $wgWhitelistRead, true ) )
1491 return true;
1495 return false;
1499 * Is this a talk page of some sort?
1500 * @return bool
1502 public function isTalkPage() {
1503 return MWNamespace::isTalk( $this->getNamespace() );
1507 * Is this a subpage?
1508 * @return bool
1510 public function isSubpage() {
1511 return MWNamespace::hasSubpages( $this->mNamespace )
1512 ? strpos( $this->getText(), '/' ) !== false
1513 : false;
1517 * Does this have subpages? (Warning, usually requires an extra DB query.)
1518 * @return bool
1520 public function hasSubpages() {
1521 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1522 # Duh
1523 return false;
1526 # We dynamically add a member variable for the purpose of this method
1527 # alone to cache the result. There's no point in having it hanging
1528 # around uninitialized in every Title object; therefore we only add it
1529 # if needed and don't declare it statically.
1530 if( isset( $this->mHasSubpages ) ) {
1531 return $this->mHasSubpages;
1534 $db = wfGetDB( DB_SLAVE );
1535 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1536 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1537 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1538 __METHOD__
1543 * Could this page contain custom CSS or JavaScript, based
1544 * on the title?
1546 * @return bool
1548 public function isCssOrJsPage() {
1549 return $this->mNamespace == NS_MEDIAWIKI
1550 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1554 * Is this a .css or .js subpage of a user page?
1555 * @return bool
1557 public function isCssJsSubpage() {
1558 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1561 * Is this a *valid* .css or .js subpage of a user page?
1562 * Check that the corresponding skin exists
1564 public function isValidCssJsSubpage() {
1565 if ( $this->isCssJsSubpage() ) {
1566 $skinNames = Skin::getSkinNames();
1567 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1568 } else {
1569 return false;
1573 * Trim down a .css or .js subpage title to get the corresponding skin name
1575 public function getSkinFromCssJsSubpage() {
1576 $subpage = explode( '/', $this->mTextform );
1577 $subpage = $subpage[ count( $subpage ) - 1 ];
1578 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1581 * Is this a .css subpage of a user page?
1582 * @return bool
1584 public function isCssSubpage() {
1585 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1588 * Is this a .js subpage of a user page?
1589 * @return bool
1591 public function isJsSubpage() {
1592 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1595 * Protect css/js subpages of user pages: can $wgUser edit
1596 * this page?
1598 * @return boolean
1599 * @todo XXX: this might be better using restrictions
1601 public function userCanEditCssJsSubpage() {
1602 global $wgUser;
1603 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1607 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1609 * @return bool If the page is subject to cascading restrictions.
1611 public function isCascadeProtected() {
1612 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1613 return ( $sources > 0 );
1617 * Cascading protection: Get the source of any cascading restrictions on this page.
1619 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1620 * @return array( mixed title array, restriction array)
1621 * 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.
1622 * The restriction array is an array of each type, each of which contains an array of unique groups
1624 public function getCascadeProtectionSources( $get_pages = true ) {
1625 global $wgRestrictionTypes;
1627 # Define our dimension of restrictions types
1628 $pagerestrictions = array();
1629 foreach( $wgRestrictionTypes as $action )
1630 $pagerestrictions[$action] = array();
1632 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1633 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1634 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1635 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1638 wfProfileIn( __METHOD__ );
1640 $dbr = wfGetDb( DB_SLAVE );
1642 if ( $this->getNamespace() == NS_IMAGE ) {
1643 $tables = array ('imagelinks', 'page_restrictions');
1644 $where_clauses = array(
1645 'il_to' => $this->getDBkey(),
1646 'il_from=pr_page',
1647 'pr_cascade' => 1 );
1648 } else {
1649 $tables = array ('templatelinks', 'page_restrictions');
1650 $where_clauses = array(
1651 'tl_namespace' => $this->getNamespace(),
1652 'tl_title' => $this->getDBkey(),
1653 'tl_from=pr_page',
1654 'pr_cascade' => 1 );
1657 if ( $get_pages ) {
1658 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1659 $where_clauses[] = 'page_id=pr_page';
1660 $tables[] = 'page';
1661 } else {
1662 $cols = array( 'pr_expiry' );
1665 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1667 $sources = $get_pages ? array() : false;
1668 $now = wfTimestampNow();
1669 $purgeExpired = false;
1671 while( $row = $dbr->fetchObject( $res ) ) {
1672 $expiry = Block::decodeExpiry( $row->pr_expiry );
1673 if( $expiry > $now ) {
1674 if ($get_pages) {
1675 $page_id = $row->pr_page;
1676 $page_ns = $row->page_namespace;
1677 $page_title = $row->page_title;
1678 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1679 # Add groups needed for each restriction type if its not already there
1680 # Make sure this restriction type still exists
1681 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1682 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1684 } else {
1685 $sources = true;
1687 } else {
1688 // Trigger lazy purge of expired restrictions from the db
1689 $purgeExpired = true;
1692 if( $purgeExpired ) {
1693 Title::purgeExpiredRestrictions();
1696 wfProfileOut( __METHOD__ );
1698 if ( $get_pages ) {
1699 $this->mCascadeSources = $sources;
1700 $this->mCascadingRestrictions = $pagerestrictions;
1701 } else {
1702 $this->mHasCascadingRestrictions = $sources;
1705 return array( $sources, $pagerestrictions );
1708 function areRestrictionsCascading() {
1709 if (!$this->mRestrictionsLoaded) {
1710 $this->loadRestrictions();
1713 return $this->mCascadeRestriction;
1717 * Loads a string into mRestrictions array
1718 * @param resource $res restrictions as an SQL result.
1720 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1721 global $wgRestrictionTypes;
1722 $dbr = wfGetDB( DB_SLAVE );
1724 foreach( $wgRestrictionTypes as $type ){
1725 $this->mRestrictions[$type] = array();
1728 $this->mCascadeRestriction = false;
1729 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1731 # Backwards-compatibility: also load the restrictions from the page record (old format).
1733 if ( $oldFashionedRestrictions === NULL ) {
1734 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1735 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1738 if ($oldFashionedRestrictions != '') {
1740 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1741 $temp = explode( '=', trim( $restrict ) );
1742 if(count($temp) == 1) {
1743 // old old format should be treated as edit/move restriction
1744 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1745 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1746 } else {
1747 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1751 $this->mOldRestrictions = true;
1755 if( $dbr->numRows( $res ) ) {
1756 # Current system - load second to make them override.
1757 $now = wfTimestampNow();
1758 $purgeExpired = false;
1760 while ($row = $dbr->fetchObject( $res ) ) {
1761 # Cycle through all the restrictions.
1763 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1764 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1765 continue;
1767 // This code should be refactored, now that it's being used more generally,
1768 // But I don't really see any harm in leaving it in Block for now -werdna
1769 $expiry = Block::decodeExpiry( $row->pr_expiry );
1771 // Only apply the restrictions if they haven't expired!
1772 if ( !$expiry || $expiry > $now ) {
1773 $this->mRestrictionsExpiry = $expiry;
1774 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1776 $this->mCascadeRestriction |= $row->pr_cascade;
1777 } else {
1778 // Trigger a lazy purge of expired restrictions
1779 $purgeExpired = true;
1783 if( $purgeExpired ) {
1784 Title::purgeExpiredRestrictions();
1788 $this->mRestrictionsLoaded = true;
1791 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1792 if( !$this->mRestrictionsLoaded ) {
1793 if ($this->exists()) {
1794 $dbr = wfGetDB( DB_SLAVE );
1796 $res = $dbr->select( 'page_restrictions', '*',
1797 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1799 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1800 } else {
1801 $title_protection = $this->getTitleProtection();
1803 if (is_array($title_protection)) {
1804 extract($title_protection);
1806 $now = wfTimestampNow();
1807 $expiry = Block::decodeExpiry($pt_expiry);
1809 if (!$expiry || $expiry > $now) {
1810 // Apply the restrictions
1811 $this->mRestrictionsExpiry = $expiry;
1812 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1813 } else { // Get rid of the old restrictions
1814 Title::purgeExpiredRestrictions();
1816 } else {
1817 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1819 $this->mRestrictionsLoaded = true;
1825 * Purge expired restrictions from the page_restrictions table
1827 static function purgeExpiredRestrictions() {
1828 $dbw = wfGetDB( DB_MASTER );
1829 $dbw->delete( 'page_restrictions',
1830 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1831 __METHOD__ );
1833 $dbw->delete( 'protected_titles',
1834 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1835 __METHOD__ );
1839 * Accessor/initialisation for mRestrictions
1841 * @param string $action action that permission needs to be checked for
1842 * @return array the array of groups allowed to edit this article
1844 public function getRestrictions( $action ) {
1845 if( !$this->mRestrictionsLoaded ) {
1846 $this->loadRestrictions();
1848 return isset( $this->mRestrictions[$action] )
1849 ? $this->mRestrictions[$action]
1850 : array();
1854 * Is there a version of this page in the deletion archive?
1855 * @return int the number of archived revisions
1857 public function isDeleted() {
1858 $fname = 'Title::isDeleted';
1859 if ( $this->getNamespace() < 0 ) {
1860 $n = 0;
1861 } else {
1862 $dbr = wfGetDB( DB_SLAVE );
1863 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1864 'ar_title' => $this->getDBkey() ), $fname );
1865 if( $this->getNamespace() == NS_IMAGE ) {
1866 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1867 array( 'fa_name' => $this->getDBkey() ), $fname );
1870 return (int)$n;
1874 * Get the article ID for this Title from the link cache,
1875 * adding it if necessary
1876 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1877 * for update
1878 * @return int the ID
1880 public function getArticleID( $flags = 0 ) {
1881 $linkCache = LinkCache::singleton();
1882 if ( $flags & GAID_FOR_UPDATE ) {
1883 $oldUpdate = $linkCache->forUpdate( true );
1884 $this->mArticleID = $linkCache->addLinkObj( $this );
1885 $linkCache->forUpdate( $oldUpdate );
1886 } else {
1887 if ( -1 == $this->mArticleID ) {
1888 $this->mArticleID = $linkCache->addLinkObj( $this );
1891 return $this->mArticleID;
1895 * Is this an article that is a redirect page?
1896 * Uses link cache, adding it if necessary
1897 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1898 * @return bool
1900 public function isRedirect( $flags = 0 ) {
1901 if( !is_null($this->mRedirect) )
1902 return $this->mRedirect;
1903 # Zero for special pages.
1904 # Also, calling getArticleID() loads the field from cache!
1905 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1906 return false;
1908 $linkCache = LinkCache::singleton();
1909 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1911 return $this->mRedirect;
1915 * What is the length of this page?
1916 * Uses link cache, adding it if necessary
1917 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1918 * @return bool
1920 public function getLength( $flags = 0 ) {
1921 if( $this->mLength != -1 )
1922 return $this->mLength;
1923 # Zero for special pages.
1924 # Also, calling getArticleID() loads the field from cache!
1925 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1926 return 0;
1928 $linkCache = LinkCache::singleton();
1929 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1931 return $this->mLength;
1935 * What is the page_latest field for this page?
1936 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1937 * @return int
1939 public function getLatestRevID( $flags = 0 ) {
1940 if ($this->mLatestID !== false)
1941 return $this->mLatestID;
1943 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1944 return $this->mLatestID = $db->selectField( 'revision',
1945 "max(rev_id)",
1946 array('rev_page' => $this->getArticleID($flags)),
1947 'Title::getLatestRevID' );
1951 * This clears some fields in this object, and clears any associated
1952 * keys in the "bad links" section of the link cache.
1954 * - This is called from Article::insertNewArticle() to allow
1955 * loading of the new page_id. It's also called from
1956 * Article::doDeleteArticle()
1958 * @param int $newid the new Article ID
1960 public function resetArticleID( $newid ) {
1961 $linkCache = LinkCache::singleton();
1962 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1964 if ( 0 == $newid ) { $this->mArticleID = -1; }
1965 else { $this->mArticleID = $newid; }
1966 $this->mRestrictionsLoaded = false;
1967 $this->mRestrictions = array();
1971 * Updates page_touched for this page; called from LinksUpdate.php
1972 * @return bool true if the update succeded
1974 public function invalidateCache() {
1975 global $wgUseFileCache;
1977 if ( wfReadOnly() ) {
1978 return;
1981 $dbw = wfGetDB( DB_MASTER );
1982 $success = $dbw->update( 'page',
1983 array( /* SET */
1984 'page_touched' => $dbw->timestamp()
1985 ), array( /* WHERE */
1986 'page_namespace' => $this->getNamespace() ,
1987 'page_title' => $this->getDBkey()
1988 ), 'Title::invalidateCache'
1991 if ($wgUseFileCache) {
1992 $cache = new HTMLFileCache($this);
1993 @unlink($cache->fileCacheName());
1996 return $success;
2000 * Prefix some arbitrary text with the namespace or interwiki prefix
2001 * of this object
2003 * @param string $name the text
2004 * @return string the prefixed text
2005 * @private
2007 /* private */ function prefix( $name ) {
2008 $p = '';
2009 if ( '' != $this->mInterwiki ) {
2010 $p = $this->mInterwiki . ':';
2012 if ( 0 != $this->mNamespace ) {
2013 $p .= $this->getNsText() . ':';
2015 return $p . $name;
2019 * Secure and split - main initialisation function for this object
2021 * Assumes that mDbkeyform has been set, and is urldecoded
2022 * and uses underscores, but not otherwise munged. This function
2023 * removes illegal characters, splits off the interwiki and
2024 * namespace prefixes, sets the other forms, and canonicalizes
2025 * everything.
2026 * @return bool true on success
2028 private function secureAndSplit() {
2029 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2031 # Initialisation
2032 static $rxTc = false;
2033 if( !$rxTc ) {
2034 # Matching titles will be held as illegal.
2035 $rxTc = '/' .
2036 # Any character not allowed is forbidden...
2037 '[^' . Title::legalChars() . ']' .
2038 # URL percent encoding sequences interfere with the ability
2039 # to round-trip titles -- you can't link to them consistently.
2040 '|%[0-9A-Fa-f]{2}' .
2041 # XML/HTML character references produce similar issues.
2042 '|&[A-Za-z0-9\x80-\xff]+;' .
2043 '|&#[0-9]+;' .
2044 '|&#x[0-9A-Fa-f]+;' .
2045 '/S';
2048 $this->mInterwiki = $this->mFragment = '';
2049 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2051 $dbkey = $this->mDbkeyform;
2053 # Strip Unicode bidi override characters.
2054 # Sometimes they slip into cut-n-pasted page titles, where the
2055 # override chars get included in list displays.
2056 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2057 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2059 # Clean up whitespace
2061 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2062 $dbkey = trim( $dbkey, '_' );
2064 if ( '' == $dbkey ) {
2065 return false;
2068 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2069 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2070 return false;
2073 $this->mDbkeyform = $dbkey;
2075 # Initial colon indicates main namespace rather than specified default
2076 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2077 if ( ':' == $dbkey{0} ) {
2078 $this->mNamespace = NS_MAIN;
2079 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2080 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2083 # Namespace or interwiki prefix
2084 $firstPass = true;
2085 do {
2086 $m = array();
2087 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2088 $p = $m[1];
2089 if ( $ns = $wgContLang->getNsIndex( $p )) {
2090 # Ordinary namespace
2091 $dbkey = $m[2];
2092 $this->mNamespace = $ns;
2093 } elseif( $this->getInterwikiLink( $p ) ) {
2094 if( !$firstPass ) {
2095 # Can't make a local interwiki link to an interwiki link.
2096 # That's just crazy!
2097 return false;
2100 # Interwiki link
2101 $dbkey = $m[2];
2102 $this->mInterwiki = $wgContLang->lc( $p );
2104 # Redundant interwiki prefix to the local wiki
2105 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2106 if( $dbkey == '' ) {
2107 # Can't have an empty self-link
2108 return false;
2110 $this->mInterwiki = '';
2111 $firstPass = false;
2112 # Do another namespace split...
2113 continue;
2116 # If there's an initial colon after the interwiki, that also
2117 # resets the default namespace
2118 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2119 $this->mNamespace = NS_MAIN;
2120 $dbkey = substr( $dbkey, 1 );
2123 # If there's no recognized interwiki or namespace,
2124 # then let the colon expression be part of the title.
2126 break;
2127 } while( true );
2129 # We already know that some pages won't be in the database!
2131 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2132 $this->mArticleID = 0;
2134 $fragment = strstr( $dbkey, '#' );
2135 if ( false !== $fragment ) {
2136 $this->setFragment( $fragment );
2137 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2138 # remove whitespace again: prevents "Foo_bar_#"
2139 # becoming "Foo_bar_"
2140 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2143 # Reject illegal characters.
2145 if( preg_match( $rxTc, $dbkey ) ) {
2146 return false;
2150 * Pages with "/./" or "/../" appearing in the URLs will
2151 * often be unreachable due to the way web browsers deal
2152 * with 'relative' URLs. Forbid them explicitly.
2154 if ( strpos( $dbkey, '.' ) !== false &&
2155 ( $dbkey === '.' || $dbkey === '..' ||
2156 strpos( $dbkey, './' ) === 0 ||
2157 strpos( $dbkey, '../' ) === 0 ||
2158 strpos( $dbkey, '/./' ) !== false ||
2159 strpos( $dbkey, '/../' ) !== false ||
2160 substr( $dbkey, -2 ) == '/.' ||
2161 substr( $dbkey, -3 ) == '/..' ) )
2163 return false;
2167 * Magic tilde sequences? Nu-uh!
2169 if( strpos( $dbkey, '~~~' ) !== false ) {
2170 return false;
2174 * Limit the size of titles to 255 bytes.
2175 * This is typically the size of the underlying database field.
2176 * We make an exception for special pages, which don't need to be stored
2177 * in the database, and may edge over 255 bytes due to subpage syntax
2178 * for long titles, e.g. [[Special:Block/Long name]]
2180 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2181 strlen( $dbkey ) > 512 )
2183 return false;
2187 * Normally, all wiki links are forced to have
2188 * an initial capital letter so [[foo]] and [[Foo]]
2189 * point to the same place.
2191 * Don't force it for interwikis, since the other
2192 * site might be case-sensitive.
2194 $this->mUserCaseDBKey = $dbkey;
2195 if( $wgCapitalLinks && $this->mInterwiki == '') {
2196 $dbkey = $wgContLang->ucfirst( $dbkey );
2200 * Can't make a link to a namespace alone...
2201 * "empty" local links can only be self-links
2202 * with a fragment identifier.
2204 if( $dbkey == '' &&
2205 $this->mInterwiki == '' &&
2206 $this->mNamespace != NS_MAIN ) {
2207 return false;
2209 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2210 // IP names are not allowed for accounts, and can only be referring to
2211 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2212 // there are numerous ways to present the same IP. Having sp:contribs scan
2213 // them all is silly and having some show the edits and others not is
2214 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2215 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2216 IP::sanitizeIP( $dbkey ) : $dbkey;
2217 // Any remaining initial :s are illegal.
2218 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2219 return false;
2222 # Fill fields
2223 $this->mDbkeyform = $dbkey;
2224 $this->mUrlform = wfUrlencode( $dbkey );
2226 $this->mTextform = str_replace( '_', ' ', $dbkey );
2228 return true;
2232 * Set the fragment for this title
2233 * This is kind of bad, since except for this rarely-used function, Title objects
2234 * are immutable. The reason this is here is because it's better than setting the
2235 * members directly, which is what Linker::formatComment was doing previously.
2237 * @param string $fragment text
2238 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2240 public function setFragment( $fragment ) {
2241 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2245 * Get a Title object associated with the talk page of this article
2246 * @return Title the object for the talk page
2248 public function getTalkPage() {
2249 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2253 * Get a title object associated with the subject page of this
2254 * talk page
2256 * @return Title the object for the subject page
2258 public function getSubjectPage() {
2259 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2263 * Get an array of Title objects linking to this Title
2264 * Also stores the IDs in the link cache.
2266 * WARNING: do not use this function on arbitrary user-supplied titles!
2267 * On heavily-used templates it will max out the memory.
2269 * @param string $options may be FOR UPDATE
2270 * @return array the Title objects linking here
2272 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2273 $linkCache = LinkCache::singleton();
2275 if ( $options ) {
2276 $db = wfGetDB( DB_MASTER );
2277 } else {
2278 $db = wfGetDB( DB_SLAVE );
2281 $res = $db->select( array( 'page', $table ),
2282 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2283 array(
2284 "{$prefix}_from=page_id",
2285 "{$prefix}_namespace" => $this->getNamespace(),
2286 "{$prefix}_title" => $this->getDBkey() ),
2287 'Title::getLinksTo',
2288 $options );
2290 $retVal = array();
2291 if ( $db->numRows( $res ) ) {
2292 while ( $row = $db->fetchObject( $res ) ) {
2293 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2294 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2295 $retVal[] = $titleObj;
2299 $db->freeResult( $res );
2300 return $retVal;
2304 * Get an array of Title objects using this Title as a template
2305 * Also stores the IDs in the link cache.
2307 * WARNING: do not use this function on arbitrary user-supplied titles!
2308 * On heavily-used templates it will max out the memory.
2310 * @param string $options may be FOR UPDATE
2311 * @return array the Title objects linking here
2313 public function getTemplateLinksTo( $options = '' ) {
2314 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2318 * Get an array of Title objects referring to non-existent articles linked from this page
2320 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2321 * @param string $options may be FOR UPDATE
2322 * @return array the Title objects
2324 public function getBrokenLinksFrom( $options = '' ) {
2325 if ( $this->getArticleId() == 0 ) {
2326 # All links from article ID 0 are false positives
2327 return array();
2330 if ( $options ) {
2331 $db = wfGetDB( DB_MASTER );
2332 } else {
2333 $db = wfGetDB( DB_SLAVE );
2336 $res = $db->safeQuery(
2337 "SELECT pl_namespace, pl_title
2338 FROM !
2339 LEFT JOIN !
2340 ON pl_namespace=page_namespace
2341 AND pl_title=page_title
2342 WHERE pl_from=?
2343 AND page_namespace IS NULL
2345 $db->tableName( 'pagelinks' ),
2346 $db->tableName( 'page' ),
2347 $this->getArticleId(),
2348 $options );
2350 $retVal = array();
2351 if ( $db->numRows( $res ) ) {
2352 while ( $row = $db->fetchObject( $res ) ) {
2353 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2356 $db->freeResult( $res );
2357 return $retVal;
2362 * Get a list of URLs to purge from the Squid cache when this
2363 * page changes
2365 * @return array the URLs
2367 public function getSquidURLs() {
2368 global $wgContLang;
2370 $urls = array(
2371 $this->getInternalURL(),
2372 $this->getInternalURL( 'action=history' )
2375 // purge variant urls as well
2376 if($wgContLang->hasVariants()){
2377 $variants = $wgContLang->getVariants();
2378 foreach($variants as $vCode){
2379 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2380 $urls[] = $this->getInternalURL('',$vCode);
2384 return $urls;
2387 public function purgeSquid() {
2388 global $wgUseSquid;
2389 if ( $wgUseSquid ) {
2390 $urls = $this->getSquidURLs();
2391 $u = new SquidUpdate( $urls );
2392 $u->doUpdate();
2397 * Move this page without authentication
2398 * @param Title &$nt the new page Title
2400 public function moveNoAuth( &$nt ) {
2401 return $this->moveTo( $nt, false );
2405 * Check whether a given move operation would be valid.
2406 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2407 * @param Title &$nt the new title
2408 * @param bool $auth indicates whether $wgUser's permissions
2409 * should be checked
2410 * @param string $reason is the log summary of the move, used for spam checking
2411 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2413 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2414 $errors = array();
2415 if( !$nt ) {
2416 // Normally we'd add this to $errors, but we'll get
2417 // lots of syntax errors if $nt is not an object
2418 return array(array('badtitletext'));
2420 if( $this->equals( $nt ) ) {
2421 $errors[] = array('selfmove');
2423 if( !$this->isMovable() || !$nt->isMovable() ) {
2424 $errors[] = array('immobile_namespace');
2427 $oldid = $this->getArticleID();
2428 $newid = $nt->getArticleID();
2430 if ( strlen( $nt->getDBkey() ) < 1 ) {
2431 $errors[] = array('articleexists');
2433 if ( ( '' == $this->getDBkey() ) ||
2434 ( !$oldid ) ||
2435 ( '' == $nt->getDBkey() ) ) {
2436 $errors[] = array('badarticleerror');
2439 // Image-specific checks
2440 if( $this->getNamespace() == NS_IMAGE ) {
2441 $file = wfLocalFile( $this );
2442 if( $file->exists() ) {
2443 if( $nt->getNamespace() != NS_IMAGE ) {
2444 $errors[] = array('imagenocrossnamespace');
2446 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2447 $errors[] = array('imageinvalidfilename');
2449 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2450 $errors[] = array('imagetypemismatch');
2455 if ( $auth ) {
2456 global $wgUser;
2457 $errors = array_merge($errors,
2458 $this->getUserPermissionsErrors('move', $wgUser),
2459 $this->getUserPermissionsErrors('edit', $wgUser),
2460 $nt->getUserPermissionsErrors('move', $wgUser),
2461 $nt->getUserPermissionsErrors('edit', $wgUser));
2464 global $wgUser;
2465 $err = null;
2466 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2467 $errors[] = array('hookaborted', $err);
2470 # The move is allowed only if (1) the target doesn't exist, or
2471 # (2) the target is a redirect to the source, and has no history
2472 # (so we can undo bad moves right after they're done).
2474 if ( 0 != $newid ) { # Target exists; check for validity
2475 if ( ! $this->isValidMoveTarget( $nt ) ) {
2476 $errors[] = array('articleexists');
2478 } else {
2479 $tp = $nt->getTitleProtection();
2480 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2481 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2482 $errors[] = array('cantmove-titleprotected');
2485 if(empty($errors))
2486 return true;
2487 return $errors;
2491 * Move a title to a new location
2492 * @param Title &$nt the new title
2493 * @param bool $auth indicates whether $wgUser's permissions
2494 * should be checked
2495 * @param string $reason The reason for the move
2496 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2497 * Ignored if the user doesn't have the suppressredirect right.
2498 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2500 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2501 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2502 if( is_array( $err ) ) {
2503 return $err;
2506 $pageid = $this->getArticleID();
2507 if( $nt->exists() ) {
2508 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2509 $pageCountChange = ($createRedirect ? 0 : -1);
2510 } else { # Target didn't exist, do normal move.
2511 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2512 $pageCountChange = ($createRedirect ? 1 : 0);
2515 if( is_array( $err ) ) {
2516 return $err;
2518 $redirid = $this->getArticleID();
2520 // Category memberships include a sort key which may be customized.
2521 // If it's left as the default (the page title), we need to update
2522 // the sort key to match the new title.
2524 // Be careful to avoid resetting cl_timestamp, which may disturb
2525 // time-based lists on some sites.
2527 // Warning -- if the sort key is *explicitly* set to the old title,
2528 // we can't actually distinguish it from a default here, and it'll
2529 // be set to the new title even though it really shouldn't.
2530 // It'll get corrected on the next edit, but resetting cl_timestamp.
2531 $dbw = wfGetDB( DB_MASTER );
2532 $dbw->update( 'categorylinks',
2533 array(
2534 'cl_sortkey' => $nt->getPrefixedText(),
2535 'cl_timestamp=cl_timestamp' ),
2536 array(
2537 'cl_from' => $pageid,
2538 'cl_sortkey' => $this->getPrefixedText() ),
2539 __METHOD__ );
2541 # Update watchlists
2543 $oldnamespace = $this->getNamespace() & ~1;
2544 $newnamespace = $nt->getNamespace() & ~1;
2545 $oldtitle = $this->getDBkey();
2546 $newtitle = $nt->getDBkey();
2548 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2549 WatchedItem::duplicateEntries( $this, $nt );
2552 # Update search engine
2553 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2554 $u->doUpdate();
2555 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2556 $u->doUpdate();
2558 # Update site_stats
2559 if( $this->isContentPage() && !$nt->isContentPage() ) {
2560 # No longer a content page
2561 # Not viewed, edited, removing
2562 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2563 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2564 # Now a content page
2565 # Not viewed, edited, adding
2566 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2567 } elseif( $pageCountChange ) {
2568 # Redirect added
2569 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2570 } else {
2571 # Nothing special
2572 $u = false;
2574 if( $u )
2575 $u->doUpdate();
2576 # Update message cache for interface messages
2577 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2578 global $wgMessageCache;
2579 $oldarticle = new Article( $this );
2580 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2581 $newarticle = new Article( $nt );
2582 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2585 global $wgUser;
2586 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2587 return true;
2591 * Move page to a title which is at present a redirect to the
2592 * source page
2594 * @param Title &$nt the page to move to, which should currently
2595 * be a redirect
2596 * @param string $reason The reason for the move
2597 * @param bool $createRedirect Whether to leave a redirect at the old title.
2598 * Ignored if the user doesn't have the suppressredirect right
2600 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2601 global $wgUseSquid, $wgUser;
2602 $fname = 'Title::moveOverExistingRedirect';
2603 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2605 if ( $reason ) {
2606 $comment .= ": $reason";
2609 $now = wfTimestampNow();
2610 $newid = $nt->getArticleID();
2611 $oldid = $this->getArticleID();
2613 $dbw = wfGetDB( DB_MASTER );
2614 $dbw->begin();
2616 # Delete the old redirect. We don't save it to history since
2617 # by definition if we've got here it's rather uninteresting.
2618 # We have to remove it so that the next step doesn't trigger
2619 # a conflict on the unique namespace+title index...
2620 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2621 if ( !$dbw->cascadingDeletes() ) {
2622 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2623 global $wgUseTrackbacks;
2624 if ($wgUseTrackbacks)
2625 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2626 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2627 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2628 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2629 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2630 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2631 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2632 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2635 # Save a null revision in the page's history notifying of the move
2636 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2637 $nullRevId = $nullRevision->insertOn( $dbw );
2639 $article = new Article( $this );
2640 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
2642 # Change the name of the target page:
2643 $dbw->update( 'page',
2644 /* SET */ array(
2645 'page_touched' => $dbw->timestamp($now),
2646 'page_namespace' => $nt->getNamespace(),
2647 'page_title' => $nt->getDBkey(),
2648 'page_latest' => $nullRevId,
2650 /* WHERE */ array( 'page_id' => $oldid ),
2651 $fname
2653 $nt->resetArticleID( $oldid );
2655 # Recreate the redirect, this time in the other direction.
2656 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2657 $mwRedir = MagicWord::get( 'redirect' );
2658 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2659 $redirectArticle = new Article( $this );
2660 $newid = $redirectArticle->insertOn( $dbw );
2661 $redirectRevision = new Revision( array(
2662 'page' => $newid,
2663 'comment' => $comment,
2664 'text' => $redirectText ) );
2665 $redirectRevision->insertOn( $dbw );
2666 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2668 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2670 # Now, we record the link from the redirect to the new title.
2671 # It should have no other outgoing links...
2672 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2673 $dbw->insert( 'pagelinks',
2674 array(
2675 'pl_from' => $newid,
2676 'pl_namespace' => $nt->getNamespace(),
2677 'pl_title' => $nt->getDBkey() ),
2678 $fname );
2679 } else {
2680 $this->resetArticleID( 0 );
2683 # Move an image if this is a file
2684 if( $this->getNamespace() == NS_IMAGE ) {
2685 $file = wfLocalFile( $this );
2686 if( $file->exists() ) {
2687 $status = $file->move( $nt );
2688 if( !$status->isOk() ) {
2689 $dbw->rollback();
2690 return $status->getErrorsArray();
2694 $dbw->commit();
2696 # Log the move
2697 $log = new LogPage( 'move' );
2698 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2700 # Purge squid
2701 if ( $wgUseSquid ) {
2702 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2703 $u = new SquidUpdate( $urls );
2704 $u->doUpdate();
2710 * Move page to non-existing title.
2711 * @param Title &$nt the new Title
2712 * @param string $reason The reason for the move
2713 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2714 * Ignored if the user doesn't have the suppressredirect right
2716 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2717 global $wgUseSquid, $wgUser;
2718 $fname = 'MovePageForm::moveToNewTitle';
2719 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2720 if ( $reason ) {
2721 $comment .= wfMsgExt( 'colon-separator',
2722 array( 'escapenoentities', 'content' ) );
2723 $comment .= $reason;
2726 $newid = $nt->getArticleID();
2727 $oldid = $this->getArticleID();
2729 $dbw = wfGetDB( DB_MASTER );
2730 $dbw->begin();
2731 $now = $dbw->timestamp();
2733 # Save a null revision in the page's history notifying of the move
2734 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2735 $nullRevId = $nullRevision->insertOn( $dbw );
2737 $article = new Article( $this );
2738 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
2740 # Rename page entry
2741 $dbw->update( 'page',
2742 /* SET */ array(
2743 'page_touched' => $now,
2744 'page_namespace' => $nt->getNamespace(),
2745 'page_title' => $nt->getDBkey(),
2746 'page_latest' => $nullRevId,
2748 /* WHERE */ array( 'page_id' => $oldid ),
2749 $fname
2751 $nt->resetArticleID( $oldid );
2753 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2754 # Insert redirect
2755 $mwRedir = MagicWord::get( 'redirect' );
2756 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2757 $redirectArticle = new Article( $this );
2758 $newid = $redirectArticle->insertOn( $dbw );
2759 $redirectRevision = new Revision( array(
2760 'page' => $newid,
2761 'comment' => $comment,
2762 'text' => $redirectText ) );
2763 $redirectRevision->insertOn( $dbw );
2764 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2766 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2768 # Record the just-created redirect's linking to the page
2769 $dbw->insert( 'pagelinks',
2770 array(
2771 'pl_from' => $newid,
2772 'pl_namespace' => $nt->getNamespace(),
2773 'pl_title' => $nt->getDBkey() ),
2774 $fname );
2775 } else {
2776 $this->resetArticleID( 0 );
2779 # Move an image if this is a file
2780 if( $this->getNamespace() == NS_IMAGE ) {
2781 $file = wfLocalFile( $this );
2782 if( $file->exists() ) {
2783 $status = $file->move( $nt );
2784 if( !$status->isOk() ) {
2785 $dbw->rollback();
2786 return $status->getErrorsArray();
2790 $dbw->commit();
2792 # Log the move
2793 $log = new LogPage( 'move' );
2794 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2796 # Purge caches as per article creation
2797 Article::onArticleCreate( $nt );
2799 # Purge old title from squid
2800 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2801 $this->purgeSquid();
2806 * Checks if $this can be moved to a given Title
2807 * - Selects for update, so don't call it unless you mean business
2809 * @param Title &$nt the new title to check
2811 public function isValidMoveTarget( $nt ) {
2813 $fname = 'Title::isValidMoveTarget';
2814 $dbw = wfGetDB( DB_MASTER );
2816 # Is it an existsing file?
2817 if( $nt->getNamespace() == NS_IMAGE ) {
2818 $file = wfLocalFile( $nt );
2819 if( $file->exists() ) {
2820 wfDebug( __METHOD__ . ": file exists\n" );
2821 return false;
2825 # Is it a redirect?
2826 $id = $nt->getArticleID();
2827 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2828 array( 'page_is_redirect','old_text','old_flags' ),
2829 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2830 $fname, 'FOR UPDATE' );
2832 if ( !$obj || 0 == $obj->page_is_redirect ) {
2833 # Not a redirect
2834 wfDebug( __METHOD__ . ": not a redirect\n" );
2835 return false;
2837 $text = Revision::getRevisionText( $obj );
2839 # Does the redirect point to the source?
2840 # Or is it a broken self-redirect, usually caused by namespace collisions?
2841 $m = array();
2842 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2843 $redirTitle = Title::newFromText( $m[1] );
2844 if( !is_object( $redirTitle ) ||
2845 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2846 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2847 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2848 return false;
2850 } else {
2851 # Fail safe
2852 wfDebug( __METHOD__ . ": failsafe\n" );
2853 return false;
2856 # Does the article have a history?
2857 $row = $dbw->selectRow( array( 'page', 'revision'),
2858 array( 'rev_id' ),
2859 array( 'page_namespace' => $nt->getNamespace(),
2860 'page_title' => $nt->getDBkey(),
2861 'page_id=rev_page AND page_latest != rev_id'
2862 ), $fname, 'FOR UPDATE'
2865 # Return true if there was no history
2866 return $row === false;
2870 * Can this title be added to a user's watchlist?
2872 * @return bool
2874 public function isWatchable() {
2875 return !$this->isExternal()
2876 && MWNamespace::isWatchable( $this->getNamespace() );
2880 * Get categories to which this Title belongs and return an array of
2881 * categories' names.
2883 * @return array an array of parents in the form:
2884 * $parent => $currentarticle
2886 public function getParentCategories() {
2887 global $wgContLang;
2889 $titlekey = $this->getArticleId();
2890 $dbr = wfGetDB( DB_SLAVE );
2891 $categorylinks = $dbr->tableName( 'categorylinks' );
2893 # NEW SQL
2894 $sql = "SELECT * FROM $categorylinks"
2895 ." WHERE cl_from='$titlekey'"
2896 ." AND cl_from <> '0'"
2897 ." ORDER BY cl_sortkey";
2899 $res = $dbr->query( $sql );
2901 if( $dbr->numRows( $res ) > 0 ) {
2902 while( $x = $dbr->fetchObject( $res ) )
2903 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2904 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2905 $dbr->freeResult( $res );
2906 } else {
2907 $data = array();
2909 return $data;
2913 * Get a tree of parent categories
2914 * @param array $children an array with the children in the keys, to check for circular refs
2915 * @return array
2917 public function getParentCategoryTree( $children = array() ) {
2918 $stack = array();
2919 $parents = $this->getParentCategories();
2921 if( $parents ) {
2922 foreach( $parents as $parent => $current ) {
2923 if ( array_key_exists( $parent, $children ) ) {
2924 # Circular reference
2925 $stack[$parent] = array();
2926 } else {
2927 $nt = Title::newFromText($parent);
2928 if ( $nt ) {
2929 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2933 return $stack;
2934 } else {
2935 return array();
2941 * Get an associative array for selecting this title from
2942 * the "page" table
2944 * @return array
2946 public function pageCond() {
2947 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2951 * Get the revision ID of the previous revision
2953 * @param integer $revision Revision ID. Get the revision that was before this one.
2954 * @param integer $flags, GAID_FOR_UPDATE
2955 * @return integer $oldrevision|false
2957 public function getPreviousRevisionID( $revision, $flags=0 ) {
2958 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2959 return $db->selectField( 'revision', 'rev_id',
2960 array(
2961 'rev_page' => $this->getArticleId($flags),
2962 'rev_id < ' . intval( $revision )
2964 __METHOD__,
2965 array( 'ORDER BY' => 'rev_id DESC' )
2970 * Get the revision ID of the next revision
2972 * @param integer $revision Revision ID. Get the revision that was after this one.
2973 * @param integer $flags, GAID_FOR_UPDATE
2974 * @return integer $oldrevision|false
2976 public function getNextRevisionID( $revision, $flags=0 ) {
2977 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2978 return $db->selectField( 'revision', 'rev_id',
2979 array(
2980 'rev_page' => $this->getArticleId($flags),
2981 'rev_id > ' . intval( $revision )
2983 __METHOD__,
2984 array( 'ORDER BY' => 'rev_id' )
2989 * Get the number of revisions between the given revision IDs.
2990 * Used for diffs and other things that really need it.
2992 * @param integer $old Revision ID.
2993 * @param integer $new Revision ID.
2994 * @return integer Number of revisions between these IDs.
2996 public function countRevisionsBetween( $old, $new ) {
2997 $dbr = wfGetDB( DB_SLAVE );
2998 return $dbr->selectField( 'revision', 'count(*)',
2999 'rev_page = ' . intval( $this->getArticleId() ) .
3000 ' AND rev_id > ' . intval( $old ) .
3001 ' AND rev_id < ' . intval( $new ),
3002 __METHOD__,
3003 array( 'USE INDEX' => 'PRIMARY' ) );
3007 * Compare with another title.
3009 * @param Title $title
3010 * @return bool
3012 public function equals( $title ) {
3013 // Note: === is necessary for proper matching of number-like titles.
3014 return $this->getInterwiki() === $title->getInterwiki()
3015 && $this->getNamespace() == $title->getNamespace()
3016 && $this->getDBkey() === $title->getDBkey();
3020 * Callback for usort() to do title sorts by (namespace, title)
3022 static function compare( $a, $b ) {
3023 if( $a->getNamespace() == $b->getNamespace() ) {
3024 return strcmp( $a->getText(), $b->getText() );
3025 } else {
3026 return $a->getNamespace() - $b->getNamespace();
3031 * Return a string representation of this title
3033 * @return string
3035 public function __toString() {
3036 return $this->getPrefixedText();
3040 * Check if page exists
3041 * @return bool
3043 public function exists() {
3044 return $this->getArticleId() != 0;
3048 * Do we know that this title definitely exists, or should we otherwise
3049 * consider that it exists?
3051 * @return bool
3053 public function isAlwaysKnown() {
3054 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3055 // the full l10n of that language to be loaded. That takes much memory and
3056 // isn't needed. So we strip the language part away.
3057 // Also, extension messages which are not loaded, are shown as red, because
3058 // we don't call MessageCache::loadAllMessages.
3059 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3060 return $this->isExternal()
3061 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3062 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3066 * Update page_touched timestamps and send squid purge messages for
3067 * pages linking to this title. May be sent to the job queue depending
3068 * on the number of links. Typically called on create and delete.
3070 public function touchLinks() {
3071 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3072 $u->doUpdate();
3074 if ( $this->getNamespace() == NS_CATEGORY ) {
3075 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3076 $u->doUpdate();
3081 * Get the last touched timestamp
3083 public function getTouched() {
3084 $dbr = wfGetDB( DB_SLAVE );
3085 $touched = $dbr->selectField( 'page', 'page_touched',
3086 array(
3087 'page_namespace' => $this->getNamespace(),
3088 'page_title' => $this->getDBkey()
3089 ), __METHOD__
3091 return $touched;
3094 public function trackbackURL() {
3095 global $wgTitle, $wgScriptPath, $wgServer;
3097 return "$wgServer$wgScriptPath/trackback.php?article="
3098 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3101 public function trackbackRDF() {
3102 $url = htmlspecialchars($this->getFullURL());
3103 $title = htmlspecialchars($this->getText());
3104 $tburl = $this->trackbackURL();
3106 // Autodiscovery RDF is placed in comments so HTML validator
3107 // won't barf. This is a rather icky workaround, but seems
3108 // frequently used by this kind of RDF thingy.
3110 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3111 return "<!--
3112 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3113 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3114 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3115 <rdf:Description
3116 rdf:about=\"$url\"
3117 dc:identifier=\"$url\"
3118 dc:title=\"$title\"
3119 trackback:ping=\"$tburl\" />
3120 </rdf:RDF>
3121 -->";
3125 * Generate strings used for xml 'id' names in monobook tabs
3126 * @return string
3128 public function getNamespaceKey() {
3129 global $wgContLang;
3130 switch ($this->getNamespace()) {
3131 case NS_MAIN:
3132 case NS_TALK:
3133 return 'nstab-main';
3134 case NS_USER:
3135 case NS_USER_TALK:
3136 return 'nstab-user';
3137 case NS_MEDIA:
3138 return 'nstab-media';
3139 case NS_SPECIAL:
3140 return 'nstab-special';
3141 case NS_PROJECT:
3142 case NS_PROJECT_TALK:
3143 return 'nstab-project';
3144 case NS_IMAGE:
3145 case NS_IMAGE_TALK:
3146 return 'nstab-image';
3147 case NS_MEDIAWIKI:
3148 case NS_MEDIAWIKI_TALK:
3149 return 'nstab-mediawiki';
3150 case NS_TEMPLATE:
3151 case NS_TEMPLATE_TALK:
3152 return 'nstab-template';
3153 case NS_HELP:
3154 case NS_HELP_TALK:
3155 return 'nstab-help';
3156 case NS_CATEGORY:
3157 case NS_CATEGORY_TALK:
3158 return 'nstab-category';
3159 default:
3160 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3165 * Returns true if this title resolves to the named special page
3166 * @param string $name The special page name
3168 public function isSpecial( $name ) {
3169 if ( $this->getNamespace() == NS_SPECIAL ) {
3170 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3171 if ( $name == $thisName ) {
3172 return true;
3175 return false;
3179 * If the Title refers to a special page alias which is not the local default,
3180 * returns a new Title which points to the local default. Otherwise, returns $this.
3182 public function fixSpecialName() {
3183 if ( $this->getNamespace() == NS_SPECIAL ) {
3184 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3185 if ( $canonicalName ) {
3186 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3187 if ( $localName != $this->mDbkeyform ) {
3188 return Title::makeTitle( NS_SPECIAL, $localName );
3192 return $this;
3196 * Is this Title in a namespace which contains content?
3197 * In other words, is this a content page, for the purposes of calculating
3198 * statistics, etc?
3200 * @return bool
3202 public function isContentPage() {
3203 return MWNamespace::isContent( $this->getNamespace() );
3206 public function getRedirectsHere( $ns = null ) {
3207 $redirs = array();
3209 $dbr = wfGetDB( DB_SLAVE );
3210 $where = array(
3211 'rd_namespace' => $this->getNamespace(),
3212 'rd_title' => $this->getDBkey(),
3213 'rd_from = page_id'
3215 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3217 $result = $dbr->select(
3218 array( 'redirect', 'page' ),
3219 array( 'page_namespace', 'page_title' ),
3220 $where,
3221 __METHOD__
3225 while( $row = $dbr->fetchObject( $result ) ) {
3226 $redirs[] = self::newFromRow( $row );
3228 return $redirs;