Update the Chinese conversion tables
[mediawiki.git] / includes / Title.php
blob71a601c229c2ff8301377676b7da36419c8b8e96
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 = NS_MAIN; # 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 = -1; # Article ID, fetched from the link cache on demand
55 var $mLatestID = false; # ID of most recent revision
56 var $mRestrictions = array(); # Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; # Cascade restrictions on this page to included templates and images?
59 var $mRestrictionsExpiry; # When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page?
61 var $mCascadeRestrictionSources; # Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; # Boolean for initialisation on demand
63 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN; # Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; # Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; # The page length, 0 for special pages
70 var $mRedirect = null; # Is the article at this title a redirect?
71 /**#@-*/
74 /**
75 * Constructor
76 * @private
78 /* private */ function __construct() {}
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return Title the new object, or NULL on an error
87 public static function newFromDBkey( $key ) {
88 $t = new Title();
89 $t->mDbkeyform = $key;
90 if( $t->secureAndSplit() )
91 return $t;
92 else
93 return NULL;
96 /**
97 * Create a new Title from text, such as what one would
98 * find in a link. Decodes any HTML entities in the text.
100 * @param string $text the link text; spaces, prefixes,
101 * and an initial ':' indicating the main namespace
102 * are accepted
103 * @param int $defaultNamespace the namespace to use if
104 * none is specified by a prefix
105 * @return Title the new object, or NULL on an error
107 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
108 if( is_object( $text ) ) {
109 throw new MWException( 'Title::newFromText given an object' );
113 * Wiki pages often contain multiple links to the same page.
114 * Title normalization and parsing can become expensive on
115 * pages with many links, so we can save a little time by
116 * caching them.
118 * In theory these are value objects and won't get changed...
120 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
121 return Title::$titleCache[$text];
125 * Convert things like &eacute; &#257; or &#x3017; into real text...
127 $filteredText = Sanitizer::decodeCharReferences( $text );
129 $t = new Title();
130 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
131 $t->mDefaultNamespace = $defaultNamespace;
133 static $cachedcount = 0 ;
134 if( $t->secureAndSplit() ) {
135 if( $defaultNamespace == NS_MAIN ) {
136 if( $cachedcount >= MW_TITLECACHE_MAX ) {
137 # Avoid memory leaks on mass operations...
138 Title::$titleCache = array();
139 $cachedcount=0;
141 $cachedcount++;
142 Title::$titleCache[$text] =& $t;
144 return $t;
145 } else {
146 $ret = NULL;
147 return $ret;
152 * Create a new Title from URL-encoded text. Ensures that
153 * the given title's length does not exceed the maximum.
154 * @param string $url the title, as might be taken from a URL
155 * @return Title the new object, or NULL on an error
157 public static function newFromURL( $url ) {
158 global $wgLegalTitleChars;
159 $t = new Title();
161 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
162 # but some URLs used it as a space replacement and they still come
163 # from some external search tools.
164 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
165 $url = str_replace( '+', ' ', $url );
168 $t->mDbkeyform = str_replace( ' ', '_', $url );
169 if( $t->secureAndSplit() ) {
170 return $t;
171 } else {
172 return NULL;
177 * Create a new Title from an article ID
179 * @todo This is inefficiently implemented, the page row is requested
180 * but not used for anything else
182 * @param int $id the page_id corresponding to the Title to create
183 * @param int $flags, use GAID_FOR_UPDATE to use master
184 * @return Title the new object, or NULL on an error
186 public static function newFromID( $id, $flags = 0 ) {
187 $fname = 'Title::newFromID';
188 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
189 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
190 array( 'page_id' => $id ), $fname );
191 if ( $row !== false ) {
192 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
193 } else {
194 $title = NULL;
196 return $title;
200 * Make an array of titles from an array of IDs
202 public static function newFromIDs( $ids ) {
203 if ( !count( $ids ) ) {
204 return array();
206 $dbr = wfGetDB( DB_SLAVE );
207 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
208 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
210 $titles = array();
211 while ( $row = $dbr->fetchObject( $res ) ) {
212 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
214 return $titles;
218 * Make a Title object from a DB row
219 * @param Row $row (needs at least page_title,page_namespace)
221 public static function newFromRow( $row ) {
222 $t = self::makeTitle( $row->page_namespace, $row->page_title );
224 $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1;
225 $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1;
226 $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL;
227 $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false;
229 return $t;
233 * Create a new Title from a namespace index and a DB key.
234 * It's assumed that $ns and $title are *valid*, for instance when
235 * they came directly from the database or a special page name.
236 * For convenience, spaces are converted to underscores so that
237 * eg user_text fields can be used directly.
239 * @param int $ns the namespace of the article
240 * @param string $title the unprefixed database key form
241 * @param string $fragment The link fragment (after the "#")
242 * @return Title the new object
244 public static function &makeTitle( $ns, $title, $fragment = '' ) {
245 $t = new Title();
246 $t->mInterwiki = '';
247 $t->mFragment = $fragment;
248 $t->mNamespace = $ns = intval( $ns );
249 $t->mDbkeyform = str_replace( ' ', '_', $title );
250 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
251 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
252 $t->mTextform = str_replace( '_', ' ', $title );
253 return $t;
257 * Create a new Title from a namespace index and a DB key.
258 * The parameters will be checked for validity, which is a bit slower
259 * than makeTitle() but safer for user-provided data.
261 * @param int $ns the namespace of the article
262 * @param string $title the database key form
263 * @param string $fragment The link fragment (after the "#")
264 * @return Title the new object, or NULL on an error
266 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
267 $t = new Title();
268 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment );
269 if( $t->secureAndSplit() ) {
270 return $t;
271 } else {
272 return NULL;
277 * Create a new Title for the Main Page
278 * @return Title the new object
280 public static function newMainPage() {
281 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
282 // Don't give fatal errors if the message is broken
283 if ( !$title ) {
284 $title = Title::newFromText( 'Main Page' );
286 return $title;
290 * Extract a redirect destination from a string and return the
291 * Title, or null if the text doesn't contain a valid redirect
293 * @param string $text Text with possible redirect
294 * @return Title
296 public static function newFromRedirect( $text ) {
297 $redir = MagicWord::get( 'redirect' );
298 if( $redir->matchStart( trim($text) ) ) {
299 // Extract the first link and see if it's usable
300 $m = array();
301 if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
302 // Strip preceding colon used to "escape" categories, etc.
303 // and URL-decode links
304 if( strpos( $m[1], '%' ) !== false ) {
305 // Match behavior of inline link parsing here;
306 // don't interpret + as " " most of the time!
307 // It might be safe to just use rawurldecode instead, though.
308 $m[1] = urldecode( ltrim( $m[1], ':' ) );
310 $title = Title::newFromText( $m[1] );
311 // Redirects to Special:Userlogout are not permitted
312 if( $title instanceof Title && !$title->isSpecial( 'Userlogout' ) )
313 return $title;
316 return null;
319 #----------------------------------------------------------------------------
320 # Static functions
321 #----------------------------------------------------------------------------
324 * Get the prefixed DB key associated with an ID
325 * @param int $id the page_id of the article
326 * @return Title an object representing the article, or NULL
327 * if no such article was found
328 * @static
329 * @access public
331 function nameOf( $id ) {
332 $fname = 'Title::nameOf';
333 $dbr = wfGetDB( DB_SLAVE );
335 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
336 if ( $s === false ) { return NULL; }
338 $n = Title::makeName( $s->page_namespace, $s->page_title );
339 return $n;
343 * Get a regex character class describing the legal characters in a link
344 * @return string the list of characters, not delimited
346 public static function legalChars() {
347 global $wgLegalTitleChars;
348 return $wgLegalTitleChars;
352 * Get a string representation of a title suitable for
353 * including in a search index
355 * @param int $ns a namespace index
356 * @param string $title text-form main part
357 * @return string a stripped-down title string ready for the
358 * search index
360 public static function indexTitle( $ns, $title ) {
361 global $wgContLang;
363 $lc = SearchEngine::legalSearchChars() . '&#;';
364 $t = $wgContLang->stripForSearch( $title );
365 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
366 $t = $wgContLang->lc( $t );
368 # Handle 's, s'
369 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
370 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
372 $t = preg_replace( "/\\s+/", ' ', $t );
374 if ( $ns == NS_IMAGE ) {
375 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
377 return trim( $t );
381 * Make a prefixed DB key from a DB key and a namespace index
382 * @param int $ns numerical representation of the namespace
383 * @param string $title the DB key form the title
384 * @param string $fragment The link fragment (after the "#")
385 * @return string the prefixed form of the title
387 public static function makeName( $ns, $title, $fragment = '' ) {
388 global $wgContLang;
390 $namespace = $wgContLang->getNsText( $ns );
391 $name = $namespace == '' ? $title : "$namespace:$title";
392 if ( strval( $fragment ) != '' ) {
393 $name .= '#' . $fragment;
395 return $name;
399 * Returns the URL associated with an interwiki prefix
400 * @param string $key the interwiki prefix (e.g. "MeatBall")
401 * @return the associated URL, containing "$1", which should be
402 * replaced by an article title
403 * @static (arguably)
405 public function getInterwikiLink( $key ) {
406 global $wgMemc, $wgInterwikiExpiry;
407 global $wgInterwikiCache, $wgContLang;
408 $fname = 'Title::getInterwikiLink';
410 $key = $wgContLang->lc( $key );
412 $k = wfMemcKey( 'interwiki', $key );
413 if( array_key_exists( $k, Title::$interwikiCache ) ) {
414 return Title::$interwikiCache[$k]->iw_url;
417 if ($wgInterwikiCache) {
418 return Title::getInterwikiCached( $key );
421 $s = $wgMemc->get( $k );
422 # Ignore old keys with no iw_local
423 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
424 Title::$interwikiCache[$k] = $s;
425 return $s->iw_url;
428 $dbr = wfGetDB( DB_SLAVE );
429 $res = $dbr->select( 'interwiki',
430 array( 'iw_url', 'iw_local', 'iw_trans' ),
431 array( 'iw_prefix' => $key ), $fname );
432 if( !$res ) {
433 return '';
436 $s = $dbr->fetchObject( $res );
437 if( !$s ) {
438 # Cache non-existence: create a blank object and save it to memcached
439 $s = (object)false;
440 $s->iw_url = '';
441 $s->iw_local = 0;
442 $s->iw_trans = 0;
444 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
445 Title::$interwikiCache[$k] = $s;
447 return $s->iw_url;
451 * Fetch interwiki prefix data from local cache in constant database
453 * More logic is explained in DefaultSettings
455 * @return string URL of interwiki site
457 public static function getInterwikiCached( $key ) {
458 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
459 static $db, $site;
461 if (!$db)
462 $db=dba_open($wgInterwikiCache,'r','cdb');
463 /* Resolve site name */
464 if ($wgInterwikiScopes>=3 and !$site) {
465 $site = dba_fetch('__sites:' . wfWikiID(), $db);
466 if ($site=="")
467 $site = $wgInterwikiFallbackSite;
469 $value = dba_fetch( wfMemcKey( $key ), $db);
470 if ($value=='' and $wgInterwikiScopes>=3) {
471 /* try site-level */
472 $value = dba_fetch("_{$site}:{$key}", $db);
474 if ($value=='' and $wgInterwikiScopes>=2) {
475 /* try globals */
476 $value = dba_fetch("__global:{$key}", $db);
478 if ($value=='undef')
479 $value='';
480 $s = (object)false;
481 $s->iw_url = '';
482 $s->iw_local = 0;
483 $s->iw_trans = 0;
484 if ($value!='') {
485 list($local,$url)=explode(' ',$value,2);
486 $s->iw_url=$url;
487 $s->iw_local=(int)$local;
489 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
490 return $s->iw_url;
493 * Determine whether the object refers to a page within
494 * this project.
496 * @return bool TRUE if this is an in-project interwiki link
497 * or a wikilink, FALSE otherwise
499 public function isLocal() {
500 if ( $this->mInterwiki != '' ) {
501 # Make sure key is loaded into cache
502 $this->getInterwikiLink( $this->mInterwiki );
503 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
504 return (bool)(Title::$interwikiCache[$k]->iw_local);
505 } else {
506 return true;
511 * Determine whether the object refers to a page within
512 * this project and is transcludable.
514 * @return bool TRUE if this is transcludable
516 public function isTrans() {
517 if ($this->mInterwiki == '')
518 return false;
519 # Make sure key is loaded into cache
520 $this->getInterwikiLink( $this->mInterwiki );
521 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
522 return (bool)(Title::$interwikiCache[$k]->iw_trans);
526 * Escape a text fragment, say from a link, for a URL
528 static function escapeFragmentForURL( $fragment ) {
529 $fragment = str_replace( ' ', '_', $fragment );
530 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
531 $replaceArray = array(
532 '%3A' => ':',
533 '%' => '.'
535 return strtr( $fragment, $replaceArray );
538 #----------------------------------------------------------------------------
539 # Other stuff
540 #----------------------------------------------------------------------------
542 /** Simple accessors */
544 * Get the text form (spaces not underscores) of the main part
545 * @return string
547 public function getText() { return $this->mTextform; }
549 * Get the URL-encoded form of the main part
550 * @return string
552 public function getPartialURL() { return $this->mUrlform; }
554 * Get the main part with underscores
555 * @return string
557 public function getDBkey() { return $this->mDbkeyform; }
559 * Get the namespace index, i.e. one of the NS_xxxx constants
560 * @return int
562 public function getNamespace() { return $this->mNamespace; }
564 * Get the namespace text
565 * @return string
567 public function getNsText() {
568 global $wgContLang, $wgCanonicalNamespaceNames;
570 if ( '' != $this->mInterwiki ) {
571 // This probably shouldn't even happen. ohh man, oh yuck.
572 // But for interwiki transclusion it sometimes does.
573 // Shit. Shit shit shit.
575 // Use the canonical namespaces if possible to try to
576 // resolve a foreign namespace.
577 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
578 return $wgCanonicalNamespaceNames[$this->mNamespace];
581 return $wgContLang->getNsText( $this->mNamespace );
584 * Get the DB key with the initial letter case as specified by the user
586 function getUserCaseDBKey() {
587 return $this->mUserCaseDBKey;
590 * Get the namespace text of the subject (rather than talk) page
591 * @return string
593 public function getSubjectNsText() {
594 global $wgContLang;
595 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
599 * Get the namespace text of the talk page
600 * @return string
602 public function getTalkNsText() {
603 global $wgContLang;
604 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
608 * Could this title have a corresponding talk page?
609 * @return bool
611 public function canTalk() {
612 return( MWNamespace::canTalk( $this->mNamespace ) );
616 * Get the interwiki prefix (or null string)
617 * @return string
619 public function getInterwiki() { return $this->mInterwiki; }
621 * Get the Title fragment (i.e. the bit after the #) in text form
622 * @return string
624 public function getFragment() { return $this->mFragment; }
626 * Get the fragment in URL form, including the "#" character if there is one
627 * @return string
629 public function getFragmentForURL() {
630 if ( $this->mFragment == '' ) {
631 return '';
632 } else {
633 return '#' . Title::escapeFragmentForURL( $this->mFragment );
637 * Get the default namespace index, for when there is no namespace
638 * @return int
640 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
643 * Get title for search index
644 * @return string a stripped-down title string ready for the
645 * search index
647 public function getIndexTitle() {
648 return Title::indexTitle( $this->mNamespace, $this->mTextform );
652 * Get the prefixed database key form
653 * @return string the prefixed title, with underscores and
654 * any interwiki and namespace prefixes
656 public function getPrefixedDBkey() {
657 $s = $this->prefix( $this->mDbkeyform );
658 $s = str_replace( ' ', '_', $s );
659 return $s;
663 * Get the prefixed title with spaces.
664 * This is the form usually used for display
665 * @return string the prefixed title, with spaces
667 public function getPrefixedText() {
668 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
669 $s = $this->prefix( $this->mTextform );
670 $s = str_replace( '_', ' ', $s );
671 $this->mPrefixedText = $s;
673 return $this->mPrefixedText;
677 * Get the prefixed title with spaces, plus any fragment
678 * (part beginning with '#')
679 * @return string the prefixed title, with spaces and
680 * the fragment, including '#'
682 public function getFullText() {
683 $text = $this->getPrefixedText();
684 if( '' != $this->mFragment ) {
685 $text .= '#' . $this->mFragment;
687 return $text;
691 * Get the base name, i.e. the leftmost parts before the /
692 * @return string Base name
694 public function getBaseText() {
695 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
696 return $this->getText();
699 $parts = explode( '/', $this->getText() );
700 # Don't discard the real title if there's no subpage involved
701 if( count( $parts ) > 1 )
702 unset( $parts[ count( $parts ) - 1 ] );
703 return implode( '/', $parts );
707 * Get the lowest-level subpage name, i.e. the rightmost part after /
708 * @return string Subpage name
710 public function getSubpageText() {
711 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
712 return( $this->mTextform );
714 $parts = explode( '/', $this->mTextform );
715 return( $parts[ count( $parts ) - 1 ] );
719 * Get a URL-encoded form of the subpage text
720 * @return string URL-encoded subpage name
722 public function getSubpageUrlForm() {
723 $text = $this->getSubpageText();
724 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
725 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
726 return( $text );
730 * Get a URL-encoded title (not an actual URL) including interwiki
731 * @return string the URL-encoded form
733 public function getPrefixedURL() {
734 $s = $this->prefix( $this->mDbkeyform );
735 $s = str_replace( ' ', '_', $s );
737 $s = wfUrlencode ( $s ) ;
739 # Cleaning up URL to make it look nice -- is this safe?
740 $s = str_replace( '%28', '(', $s );
741 $s = str_replace( '%29', ')', $s );
743 return $s;
747 * Get a real URL referring to this title, with interwiki link and
748 * fragment
750 * @param string $query an optional query string, not used
751 * for interwiki links
752 * @param string $variant language variant of url (for sr, zh..)
753 * @return string the URL
755 public function getFullURL( $query = '', $variant = false ) {
756 global $wgContLang, $wgServer, $wgRequest;
758 if ( '' == $this->mInterwiki ) {
759 $url = $this->getLocalUrl( $query, $variant );
761 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
762 // Correct fix would be to move the prepending elsewhere.
763 if ($wgRequest->getVal('action') != 'render') {
764 $url = $wgServer . $url;
766 } else {
767 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
769 $namespace = wfUrlencode( $this->getNsText() );
770 if ( '' != $namespace ) {
771 # Can this actually happen? Interwikis shouldn't be parsed.
772 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
773 $namespace .= ':';
775 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
776 $url = wfAppendQuery( $url, $query );
779 # Finally, add the fragment.
780 $url .= $this->getFragmentForURL();
782 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
783 return $url;
787 * Get a URL with no fragment or server name. If this page is generated
788 * with action=render, $wgServer is prepended.
789 * @param string $query an optional query string; if not specified,
790 * $wgArticlePath will be used.
791 * @param string $variant language variant of url (for sr, zh..)
792 * @return string the URL
794 public function getLocalURL( $query = '', $variant = false ) {
795 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
796 global $wgVariantArticlePath, $wgContLang, $wgUser;
798 // internal links should point to same variant as current page (only anonymous users)
799 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
800 $pref = $wgContLang->getPreferredVariant(false);
801 if($pref != $wgContLang->getCode())
802 $variant = $pref;
805 if ( $this->isExternal() ) {
806 $url = $this->getFullURL();
807 if ( $query ) {
808 // This is currently only used for edit section links in the
809 // context of interwiki transclusion. In theory we should
810 // append the query to the end of any existing query string,
811 // but interwiki transclusion is already broken in that case.
812 $url .= "?$query";
814 } else {
815 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
816 if ( $query == '' ) {
817 if( $variant != false && $wgContLang->hasVariants() ) {
818 if( $wgVariantArticlePath == false ) {
819 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
820 } else {
821 $variantArticlePath = $wgVariantArticlePath;
823 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
824 $url = str_replace( '$1', $dbkey, $url );
825 } else {
826 $url = str_replace( '$1', $dbkey, $wgArticlePath );
828 } else {
829 global $wgActionPaths;
830 $url = false;
831 $matches = array();
832 if( !empty( $wgActionPaths ) &&
833 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
835 $action = urldecode( $matches[2] );
836 if( isset( $wgActionPaths[$action] ) ) {
837 $query = $matches[1];
838 if( isset( $matches[4] ) ) $query .= $matches[4];
839 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
840 if( $query != '' ) $url .= '?' . $query;
843 if ( $url === false ) {
844 if ( $query == '-' ) {
845 $query = '';
847 $url = "{$wgScript}?title={$dbkey}&{$query}";
851 // FIXME: this causes breakage in various places when we
852 // actually expected a local URL and end up with dupe prefixes.
853 if ($wgRequest->getVal('action') == 'render') {
854 $url = $wgServer . $url;
857 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
858 return $url;
862 * Get an HTML-escaped version of the URL form, suitable for
863 * using in a link, without a server name or fragment
864 * @param string $query an optional query string
865 * @return string the URL
867 public function escapeLocalURL( $query = '' ) {
868 return htmlspecialchars( $this->getLocalURL( $query ) );
872 * Get an HTML-escaped version of the URL form, suitable for
873 * using in a link, including the server name and fragment
875 * @return string the URL
876 * @param string $query an optional query string
878 public function escapeFullURL( $query = '' ) {
879 return htmlspecialchars( $this->getFullURL( $query ) );
883 * Get the URL form for an internal link.
884 * - Used in various Squid-related code, in case we have a different
885 * internal hostname for the server from the exposed one.
887 * @param string $query an optional query string
888 * @param string $variant language variant of url (for sr, zh..)
889 * @return string the URL
891 public function getInternalURL( $query = '', $variant = false ) {
892 global $wgInternalServer;
893 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
894 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
895 return $url;
899 * Get the edit URL for this Title
900 * @return string the URL, or a null string if this is an
901 * interwiki link
903 public function getEditURL() {
904 if ( '' != $this->mInterwiki ) { return ''; }
905 $s = $this->getLocalURL( 'action=edit' );
907 return $s;
911 * Get the HTML-escaped displayable text form.
912 * Used for the title field in <a> tags.
913 * @return string the text, including any prefixes
915 public function getEscapedText() {
916 return htmlspecialchars( $this->getPrefixedText() );
920 * Is this Title interwiki?
921 * @return boolean
923 public function isExternal() { return ( '' != $this->mInterwiki ); }
926 * Is this page "semi-protected" - the *only* protection is autoconfirm?
928 * @param string Action to check (default: edit)
929 * @return bool
931 public function isSemiProtected( $action = 'edit' ) {
932 if( $this->exists() ) {
933 $restrictions = $this->getRestrictions( $action );
934 if( count( $restrictions ) > 0 ) {
935 foreach( $restrictions as $restriction ) {
936 if( strtolower( $restriction ) != 'autoconfirmed' )
937 return false;
939 } else {
940 # Not protected
941 return false;
943 return true;
944 } else {
945 # If it doesn't exist, it can't be protected
946 return false;
951 * Does the title correspond to a protected article?
952 * @param string $what the action the page is protected from,
953 * by default checks move and edit
954 * @return boolean
956 public function isProtected( $action = '' ) {
957 global $wgRestrictionLevels, $wgRestrictionTypes;
959 # Special pages have inherent protection
960 if( $this->getNamespace() == NS_SPECIAL )
961 return true;
963 # Check regular protection levels
964 foreach( $wgRestrictionTypes as $type ){
965 if( $action == $type || $action == '' ) {
966 $r = $this->getRestrictions( $type );
967 foreach( $wgRestrictionLevels as $level ) {
968 if( in_array( $level, $r ) && $level != '' ) {
969 return true;
975 return false;
979 * Is $wgUser watching this page?
980 * @return boolean
982 public function userIsWatching() {
983 global $wgUser;
985 if ( is_null( $this->mWatched ) ) {
986 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
987 $this->mWatched = false;
988 } else {
989 $this->mWatched = $wgUser->isWatched( $this );
992 return $this->mWatched;
996 * Can $wgUser perform $action on this page?
997 * This skips potentially expensive cascading permission checks.
999 * Suitable for use for nonessential UI controls in common cases, but
1000 * _not_ for functional access control.
1002 * May provide false positives, but should never provide a false negative.
1004 * @param string $action action that permission needs to be checked for
1005 * @return boolean
1007 public function quickUserCan( $action ) {
1008 return $this->userCan( $action, false );
1012 * Determines if $wgUser is unable to edit this page because it has been protected
1013 * by $wgNamespaceProtection.
1015 * @return boolean
1017 public function isNamespaceProtected() {
1018 global $wgNamespaceProtection, $wgUser;
1019 if( isset( $wgNamespaceProtection[ $this->mNamespace ] ) ) {
1020 foreach( (array)$wgNamespaceProtection[ $this->mNamespace ] as $right ) {
1021 if( $right != '' && !$wgUser->isAllowed( $right ) )
1022 return true;
1025 return false;
1029 * Can $wgUser perform $action on this page?
1030 * @param string $action action that permission needs to be checked for
1031 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1032 * @return boolean
1034 public function userCan( $action, $doExpensiveQueries = true ) {
1035 global $wgUser;
1036 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
1040 * Can $user perform $action on this page?
1042 * FIXME: This *does not* check throttles (User::pingLimiter()).
1044 * @param string $action action that permission needs to be checked for
1045 * @param User $user user to check
1046 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1047 * @param array $ignoreErrors Set this to a list of message keys whose corresponding errors may be ignored.
1048 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1050 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1051 if( !StubObject::isRealObject( $user ) ) {
1052 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1053 global $wgUser;
1054 $wgUser->_unstub( '', 5 );
1055 $user = $wgUser;
1057 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1059 global $wgContLang;
1060 global $wgLang;
1061 global $wgEmailConfirmToEdit;
1063 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1064 $errors[] = array( 'confirmedittext' );
1067 if ( $user->isBlockedFrom( $this ) && $action != 'createaccount' ) {
1068 $block = $user->mBlock;
1070 // This is from OutputPage::blockedPage
1071 // Copied at r23888 by werdna
1073 $id = $user->blockedBy();
1074 $reason = $user->blockedFor();
1075 if( $reason == '' ) {
1076 $reason = wfMsg( 'blockednoreason' );
1078 $ip = wfGetIP();
1080 if ( is_numeric( $id ) ) {
1081 $name = User::whoIs( $id );
1082 } else {
1083 $name = $id;
1086 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1087 $blockid = $block->mId;
1088 $blockExpiry = $user->mBlock->mExpiry;
1089 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1091 if ( $blockExpiry == 'infinity' ) {
1092 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1093 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1095 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1096 if ( strpos( $option, ':' ) == false )
1097 continue;
1099 list ($show, $value) = explode( ":", $option );
1101 if ( $value == 'infinite' || $value == 'indefinite' ) {
1102 $blockExpiry = $show;
1103 break;
1106 } else {
1107 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1110 $intended = $user->mBlock->mAddress;
1112 $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1113 $blockid, $blockExpiry, $intended, $blockTimestamp );
1116 // Remove the errors being ignored.
1118 foreach( $errors as $index => $error ) {
1119 $error_key = is_array($error) ? $error[0] : $error;
1121 if (in_array( $error_key, $ignoreErrors )) {
1122 unset($errors[$index]);
1126 return $errors;
1130 * Can $user perform $action on this page? This is an internal function,
1131 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1132 * checks on wfReadOnly() and blocks)
1134 * @param string $action action that permission needs to be checked for
1135 * @param User $user user to check
1136 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1137 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1139 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1140 wfProfileIn( __METHOD__ );
1142 $errors = array();
1144 // Use getUserPermissionsErrors instead
1145 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1146 wfProfileOut( __METHOD__ );
1147 return $result ? array() : array( array( 'badaccess-group0' ) );
1150 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1151 if ($result != array() && is_array($result) && !is_array($result[0]))
1152 $errors[] = $result; # A single array representing an error
1153 else if (is_array($result) && is_array($result[0]))
1154 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1155 else if ($result != '' && $result != null && $result !== true && $result !== false)
1156 $errors[] = array($result); # A string representing a message-id
1157 else if ($result === false )
1158 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1160 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1161 if ($result != array() && is_array($result) && !is_array($result[0]))
1162 $errors[] = $result; # A single array representing an error
1163 else if (is_array($result) && is_array($result[0]))
1164 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1165 else if ($result != '' && $result != null && $result !== true && $result !== false)
1166 $errors[] = array($result); # A string representing a message-id
1167 else if ($result === false )
1168 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1171 $specialOKActions = array( 'createaccount', 'execute' );
1172 if( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions) ) {
1173 $errors[] = array('ns-specialprotected');
1176 if ( $this->isNamespaceProtected() ) {
1177 $ns = $this->getNamespace() == NS_MAIN
1178 ? wfMsg( 'nstab-main' )
1179 : $this->getNsText();
1180 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1181 ? array('protectedinterface')
1182 : array( 'namespaceprotected', $ns ) );
1185 if( $this->mDbkeyform == '_' ) {
1186 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1187 $errors[] = array('badaccess-group0');
1190 # protect css/js subpages of user pages
1191 # XXX: this might be better using restrictions
1192 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1193 if( $this->isCssJsSubpage()
1194 && !$user->isAllowed('editusercssjs')
1195 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1196 $errors[] = array('customcssjsprotected');
1199 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1200 # We /could/ use the protection level on the source page, but it's fairly ugly
1201 # as we have to establish a precedence hierarchy for pages included by multiple
1202 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1203 # as they could remove the protection anyway.
1204 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1205 # Cascading protection depends on more than this page...
1206 # Several cascading protected pages may include this page...
1207 # Check each cascading level
1208 # This is only for protection restrictions, not for all actions
1209 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1210 foreach( $restrictions[$action] as $right ) {
1211 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1212 if( '' != $right && !$user->isAllowed( $right ) ) {
1213 $pages = '';
1214 foreach( $cascadingSources as $page )
1215 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1216 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1222 foreach( $this->getRestrictions($action) as $right ) {
1223 // Backwards compatibility, rewrite sysop -> protect
1224 if ( $right == 'sysop' ) {
1225 $right = 'protect';
1227 if( '' != $right && !$user->isAllowed( $right ) ) {
1228 //Users with 'editprotected' permission can edit protected pages
1229 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1230 //Users with 'editprotected' permission cannot edit protected pages
1231 //with cascading option turned on.
1232 if($this->mCascadeRestriction) {
1233 $errors[] = array( 'protectedpagetext', $right );
1234 } else {
1235 //Nothing, user can edit!
1237 } else {
1238 $errors[] = array( 'protectedpagetext', $right );
1243 if ($action == 'protect') {
1244 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1245 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1249 if ($action == 'create') {
1250 $title_protection = $this->getTitleProtection();
1252 if (is_array($title_protection)) {
1253 extract($title_protection);
1255 if ($pt_create_perm == 'sysop')
1256 $pt_create_perm = 'protect';
1258 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1259 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1263 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1264 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1265 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1267 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1268 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1269 } elseif ( !$user->isAllowed( $action ) ) {
1270 $return = null;
1271 $groups = array();
1272 global $wgGroupPermissions;
1273 foreach( $wgGroupPermissions as $key => $value ) {
1274 if( isset( $value[$action] ) && $value[$action] == true ) {
1275 $groupName = User::getGroupName( $key );
1276 $groupPage = User::getGroupPage( $key );
1277 if( $groupPage ) {
1278 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1279 } else {
1280 $groups[] = $groupName;
1284 $n = count( $groups );
1285 $groups = implode( ', ', $groups );
1286 switch( $n ) {
1287 case 0:
1288 case 1:
1289 case 2:
1290 $return = array( "badaccess-group$n", $groups );
1291 break;
1292 default:
1293 $return = array( 'badaccess-groups', $groups );
1295 $errors[] = $return;
1298 wfProfileOut( __METHOD__ );
1299 return $errors;
1303 * Is this title subject to title protection?
1304 * @return mixed An associative array representing any existent title
1305 * protection, or false if there's none.
1307 private function getTitleProtection() {
1308 // Can't protect pages in special namespaces
1309 if ( $this->getNamespace() < 0 ) {
1310 return false;
1313 $dbr = wfGetDB( DB_SLAVE );
1314 $res = $dbr->select( 'protected_titles', '*',
1315 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1317 if ($row = $dbr->fetchRow( $res )) {
1318 return $row;
1319 } else {
1320 return false;
1324 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1325 global $wgGroupPermissions,$wgUser,$wgContLang;
1327 if ($create_perm == implode(',',$this->getRestrictions('create'))
1328 && $expiry == $this->mRestrictionsExpiry) {
1329 // No change
1330 return true;
1333 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1335 $dbw = wfGetDB( DB_MASTER );
1337 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1339 $expiry_description = '';
1340 if ( $encodedExpiry != 'infinity' ) {
1341 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1344 # Update protection table
1345 if ($create_perm != '' ) {
1346 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1347 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1348 , 'pt_create_perm' => $create_perm
1349 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1350 , 'pt_expiry' => $encodedExpiry
1351 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1352 } else {
1353 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1354 'pt_title' => $title ), __METHOD__ );
1356 # Update the protection log
1357 $log = new LogPage( 'protect' );
1359 if( $create_perm ) {
1360 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1361 } else {
1362 $log->addEntry( 'unprotect', $this, $reason );
1365 return true;
1369 * Remove any title protection (due to page existing
1371 public function deleteTitleProtection() {
1372 $dbw = wfGetDB( DB_MASTER );
1374 $dbw->delete( 'protected_titles',
1375 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1379 * Can $wgUser edit this page?
1380 * @return boolean
1381 * @deprecated use userCan('edit')
1383 public function userCanEdit( $doExpensiveQueries = true ) {
1384 return $this->userCan( 'edit', $doExpensiveQueries );
1388 * Can $wgUser create this page?
1389 * @return boolean
1390 * @deprecated use userCan('create')
1392 public function userCanCreate( $doExpensiveQueries = true ) {
1393 return $this->userCan( 'create', $doExpensiveQueries );
1397 * Can $wgUser move this page?
1398 * @return boolean
1399 * @deprecated use userCan('move')
1401 public function userCanMove( $doExpensiveQueries = true ) {
1402 return $this->userCan( 'move', $doExpensiveQueries );
1406 * Would anybody with sufficient privileges be able to move this page?
1407 * Some pages just aren't movable.
1409 * @return boolean
1411 public function isMovable() {
1412 return MWNamespace::isMovable( $this->getNamespace() )
1413 && $this->getInterwiki() == '';
1417 * Can $wgUser read this page?
1418 * @return boolean
1419 * @todo fold these checks into userCan()
1421 public function userCanRead() {
1422 global $wgUser, $wgGroupPermissions;
1424 $result = null;
1425 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1426 if ( $result !== null ) {
1427 return $result;
1430 # Shortcut for public wikis, allows skipping quite a bit of code
1431 if ($wgGroupPermissions['*']['read'])
1432 return true;
1434 if( $wgUser->isAllowed( 'read' ) ) {
1435 return true;
1436 } else {
1437 global $wgWhitelistRead;
1440 * Always grant access to the login page.
1441 * Even anons need to be able to log in.
1443 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1444 return true;
1448 * Bail out if there isn't whitelist
1450 if( !is_array($wgWhitelistRead) ) {
1451 return false;
1455 * Check for explicit whitelisting
1457 $name = $this->getPrefixedText();
1458 $dbName = $this->getPrefixedDBKey();
1459 // Check with and without underscores
1460 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1461 return true;
1464 * Old settings might have the title prefixed with
1465 * a colon for main-namespace pages
1467 if( $this->getNamespace() == NS_MAIN ) {
1468 if( in_array( ':' . $name, $wgWhitelistRead ) )
1469 return true;
1473 * If it's a special page, ditch the subpage bit
1474 * and check again
1476 if( $this->getNamespace() == NS_SPECIAL ) {
1477 $name = $this->getDBkey();
1478 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1479 if ( $name === false ) {
1480 # Invalid special page, but we show standard login required message
1481 return false;
1484 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1485 if( in_array( $pure, $wgWhitelistRead, true ) )
1486 return true;
1490 return false;
1494 * Is this a talk page of some sort?
1495 * @return bool
1497 public function isTalkPage() {
1498 return MWNamespace::isTalk( $this->getNamespace() );
1502 * Is this a subpage?
1503 * @return bool
1505 public function isSubpage() {
1506 return MWNamespace::hasSubpages( $this->mNamespace )
1507 ? strpos( $this->getText(), '/' ) !== false
1508 : false;
1512 * Does this have subpages? (Warning, usually requires an extra DB query.)
1513 * @return bool
1515 public function hasSubpages() {
1516 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1517 # Duh
1518 return false;
1521 # We dynamically add a member variable for the purpose of this method
1522 # alone to cache the result. There's no point in having it hanging
1523 # around uninitialized in every Title object; therefore we only add it
1524 # if needed and don't declare it statically.
1525 if( isset( $this->mHasSubpages ) ) {
1526 return $this->mHasSubpages;
1529 $db = wfGetDB( DB_SLAVE );
1530 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1531 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1532 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1533 __METHOD__
1538 * Could this page contain custom CSS or JavaScript, based
1539 * on the title?
1541 * @return bool
1543 public function isCssOrJsPage() {
1544 return $this->mNamespace == NS_MEDIAWIKI
1545 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1549 * Is this a .css or .js subpage of a user page?
1550 * @return bool
1552 public function isCssJsSubpage() {
1553 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1556 * Is this a *valid* .css or .js subpage of a user page?
1557 * Check that the corresponding skin exists
1559 public function isValidCssJsSubpage() {
1560 if ( $this->isCssJsSubpage() ) {
1561 $skinNames = Skin::getSkinNames();
1562 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1563 } else {
1564 return false;
1568 * Trim down a .css or .js subpage title to get the corresponding skin name
1570 public function getSkinFromCssJsSubpage() {
1571 $subpage = explode( '/', $this->mTextform );
1572 $subpage = $subpage[ count( $subpage ) - 1 ];
1573 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1576 * Is this a .css subpage of a user page?
1577 * @return bool
1579 public function isCssSubpage() {
1580 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1583 * Is this a .js subpage of a user page?
1584 * @return bool
1586 public function isJsSubpage() {
1587 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1590 * Protect css/js subpages of user pages: can $wgUser edit
1591 * this page?
1593 * @return boolean
1594 * @todo XXX: this might be better using restrictions
1596 public function userCanEditCssJsSubpage() {
1597 global $wgUser;
1598 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1602 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1604 * @return bool If the page is subject to cascading restrictions.
1606 public function isCascadeProtected() {
1607 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1608 return ( $sources > 0 );
1612 * Cascading protection: Get the source of any cascading restrictions on this page.
1614 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1615 * @return array( mixed title array, restriction array)
1616 * 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.
1617 * The restriction array is an array of each type, each of which contains an array of unique groups
1619 public function getCascadeProtectionSources( $get_pages = true ) {
1620 global $wgRestrictionTypes;
1622 # Define our dimension of restrictions types
1623 $pagerestrictions = array();
1624 foreach( $wgRestrictionTypes as $action )
1625 $pagerestrictions[$action] = array();
1627 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1628 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1629 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1630 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1633 wfProfileIn( __METHOD__ );
1635 $dbr = wfGetDb( DB_SLAVE );
1637 if ( $this->getNamespace() == NS_IMAGE ) {
1638 $tables = array ('imagelinks', 'page_restrictions');
1639 $where_clauses = array(
1640 'il_to' => $this->getDBkey(),
1641 'il_from=pr_page',
1642 'pr_cascade' => 1 );
1643 } else {
1644 $tables = array ('templatelinks', 'page_restrictions');
1645 $where_clauses = array(
1646 'tl_namespace' => $this->getNamespace(),
1647 'tl_title' => $this->getDBkey(),
1648 'tl_from=pr_page',
1649 'pr_cascade' => 1 );
1652 if ( $get_pages ) {
1653 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1654 $where_clauses[] = 'page_id=pr_page';
1655 $tables[] = 'page';
1656 } else {
1657 $cols = array( 'pr_expiry' );
1660 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1662 $sources = $get_pages ? array() : false;
1663 $now = wfTimestampNow();
1664 $purgeExpired = false;
1666 while( $row = $dbr->fetchObject( $res ) ) {
1667 $expiry = Block::decodeExpiry( $row->pr_expiry );
1668 if( $expiry > $now ) {
1669 if ($get_pages) {
1670 $page_id = $row->pr_page;
1671 $page_ns = $row->page_namespace;
1672 $page_title = $row->page_title;
1673 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1674 # Add groups needed for each restriction type if its not already there
1675 # Make sure this restriction type still exists
1676 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1677 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1679 } else {
1680 $sources = true;
1682 } else {
1683 // Trigger lazy purge of expired restrictions from the db
1684 $purgeExpired = true;
1687 if( $purgeExpired ) {
1688 Title::purgeExpiredRestrictions();
1691 wfProfileOut( __METHOD__ );
1693 if ( $get_pages ) {
1694 $this->mCascadeSources = $sources;
1695 $this->mCascadingRestrictions = $pagerestrictions;
1696 } else {
1697 $this->mHasCascadingRestrictions = $sources;
1700 return array( $sources, $pagerestrictions );
1703 function areRestrictionsCascading() {
1704 if (!$this->mRestrictionsLoaded) {
1705 $this->loadRestrictions();
1708 return $this->mCascadeRestriction;
1712 * Loads a string into mRestrictions array
1713 * @param resource $res restrictions as an SQL result.
1715 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1716 global $wgRestrictionTypes;
1717 $dbr = wfGetDB( DB_SLAVE );
1719 foreach( $wgRestrictionTypes as $type ){
1720 $this->mRestrictions[$type] = array();
1723 $this->mCascadeRestriction = false;
1724 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1726 # Backwards-compatibility: also load the restrictions from the page record (old format).
1728 if ( $oldFashionedRestrictions === NULL ) {
1729 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1730 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1733 if ($oldFashionedRestrictions != '') {
1735 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1736 $temp = explode( '=', trim( $restrict ) );
1737 if(count($temp) == 1) {
1738 // old old format should be treated as edit/move restriction
1739 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1740 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1741 } else {
1742 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1746 $this->mOldRestrictions = true;
1750 if( $dbr->numRows( $res ) ) {
1751 # Current system - load second to make them override.
1752 $now = wfTimestampNow();
1753 $purgeExpired = false;
1755 while ($row = $dbr->fetchObject( $res ) ) {
1756 # Cycle through all the restrictions.
1758 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1759 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1760 continue;
1762 // This code should be refactored, now that it's being used more generally,
1763 // But I don't really see any harm in leaving it in Block for now -werdna
1764 $expiry = Block::decodeExpiry( $row->pr_expiry );
1766 // Only apply the restrictions if they haven't expired!
1767 if ( !$expiry || $expiry > $now ) {
1768 $this->mRestrictionsExpiry = $expiry;
1769 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1771 $this->mCascadeRestriction |= $row->pr_cascade;
1772 } else {
1773 // Trigger a lazy purge of expired restrictions
1774 $purgeExpired = true;
1778 if( $purgeExpired ) {
1779 Title::purgeExpiredRestrictions();
1783 $this->mRestrictionsLoaded = true;
1786 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1787 if( !$this->mRestrictionsLoaded ) {
1788 if ($this->exists()) {
1789 $dbr = wfGetDB( DB_SLAVE );
1791 $res = $dbr->select( 'page_restrictions', '*',
1792 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1794 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1795 } else {
1796 $title_protection = $this->getTitleProtection();
1798 if (is_array($title_protection)) {
1799 extract($title_protection);
1801 $now = wfTimestampNow();
1802 $expiry = Block::decodeExpiry($pt_expiry);
1804 if (!$expiry || $expiry > $now) {
1805 // Apply the restrictions
1806 $this->mRestrictionsExpiry = $expiry;
1807 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1808 } else { // Get rid of the old restrictions
1809 Title::purgeExpiredRestrictions();
1811 } else {
1812 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1814 $this->mRestrictionsLoaded = true;
1820 * Purge expired restrictions from the page_restrictions table
1822 static function purgeExpiredRestrictions() {
1823 $dbw = wfGetDB( DB_MASTER );
1824 $dbw->delete( 'page_restrictions',
1825 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1826 __METHOD__ );
1828 $dbw->delete( 'protected_titles',
1829 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1830 __METHOD__ );
1834 * Accessor/initialisation for mRestrictions
1836 * @param string $action action that permission needs to be checked for
1837 * @return array the array of groups allowed to edit this article
1839 public function getRestrictions( $action ) {
1840 if( !$this->mRestrictionsLoaded ) {
1841 $this->loadRestrictions();
1843 return isset( $this->mRestrictions[$action] )
1844 ? $this->mRestrictions[$action]
1845 : array();
1849 * Is there a version of this page in the deletion archive?
1850 * @return int the number of archived revisions
1852 public function isDeleted() {
1853 $fname = 'Title::isDeleted';
1854 if ( $this->getNamespace() < 0 ) {
1855 $n = 0;
1856 } else {
1857 $dbr = wfGetDB( DB_SLAVE );
1858 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1859 'ar_title' => $this->getDBkey() ), $fname );
1860 if( $this->getNamespace() == NS_IMAGE ) {
1861 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1862 array( 'fa_name' => $this->getDBkey() ), $fname );
1865 return (int)$n;
1869 * Get the article ID for this Title from the link cache,
1870 * adding it if necessary
1871 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1872 * for update
1873 * @return int the ID
1875 public function getArticleID( $flags = 0 ) {
1876 $linkCache = LinkCache::singleton();
1877 if ( $flags & GAID_FOR_UPDATE ) {
1878 $oldUpdate = $linkCache->forUpdate( true );
1879 $this->mArticleID = $linkCache->addLinkObj( $this );
1880 $linkCache->forUpdate( $oldUpdate );
1881 } else {
1882 if ( -1 == $this->mArticleID ) {
1883 $this->mArticleID = $linkCache->addLinkObj( $this );
1886 return $this->mArticleID;
1890 * Is this an article that is a redirect page?
1891 * Uses link cache, adding it if necessary
1892 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1893 * @return bool
1895 public function isRedirect( $flags = 0 ) {
1896 if( !is_null($this->mRedirect) )
1897 return $this->mRedirect;
1898 # Zero for special pages.
1899 # Also, calling getArticleID() loads the field from cache!
1900 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1901 return false;
1903 $linkCache = LinkCache::singleton();
1904 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1906 return $this->mRedirect;
1910 * What is the length of this page?
1911 * Uses link cache, adding it if necessary
1912 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1913 * @return bool
1915 public function getLength( $flags = 0 ) {
1916 if( $this->mLength != -1 )
1917 return $this->mLength;
1918 # Zero for special pages.
1919 # Also, calling getArticleID() loads the field from cache!
1920 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1921 return 0;
1923 $linkCache = LinkCache::singleton();
1924 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1926 return $this->mLength;
1930 * What is the page_latest field for this page?
1931 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1932 * @return int
1934 public function getLatestRevID( $flags = 0 ) {
1935 if ($this->mLatestID !== false)
1936 return $this->mLatestID;
1938 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1939 return $this->mLatestID = $db->selectField( 'revision',
1940 "max(rev_id)",
1941 array('rev_page' => $this->getArticleID($flags)),
1942 'Title::getLatestRevID' );
1946 * This clears some fields in this object, and clears any associated
1947 * keys in the "bad links" section of the link cache.
1949 * - This is called from Article::insertNewArticle() to allow
1950 * loading of the new page_id. It's also called from
1951 * Article::doDeleteArticle()
1953 * @param int $newid the new Article ID
1955 public function resetArticleID( $newid ) {
1956 $linkCache = LinkCache::singleton();
1957 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1959 if ( 0 == $newid ) { $this->mArticleID = -1; }
1960 else { $this->mArticleID = $newid; }
1961 $this->mRestrictionsLoaded = false;
1962 $this->mRestrictions = array();
1966 * Updates page_touched for this page; called from LinksUpdate.php
1967 * @return bool true if the update succeded
1969 public function invalidateCache() {
1970 global $wgUseFileCache;
1972 if ( wfReadOnly() ) {
1973 return;
1976 $dbw = wfGetDB( DB_MASTER );
1977 $success = $dbw->update( 'page',
1978 array( /* SET */
1979 'page_touched' => $dbw->timestamp()
1980 ), array( /* WHERE */
1981 'page_namespace' => $this->getNamespace() ,
1982 'page_title' => $this->getDBkey()
1983 ), 'Title::invalidateCache'
1986 if ($wgUseFileCache) {
1987 $cache = new HTMLFileCache($this);
1988 @unlink($cache->fileCacheName());
1991 return $success;
1995 * Prefix some arbitrary text with the namespace or interwiki prefix
1996 * of this object
1998 * @param string $name the text
1999 * @return string the prefixed text
2000 * @private
2002 /* private */ function prefix( $name ) {
2003 $p = '';
2004 if ( '' != $this->mInterwiki ) {
2005 $p = $this->mInterwiki . ':';
2007 if ( 0 != $this->mNamespace ) {
2008 $p .= $this->getNsText() . ':';
2010 return $p . $name;
2014 * Secure and split - main initialisation function for this object
2016 * Assumes that mDbkeyform has been set, and is urldecoded
2017 * and uses underscores, but not otherwise munged. This function
2018 * removes illegal characters, splits off the interwiki and
2019 * namespace prefixes, sets the other forms, and canonicalizes
2020 * everything.
2021 * @return bool true on success
2023 private function secureAndSplit() {
2024 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2026 # Initialisation
2027 static $rxTc = false;
2028 if( !$rxTc ) {
2029 # Matching titles will be held as illegal.
2030 $rxTc = '/' .
2031 # Any character not allowed is forbidden...
2032 '[^' . Title::legalChars() . ']' .
2033 # URL percent encoding sequences interfere with the ability
2034 # to round-trip titles -- you can't link to them consistently.
2035 '|%[0-9A-Fa-f]{2}' .
2036 # XML/HTML character references produce similar issues.
2037 '|&[A-Za-z0-9\x80-\xff]+;' .
2038 '|&#[0-9]+;' .
2039 '|&#x[0-9A-Fa-f]+;' .
2040 '/S';
2043 $this->mInterwiki = $this->mFragment = '';
2044 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2046 $dbkey = $this->mDbkeyform;
2048 # Strip Unicode bidi override characters.
2049 # Sometimes they slip into cut-n-pasted page titles, where the
2050 # override chars get included in list displays.
2051 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2052 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2054 # Clean up whitespace
2056 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2057 $dbkey = trim( $dbkey, '_' );
2059 if ( '' == $dbkey ) {
2060 return false;
2063 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2064 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2065 return false;
2068 $this->mDbkeyform = $dbkey;
2070 # Initial colon indicates main namespace rather than specified default
2071 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2072 if ( ':' == $dbkey{0} ) {
2073 $this->mNamespace = NS_MAIN;
2074 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2075 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2078 # Namespace or interwiki prefix
2079 $firstPass = true;
2080 do {
2081 $m = array();
2082 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2083 $p = $m[1];
2084 if ( $ns = $wgContLang->getNsIndex( $p )) {
2085 # Ordinary namespace
2086 $dbkey = $m[2];
2087 $this->mNamespace = $ns;
2088 } elseif( $this->getInterwikiLink( $p ) ) {
2089 if( !$firstPass ) {
2090 # Can't make a local interwiki link to an interwiki link.
2091 # That's just crazy!
2092 return false;
2095 # Interwiki link
2096 $dbkey = $m[2];
2097 $this->mInterwiki = $wgContLang->lc( $p );
2099 # Redundant interwiki prefix to the local wiki
2100 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2101 if( $dbkey == '' ) {
2102 # Can't have an empty self-link
2103 return false;
2105 $this->mInterwiki = '';
2106 $firstPass = false;
2107 # Do another namespace split...
2108 continue;
2111 # If there's an initial colon after the interwiki, that also
2112 # resets the default namespace
2113 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2114 $this->mNamespace = NS_MAIN;
2115 $dbkey = substr( $dbkey, 1 );
2118 # If there's no recognized interwiki or namespace,
2119 # then let the colon expression be part of the title.
2121 break;
2122 } while( true );
2124 # We already know that some pages won't be in the database!
2126 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2127 $this->mArticleID = 0;
2129 $fragment = strstr( $dbkey, '#' );
2130 if ( false !== $fragment ) {
2131 $this->setFragment( $fragment );
2132 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2133 # remove whitespace again: prevents "Foo_bar_#"
2134 # becoming "Foo_bar_"
2135 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2138 # Reject illegal characters.
2140 if( preg_match( $rxTc, $dbkey ) ) {
2141 return false;
2145 * Pages with "/./" or "/../" appearing in the URLs will
2146 * often be unreachable due to the way web browsers deal
2147 * with 'relative' URLs. Forbid them explicitly.
2149 if ( strpos( $dbkey, '.' ) !== false &&
2150 ( $dbkey === '.' || $dbkey === '..' ||
2151 strpos( $dbkey, './' ) === 0 ||
2152 strpos( $dbkey, '../' ) === 0 ||
2153 strpos( $dbkey, '/./' ) !== false ||
2154 strpos( $dbkey, '/../' ) !== false ||
2155 substr( $dbkey, -2 ) == '/.' ||
2156 substr( $dbkey, -3 ) == '/..' ) )
2158 return false;
2162 * Magic tilde sequences? Nu-uh!
2164 if( strpos( $dbkey, '~~~' ) !== false ) {
2165 return false;
2169 * Limit the size of titles to 255 bytes.
2170 * This is typically the size of the underlying database field.
2171 * We make an exception for special pages, which don't need to be stored
2172 * in the database, and may edge over 255 bytes due to subpage syntax
2173 * for long titles, e.g. [[Special:Block/Long name]]
2175 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2176 strlen( $dbkey ) > 512 )
2178 return false;
2182 * Normally, all wiki links are forced to have
2183 * an initial capital letter so [[foo]] and [[Foo]]
2184 * point to the same place.
2186 * Don't force it for interwikis, since the other
2187 * site might be case-sensitive.
2189 $this->mUserCaseDBKey = $dbkey;
2190 if( $wgCapitalLinks && $this->mInterwiki == '') {
2191 $dbkey = $wgContLang->ucfirst( $dbkey );
2195 * Can't make a link to a namespace alone...
2196 * "empty" local links can only be self-links
2197 * with a fragment identifier.
2199 if( $dbkey == '' &&
2200 $this->mInterwiki == '' &&
2201 $this->mNamespace != NS_MAIN ) {
2202 return false;
2204 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2205 // IP names are not allowed for accounts, and can only be referring to
2206 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2207 // there are numerous ways to present the same IP. Having sp:contribs scan
2208 // them all is silly and having some show the edits and others not is
2209 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2210 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2211 IP::sanitizeIP( $dbkey ) : $dbkey;
2212 // Any remaining initial :s are illegal.
2213 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2214 return false;
2217 # Fill fields
2218 $this->mDbkeyform = $dbkey;
2219 $this->mUrlform = wfUrlencode( $dbkey );
2221 $this->mTextform = str_replace( '_', ' ', $dbkey );
2223 return true;
2227 * Set the fragment for this title
2228 * This is kind of bad, since except for this rarely-used function, Title objects
2229 * are immutable. The reason this is here is because it's better than setting the
2230 * members directly, which is what Linker::formatComment was doing previously.
2232 * @param string $fragment text
2233 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2235 public function setFragment( $fragment ) {
2236 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2240 * Get a Title object associated with the talk page of this article
2241 * @return Title the object for the talk page
2243 public function getTalkPage() {
2244 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2248 * Get a title object associated with the subject page of this
2249 * talk page
2251 * @return Title the object for the subject page
2253 public function getSubjectPage() {
2254 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2258 * Get an array of Title objects linking to this Title
2259 * Also stores the IDs in the link cache.
2261 * WARNING: do not use this function on arbitrary user-supplied titles!
2262 * On heavily-used templates it will max out the memory.
2264 * @param string $options may be FOR UPDATE
2265 * @return array the Title objects linking here
2267 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2268 $linkCache = LinkCache::singleton();
2270 if ( $options ) {
2271 $db = wfGetDB( DB_MASTER );
2272 } else {
2273 $db = wfGetDB( DB_SLAVE );
2276 $res = $db->select( array( 'page', $table ),
2277 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2278 array(
2279 "{$prefix}_from=page_id",
2280 "{$prefix}_namespace" => $this->getNamespace(),
2281 "{$prefix}_title" => $this->getDBkey() ),
2282 'Title::getLinksTo',
2283 $options );
2285 $retVal = array();
2286 if ( $db->numRows( $res ) ) {
2287 while ( $row = $db->fetchObject( $res ) ) {
2288 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2289 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2290 $retVal[] = $titleObj;
2294 $db->freeResult( $res );
2295 return $retVal;
2299 * Get an array of Title objects using this Title as a template
2300 * Also stores the IDs in the link cache.
2302 * WARNING: do not use this function on arbitrary user-supplied titles!
2303 * On heavily-used templates it will max out the memory.
2305 * @param string $options may be FOR UPDATE
2306 * @return array the Title objects linking here
2308 public function getTemplateLinksTo( $options = '' ) {
2309 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2313 * Get an array of Title objects referring to non-existent articles linked from this page
2315 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2316 * @param string $options may be FOR UPDATE
2317 * @return array the Title objects
2319 public function getBrokenLinksFrom( $options = '' ) {
2320 if ( $this->getArticleId() == 0 ) {
2321 # All links from article ID 0 are false positives
2322 return array();
2325 if ( $options ) {
2326 $db = wfGetDB( DB_MASTER );
2327 } else {
2328 $db = wfGetDB( DB_SLAVE );
2331 $res = $db->safeQuery(
2332 "SELECT pl_namespace, pl_title
2333 FROM !
2334 LEFT JOIN !
2335 ON pl_namespace=page_namespace
2336 AND pl_title=page_title
2337 WHERE pl_from=?
2338 AND page_namespace IS NULL
2340 $db->tableName( 'pagelinks' ),
2341 $db->tableName( 'page' ),
2342 $this->getArticleId(),
2343 $options );
2345 $retVal = array();
2346 if ( $db->numRows( $res ) ) {
2347 while ( $row = $db->fetchObject( $res ) ) {
2348 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2351 $db->freeResult( $res );
2352 return $retVal;
2357 * Get a list of URLs to purge from the Squid cache when this
2358 * page changes
2360 * @return array the URLs
2362 public function getSquidURLs() {
2363 global $wgContLang;
2365 $urls = array(
2366 $this->getInternalURL(),
2367 $this->getInternalURL( 'action=history' )
2370 // purge variant urls as well
2371 if($wgContLang->hasVariants()){
2372 $variants = $wgContLang->getVariants();
2373 foreach($variants as $vCode){
2374 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2375 $urls[] = $this->getInternalURL('',$vCode);
2379 return $urls;
2382 public function purgeSquid() {
2383 global $wgUseSquid;
2384 if ( $wgUseSquid ) {
2385 $urls = $this->getSquidURLs();
2386 $u = new SquidUpdate( $urls );
2387 $u->doUpdate();
2392 * Move this page without authentication
2393 * @param Title &$nt the new page Title
2395 public function moveNoAuth( &$nt ) {
2396 return $this->moveTo( $nt, false );
2400 * Check whether a given move operation would be valid.
2401 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2402 * @param Title &$nt the new title
2403 * @param bool $auth indicates whether $wgUser's permissions
2404 * should be checked
2405 * @param string $reason is the log summary of the move, used for spam checking
2406 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2408 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2409 $errors = array();
2410 if( !$nt ) {
2411 // Normally we'd add this to $errors, but we'll get
2412 // lots of syntax errors if $nt is not an object
2413 return array(array('badtitletext'));
2415 if( $this->equals( $nt ) ) {
2416 $errors[] = array('selfmove');
2418 if( !$this->isMovable() || !$nt->isMovable() ) {
2419 $errors[] = array('immobile_namespace');
2422 $oldid = $this->getArticleID();
2423 $newid = $nt->getArticleID();
2425 if ( strlen( $nt->getDBkey() ) < 1 ) {
2426 $errors[] = array('articleexists');
2428 if ( ( '' == $this->getDBkey() ) ||
2429 ( !$oldid ) ||
2430 ( '' == $nt->getDBkey() ) ) {
2431 $errors[] = array('badarticleerror');
2434 // Image-specific checks
2435 if( $this->getNamespace() == NS_IMAGE ) {
2436 $file = wfLocalFile( $this );
2437 if( $file->exists() ) {
2438 if( $nt->getNamespace() != NS_IMAGE ) {
2439 $errors[] = array('imagenocrossnamespace');
2441 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2442 $errors[] = array('imageinvalidfilename');
2444 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2445 $errors[] = array('imagetypemismatch');
2450 if ( $auth ) {
2451 global $wgUser;
2452 $errors = array_merge($errors,
2453 $this->getUserPermissionsErrors('move', $wgUser),
2454 $this->getUserPermissionsErrors('edit', $wgUser),
2455 $nt->getUserPermissionsErrors('move', $wgUser),
2456 $nt->getUserPermissionsErrors('edit', $wgUser));
2459 global $wgUser;
2460 $err = null;
2461 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2462 $errors[] = array('hookaborted', $err);
2465 # The move is allowed only if (1) the target doesn't exist, or
2466 # (2) the target is a redirect to the source, and has no history
2467 # (so we can undo bad moves right after they're done).
2469 if ( 0 != $newid ) { # Target exists; check for validity
2470 if ( ! $this->isValidMoveTarget( $nt ) ) {
2471 $errors[] = array('articleexists');
2473 } else {
2474 $tp = $nt->getTitleProtection();
2475 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2476 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2477 $errors[] = array('cantmove-titleprotected');
2480 if(empty($errors))
2481 return true;
2482 return $errors;
2486 * Move a title to a new location
2487 * @param Title &$nt the new title
2488 * @param bool $auth indicates whether $wgUser's permissions
2489 * should be checked
2490 * @param string $reason The reason for the move
2491 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2492 * Ignored if the user doesn't have the suppressredirect right.
2493 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2495 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2496 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2497 if( is_array( $err ) ) {
2498 return $err;
2501 $pageid = $this->getArticleID();
2502 if( $nt->exists() ) {
2503 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2504 $pageCountChange = ($createRedirect ? 0 : -1);
2505 } else { # Target didn't exist, do normal move.
2506 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2507 $pageCountChange = ($createRedirect ? 1 : 0);
2510 if( is_array( $err ) ) {
2511 return $err;
2513 $redirid = $this->getArticleID();
2515 // Category memberships include a sort key which may be customized.
2516 // If it's left as the default (the page title), we need to update
2517 // the sort key to match the new title.
2519 // Be careful to avoid resetting cl_timestamp, which may disturb
2520 // time-based lists on some sites.
2522 // Warning -- if the sort key is *explicitly* set to the old title,
2523 // we can't actually distinguish it from a default here, and it'll
2524 // be set to the new title even though it really shouldn't.
2525 // It'll get corrected on the next edit, but resetting cl_timestamp.
2526 $dbw = wfGetDB( DB_MASTER );
2527 $dbw->update( 'categorylinks',
2528 array(
2529 'cl_sortkey' => $nt->getPrefixedText(),
2530 'cl_timestamp=cl_timestamp' ),
2531 array(
2532 'cl_from' => $pageid,
2533 'cl_sortkey' => $this->getPrefixedText() ),
2534 __METHOD__ );
2536 # Update watchlists
2538 $oldnamespace = $this->getNamespace() & ~1;
2539 $newnamespace = $nt->getNamespace() & ~1;
2540 $oldtitle = $this->getDBkey();
2541 $newtitle = $nt->getDBkey();
2543 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2544 WatchedItem::duplicateEntries( $this, $nt );
2547 # Update search engine
2548 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2549 $u->doUpdate();
2550 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2551 $u->doUpdate();
2553 # Update site_stats
2554 if( $this->isContentPage() && !$nt->isContentPage() ) {
2555 # No longer a content page
2556 # Not viewed, edited, removing
2557 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2558 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2559 # Now a content page
2560 # Not viewed, edited, adding
2561 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2562 } elseif( $pageCountChange ) {
2563 # Redirect added
2564 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2565 } else {
2566 # Nothing special
2567 $u = false;
2569 if( $u )
2570 $u->doUpdate();
2571 # Update message cache for interface messages
2572 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2573 global $wgMessageCache;
2574 $oldarticle = new Article( $this );
2575 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2576 $newarticle = new Article( $nt );
2577 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2580 global $wgUser;
2581 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2582 return true;
2586 * Move page to a title which is at present a redirect to the
2587 * source page
2589 * @param Title &$nt the page to move to, which should currently
2590 * be a redirect
2591 * @param string $reason The reason for the move
2592 * @param bool $createRedirect Whether to leave a redirect at the old title.
2593 * Ignored if the user doesn't have the suppressredirect right
2595 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2596 global $wgUseSquid, $wgUser;
2597 $fname = 'Title::moveOverExistingRedirect';
2598 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2600 if ( $reason ) {
2601 $comment .= ": $reason";
2604 $now = wfTimestampNow();
2605 $newid = $nt->getArticleID();
2606 $oldid = $this->getArticleID();
2608 $dbw = wfGetDB( DB_MASTER );
2609 $dbw->begin();
2611 # Delete the old redirect. We don't save it to history since
2612 # by definition if we've got here it's rather uninteresting.
2613 # We have to remove it so that the next step doesn't trigger
2614 # a conflict on the unique namespace+title index...
2615 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2616 if ( !$dbw->cascadingDeletes() ) {
2617 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2618 global $wgUseTrackbacks;
2619 if ($wgUseTrackbacks)
2620 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2621 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2622 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2623 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2624 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2625 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2626 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2627 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2630 # Save a null revision in the page's history notifying of the move
2631 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2632 $nullRevId = $nullRevision->insertOn( $dbw );
2634 $article = new Article( $this );
2635 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
2637 # Change the name of the target page:
2638 $dbw->update( 'page',
2639 /* SET */ array(
2640 'page_touched' => $dbw->timestamp($now),
2641 'page_namespace' => $nt->getNamespace(),
2642 'page_title' => $nt->getDBkey(),
2643 'page_latest' => $nullRevId,
2645 /* WHERE */ array( 'page_id' => $oldid ),
2646 $fname
2648 $nt->resetArticleID( $oldid );
2650 # Recreate the redirect, this time in the other direction.
2651 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2652 $mwRedir = MagicWord::get( 'redirect' );
2653 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2654 $redirectArticle = new Article( $this );
2655 $newid = $redirectArticle->insertOn( $dbw );
2656 $redirectRevision = new Revision( array(
2657 'page' => $newid,
2658 'comment' => $comment,
2659 'text' => $redirectText ) );
2660 $redirectRevision->insertOn( $dbw );
2661 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2663 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2665 # Now, we record the link from the redirect to the new title.
2666 # It should have no other outgoing links...
2667 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2668 $dbw->insert( 'pagelinks',
2669 array(
2670 'pl_from' => $newid,
2671 'pl_namespace' => $nt->getNamespace(),
2672 'pl_title' => $nt->getDBkey() ),
2673 $fname );
2674 } else {
2675 $this->resetArticleID( 0 );
2678 # Move an image if this is a file
2679 if( $this->getNamespace() == NS_IMAGE ) {
2680 $file = wfLocalFile( $this );
2681 if( $file->exists() ) {
2682 $status = $file->move( $nt );
2683 if( !$status->isOk() ) {
2684 $dbw->rollback();
2685 return $status->getErrorsArray();
2689 $dbw->commit();
2691 # Log the move
2692 $log = new LogPage( 'move' );
2693 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2695 # Purge squid
2696 if ( $wgUseSquid ) {
2697 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2698 $u = new SquidUpdate( $urls );
2699 $u->doUpdate();
2705 * Move page to non-existing title.
2706 * @param Title &$nt the new Title
2707 * @param string $reason The reason for the move
2708 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2709 * Ignored if the user doesn't have the suppressredirect right
2711 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2712 global $wgUseSquid, $wgUser;
2713 $fname = 'MovePageForm::moveToNewTitle';
2714 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2715 if ( $reason ) {
2716 $comment .= ": $reason";
2719 $newid = $nt->getArticleID();
2720 $oldid = $this->getArticleID();
2722 $dbw = wfGetDB( DB_MASTER );
2723 $dbw->begin();
2724 $now = $dbw->timestamp();
2726 # Save a null revision in the page's history notifying of the move
2727 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2728 $nullRevId = $nullRevision->insertOn( $dbw );
2730 $article = new Article( $this );
2731 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, false) );
2733 # Rename page entry
2734 $dbw->update( 'page',
2735 /* SET */ array(
2736 'page_touched' => $now,
2737 'page_namespace' => $nt->getNamespace(),
2738 'page_title' => $nt->getDBkey(),
2739 'page_latest' => $nullRevId,
2741 /* WHERE */ array( 'page_id' => $oldid ),
2742 $fname
2744 $nt->resetArticleID( $oldid );
2746 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2747 # Insert redirect
2748 $mwRedir = MagicWord::get( 'redirect' );
2749 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2750 $redirectArticle = new Article( $this );
2751 $newid = $redirectArticle->insertOn( $dbw );
2752 $redirectRevision = new Revision( array(
2753 'page' => $newid,
2754 'comment' => $comment,
2755 'text' => $redirectText ) );
2756 $redirectRevision->insertOn( $dbw );
2757 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2759 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2761 # Record the just-created redirect's linking to the page
2762 $dbw->insert( 'pagelinks',
2763 array(
2764 'pl_from' => $newid,
2765 'pl_namespace' => $nt->getNamespace(),
2766 'pl_title' => $nt->getDBkey() ),
2767 $fname );
2768 } else {
2769 $this->resetArticleID( 0 );
2772 # Move an image if this is a file
2773 if( $this->getNamespace() == NS_IMAGE ) {
2774 $file = wfLocalFile( $this );
2775 if( $file->exists() ) {
2776 $status = $file->move( $nt );
2777 if( !$status->isOk() ) {
2778 $dbw->rollback();
2779 return $status->getErrorsArray();
2783 $dbw->commit();
2785 # Log the move
2786 $log = new LogPage( 'move' );
2787 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2789 # Purge caches as per article creation
2790 Article::onArticleCreate( $nt );
2792 # Purge old title from squid
2793 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2794 $this->purgeSquid();
2799 * Checks if $this can be moved to a given Title
2800 * - Selects for update, so don't call it unless you mean business
2802 * @param Title &$nt the new title to check
2804 public function isValidMoveTarget( $nt ) {
2806 $fname = 'Title::isValidMoveTarget';
2807 $dbw = wfGetDB( DB_MASTER );
2809 # Is it an existsing file?
2810 if( $nt->getNamespace() == NS_IMAGE ) {
2811 $file = wfLocalFile( $nt );
2812 if( $file->exists() ) {
2813 wfDebug( __METHOD__ . ": file exists\n" );
2814 return false;
2818 # Is it a redirect?
2819 $id = $nt->getArticleID();
2820 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2821 array( 'page_is_redirect','old_text','old_flags' ),
2822 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2823 $fname, 'FOR UPDATE' );
2825 if ( !$obj || 0 == $obj->page_is_redirect ) {
2826 # Not a redirect
2827 wfDebug( __METHOD__ . ": not a redirect\n" );
2828 return false;
2830 $text = Revision::getRevisionText( $obj );
2832 # Does the redirect point to the source?
2833 # Or is it a broken self-redirect, usually caused by namespace collisions?
2834 $m = array();
2835 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2836 $redirTitle = Title::newFromText( $m[1] );
2837 if( !is_object( $redirTitle ) ||
2838 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2839 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2840 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2841 return false;
2843 } else {
2844 # Fail safe
2845 wfDebug( __METHOD__ . ": failsafe\n" );
2846 return false;
2849 # Does the article have a history?
2850 $row = $dbw->selectRow( array( 'page', 'revision'),
2851 array( 'rev_id' ),
2852 array( 'page_namespace' => $nt->getNamespace(),
2853 'page_title' => $nt->getDBkey(),
2854 'page_id=rev_page AND page_latest != rev_id'
2855 ), $fname, 'FOR UPDATE'
2858 # Return true if there was no history
2859 return $row === false;
2863 * Can this title be added to a user's watchlist?
2865 * @return bool
2867 public function isWatchable() {
2868 return !$this->isExternal()
2869 && MWNamespace::isWatchable( $this->getNamespace() );
2873 * Get categories to which this Title belongs and return an array of
2874 * categories' names.
2876 * @return array an array of parents in the form:
2877 * $parent => $currentarticle
2879 public function getParentCategories() {
2880 global $wgContLang;
2882 $titlekey = $this->getArticleId();
2883 $dbr = wfGetDB( DB_SLAVE );
2884 $categorylinks = $dbr->tableName( 'categorylinks' );
2886 # NEW SQL
2887 $sql = "SELECT * FROM $categorylinks"
2888 ." WHERE cl_from='$titlekey'"
2889 ." AND cl_from <> '0'"
2890 ." ORDER BY cl_sortkey";
2892 $res = $dbr->query( $sql );
2894 if( $dbr->numRows( $res ) > 0 ) {
2895 while( $x = $dbr->fetchObject( $res ) )
2896 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2897 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2898 $dbr->freeResult( $res );
2899 } else {
2900 $data = array();
2902 return $data;
2906 * Get a tree of parent categories
2907 * @param array $children an array with the children in the keys, to check for circular refs
2908 * @return array
2910 public function getParentCategoryTree( $children = array() ) {
2911 $stack = array();
2912 $parents = $this->getParentCategories();
2914 if( $parents ) {
2915 foreach( $parents as $parent => $current ) {
2916 if ( array_key_exists( $parent, $children ) ) {
2917 # Circular reference
2918 $stack[$parent] = array();
2919 } else {
2920 $nt = Title::newFromText($parent);
2921 if ( $nt ) {
2922 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2926 return $stack;
2927 } else {
2928 return array();
2934 * Get an associative array for selecting this title from
2935 * the "page" table
2937 * @return array
2939 public function pageCond() {
2940 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2944 * Get the revision ID of the previous revision
2946 * @param integer $revision Revision ID. Get the revision that was before this one.
2947 * @param integer $flags, GAID_FOR_UPDATE
2948 * @return integer $oldrevision|false
2950 public function getPreviousRevisionID( $revision, $flags=0 ) {
2951 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2952 return $db->selectField( 'revision', 'rev_id',
2953 array(
2954 'rev_page' => $this->getArticleId($flags),
2955 'rev_id < ' . intval( $revision )
2957 __METHOD__,
2958 array( 'ORDER BY' => 'rev_id DESC' )
2963 * Get the revision ID of the next revision
2965 * @param integer $revision Revision ID. Get the revision that was after this one.
2966 * @param integer $flags, GAID_FOR_UPDATE
2967 * @return integer $oldrevision|false
2969 public function getNextRevisionID( $revision, $flags=0 ) {
2970 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
2971 return $db->selectField( 'revision', 'rev_id',
2972 array(
2973 'rev_page' => $this->getArticleId($flags),
2974 'rev_id > ' . intval( $revision )
2976 __METHOD__,
2977 array( 'ORDER BY' => 'rev_id' )
2982 * Get the number of revisions between the given revision IDs.
2983 * Used for diffs and other things that really need it.
2985 * @param integer $old Revision ID.
2986 * @param integer $new Revision ID.
2987 * @return integer Number of revisions between these IDs.
2989 public function countRevisionsBetween( $old, $new ) {
2990 $dbr = wfGetDB( DB_SLAVE );
2991 return $dbr->selectField( 'revision', 'count(*)',
2992 'rev_page = ' . intval( $this->getArticleId() ) .
2993 ' AND rev_id > ' . intval( $old ) .
2994 ' AND rev_id < ' . intval( $new ),
2995 __METHOD__,
2996 array( 'USE INDEX' => 'PRIMARY' ) );
3000 * Compare with another title.
3002 * @param Title $title
3003 * @return bool
3005 public function equals( $title ) {
3006 // Note: === is necessary for proper matching of number-like titles.
3007 return $this->getInterwiki() === $title->getInterwiki()
3008 && $this->getNamespace() == $title->getNamespace()
3009 && $this->getDBkey() === $title->getDBkey();
3013 * Callback for usort() to do title sorts by (namespace, title)
3015 static function compare( $a, $b ) {
3016 if( $a->getNamespace() == $b->getNamespace() ) {
3017 return strcmp( $a->getText(), $b->getText() );
3018 } else {
3019 return $a->getNamespace() - $b->getNamespace();
3024 * Return a string representation of this title
3026 * @return string
3028 public function __toString() {
3029 return $this->getPrefixedText();
3033 * Check if page exists
3034 * @return bool
3036 public function exists() {
3037 return $this->getArticleId() != 0;
3041 * Do we know that this title definitely exists, or should we otherwise
3042 * consider that it exists?
3044 * @return bool
3046 public function isAlwaysKnown() {
3047 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3048 // the full l10n of that language to be loaded. That takes much memory and
3049 // isn't needed. So we strip the language part away.
3050 // Also, extension messages which are not loaded, are shown as red, because
3051 // we don't call MessageCache::loadAllMessages.
3052 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3053 return $this->isExternal()
3054 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3055 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3059 * Update page_touched timestamps and send squid purge messages for
3060 * pages linking to this title. May be sent to the job queue depending
3061 * on the number of links. Typically called on create and delete.
3063 public function touchLinks() {
3064 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3065 $u->doUpdate();
3067 if ( $this->getNamespace() == NS_CATEGORY ) {
3068 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3069 $u->doUpdate();
3074 * Get the last touched timestamp
3076 public function getTouched() {
3077 $dbr = wfGetDB( DB_SLAVE );
3078 $touched = $dbr->selectField( 'page', 'page_touched',
3079 array(
3080 'page_namespace' => $this->getNamespace(),
3081 'page_title' => $this->getDBkey()
3082 ), __METHOD__
3084 return $touched;
3087 public function trackbackURL() {
3088 global $wgTitle, $wgScriptPath, $wgServer;
3090 return "$wgServer$wgScriptPath/trackback.php?article="
3091 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3094 public function trackbackRDF() {
3095 $url = htmlspecialchars($this->getFullURL());
3096 $title = htmlspecialchars($this->getText());
3097 $tburl = $this->trackbackURL();
3099 // Autodiscovery RDF is placed in comments so HTML validator
3100 // won't barf. This is a rather icky workaround, but seems
3101 // frequently used by this kind of RDF thingy.
3103 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3104 return "<!--
3105 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3106 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3107 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3108 <rdf:Description
3109 rdf:about=\"$url\"
3110 dc:identifier=\"$url\"
3111 dc:title=\"$title\"
3112 trackback:ping=\"$tburl\" />
3113 </rdf:RDF>
3114 -->";
3118 * Generate strings used for xml 'id' names in monobook tabs
3119 * @return string
3121 public function getNamespaceKey() {
3122 global $wgContLang;
3123 switch ($this->getNamespace()) {
3124 case NS_MAIN:
3125 case NS_TALK:
3126 return 'nstab-main';
3127 case NS_USER:
3128 case NS_USER_TALK:
3129 return 'nstab-user';
3130 case NS_MEDIA:
3131 return 'nstab-media';
3132 case NS_SPECIAL:
3133 return 'nstab-special';
3134 case NS_PROJECT:
3135 case NS_PROJECT_TALK:
3136 return 'nstab-project';
3137 case NS_IMAGE:
3138 case NS_IMAGE_TALK:
3139 return 'nstab-image';
3140 case NS_MEDIAWIKI:
3141 case NS_MEDIAWIKI_TALK:
3142 return 'nstab-mediawiki';
3143 case NS_TEMPLATE:
3144 case NS_TEMPLATE_TALK:
3145 return 'nstab-template';
3146 case NS_HELP:
3147 case NS_HELP_TALK:
3148 return 'nstab-help';
3149 case NS_CATEGORY:
3150 case NS_CATEGORY_TALK:
3151 return 'nstab-category';
3152 default:
3153 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3158 * Returns true if this title resolves to the named special page
3159 * @param string $name The special page name
3161 public function isSpecial( $name ) {
3162 if ( $this->getNamespace() == NS_SPECIAL ) {
3163 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3164 if ( $name == $thisName ) {
3165 return true;
3168 return false;
3172 * If the Title refers to a special page alias which is not the local default,
3173 * returns a new Title which points to the local default. Otherwise, returns $this.
3175 public function fixSpecialName() {
3176 if ( $this->getNamespace() == NS_SPECIAL ) {
3177 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3178 if ( $canonicalName ) {
3179 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3180 if ( $localName != $this->mDbkeyform ) {
3181 return Title::makeTitle( NS_SPECIAL, $localName );
3185 return $this;
3189 * Is this Title in a namespace which contains content?
3190 * In other words, is this a content page, for the purposes of calculating
3191 * statistics, etc?
3193 * @return bool
3195 public function isContentPage() {
3196 return MWNamespace::isContent( $this->getNamespace() );
3199 public function getRedirectsHere( $ns = null ) {
3200 $redirs = array();
3202 $dbr = wfGetDB( DB_SLAVE );
3203 $where = array(
3204 'rd_namespace' => $this->getNamespace(),
3205 'rd_title' => $this->getDBkey(),
3206 'rd_from = page_id'
3208 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3210 $result = $dbr->select(
3211 array( 'redirect', 'page' ),
3212 array( 'page_namespace', 'page_title' ),
3213 $where,
3214 __METHOD__
3218 while( $row = $dbr->fetchObject( $result ) ) {
3219 $redirs[] = self::newFromRow( $row );
3221 return $redirs;