* (bug 9556) Update Bulgarian translations
[mediawiki.git] / includes / Title.php
blob8a855324575b5d9216ba3fd9b2ebe81b4dd8b875
1 <?php
2 /**
3 * See title.txt
5 */
7 /** */
8 if ( !class_exists( 'UtfNormal' ) ) {
9 require_once( dirname(__FILE__) . '/normal/UtfNormal.php' );
12 define ( 'GAID_FOR_UPDATE', 1 );
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
18 # reset the cache.
19 define( 'MW_TITLECACHE_MAX', 1000 );
21 # Constants for pr_cascade bitfield
22 define( 'CASCADE', 1 );
24 /**
25 * Title class
26 * - Represents a title, which may contain an interwiki designation or namespace
27 * - Can fetch various kinds of data from the database, albeit inefficiently.
30 class Title {
31 /**
32 * Static cache variables
34 static private $titleCache=array();
35 static private $interwikiCache=array();
38 /**
39 * All member variables should be considered private
40 * Please use the accessor functions
43 /**#@+
44 * @private
47 var $mTextform; # Text form (spaces not underscores) of the main part
48 var $mUrlform; # URL-encoded form of the main part
49 var $mDbkeyform; # Main part with underscores
50 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
51 var $mInterwiki; # Interwiki prefix (or null string)
52 var $mFragment; # Title fragment (i.e. the bit after the #)
53 var $mArticleID; # Article ID, fetched from the link cache on demand
54 var $mLatestID; # ID of most recent revision
55 var $mRestrictions; # Array of groups allowed to edit this article
56 var $mCascadeRestriction; # Cascade restrictions on this page to included templates and images?
57 var $mRestrictionsExpiry; # When do the restrictions on this page expire?
58 var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page?
59 var $mCascadeRestrictionSources;# Where are the cascading restrictions coming from on this page?
60 var $mRestrictionsLoaded; # Boolean for initialisation on demand
61 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
62 var $mDefaultNamespace; # Namespace index when there is no namespace
63 # Zero except in {{transclusion}} tags
64 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
65 /**#@-*/
68 /**
69 * Constructor
70 * @private
72 /* private */ function __construct() {
73 $this->mInterwiki = $this->mUrlform =
74 $this->mTextform = $this->mDbkeyform = '';
75 $this->mArticleID = -1;
76 $this->mNamespace = NS_MAIN;
77 $this->mRestrictionsLoaded = false;
78 $this->mRestrictions = array();
79 # Dont change the following, NS_MAIN is hardcoded in several place
80 # See bug #696
81 $this->mDefaultNamespace = NS_MAIN;
82 $this->mWatched = NULL;
83 $this->mLatestID = false;
84 $this->mOldRestrictions = false;
87 /**
88 * Create a new Title from a prefixed DB key
89 * @param string $key The database key, which has underscores
90 * instead of spaces, possibly including namespace and
91 * interwiki prefixes
92 * @return Title the new object, or NULL on an error
93 * @static
94 * @access public
96 /* static */ function newFromDBkey( $key ) {
97 $t = new Title();
98 $t->mDbkeyform = $key;
99 if( $t->secureAndSplit() )
100 return $t;
101 else
102 return NULL;
106 * Create a new Title from text, such as what one would
107 * find in a link. Decodes any HTML entities in the text.
109 * @param string $text the link text; spaces, prefixes,
110 * and an initial ':' indicating the main namespace
111 * are accepted
112 * @param int $defaultNamespace the namespace to use if
113 * none is specified by a prefix
114 * @return Title the new object, or NULL on an error
115 * @static
116 * @access public
118 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
119 if( is_object( $text ) ) {
120 throw new MWException( 'Title::newFromText given an object' );
124 * Wiki pages often contain multiple links to the same page.
125 * Title normalization and parsing can become expensive on
126 * pages with many links, so we can save a little time by
127 * caching them.
129 * In theory these are value objects and won't get changed...
131 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
132 return Title::$titleCache[$text];
136 * Convert things like &eacute; &#257; or &#x3017; into real text...
138 $filteredText = Sanitizer::decodeCharReferences( $text );
140 $t = new Title();
141 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
142 $t->mDefaultNamespace = $defaultNamespace;
144 static $cachedcount = 0 ;
145 if( $t->secureAndSplit() ) {
146 if( $defaultNamespace == NS_MAIN ) {
147 if( $cachedcount >= MW_TITLECACHE_MAX ) {
148 # Avoid memory leaks on mass operations...
149 Title::$titleCache = array();
150 $cachedcount=0;
152 $cachedcount++;
153 Title::$titleCache[$text] =& $t;
155 return $t;
156 } else {
157 $ret = NULL;
158 return $ret;
163 * Create a new Title from URL-encoded text. Ensures that
164 * the given title's length does not exceed the maximum.
165 * @param string $url the title, as might be taken from a URL
166 * @return Title the new object, or NULL on an error
167 * @static
168 * @access public
170 public static function newFromURL( $url ) {
171 global $wgLegalTitleChars;
172 $t = new Title();
174 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
175 # but some URLs used it as a space replacement and they still come
176 # from some external search tools.
177 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
178 $url = str_replace( '+', ' ', $url );
181 $t->mDbkeyform = str_replace( ' ', '_', $url );
182 if( $t->secureAndSplit() ) {
183 return $t;
184 } else {
185 return NULL;
190 * Create a new Title from an article ID
192 * @todo This is inefficiently implemented, the page row is requested
193 * but not used for anything else
195 * @param int $id the page_id corresponding to the Title to create
196 * @return Title the new object, or NULL on an error
197 * @access public
198 * @static
200 public static function newFromID( $id ) {
201 $fname = 'Title::newFromID';
202 $dbr = wfGetDB( DB_SLAVE );
203 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
204 array( 'page_id' => $id ), $fname );
205 if ( $row !== false ) {
206 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
207 } else {
208 $title = NULL;
210 return $title;
214 * Make an array of titles from an array of IDs
216 function newFromIDs( $ids ) {
217 $dbr = wfGetDB( DB_SLAVE );
218 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
219 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
221 $titles = array();
222 while ( $row = $dbr->fetchObject( $res ) ) {
223 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
225 return $titles;
229 * Create a new Title from a namespace index and a DB key.
230 * It's assumed that $ns and $title are *valid*, for instance when
231 * they came directly from the database or a special page name.
232 * For convenience, spaces are converted to underscores so that
233 * eg user_text fields can be used directly.
235 * @param int $ns the namespace of the article
236 * @param string $title the unprefixed database key form
237 * @return Title the new object
238 * @static
239 * @access public
241 public static function &makeTitle( $ns, $title ) {
242 $t = new Title();
243 $t->mInterwiki = '';
244 $t->mFragment = '';
245 $t->mNamespace = intval( $ns );
246 $t->mDbkeyform = str_replace( ' ', '_', $title );
247 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
248 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
249 $t->mTextform = str_replace( '_', ' ', $title );
250 return $t;
254 * Create a new Title from a namespace index and a DB key.
255 * The parameters will be checked for validity, which is a bit slower
256 * than makeTitle() but safer for user-provided data.
258 * @param int $ns the namespace of the article
259 * @param string $title the database key form
260 * @return Title the new object, or NULL on an error
261 * @static
262 * @access public
264 public static function makeTitleSafe( $ns, $title ) {
265 $t = new Title();
266 $t->mDbkeyform = Title::makeName( $ns, $title );
267 if( $t->secureAndSplit() ) {
268 return $t;
269 } else {
270 return NULL;
275 * Create a new Title for the Main Page
277 * @static
278 * @return Title the new object
279 * @access public
281 public static function newMainPage() {
282 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
286 * Create a new Title for a redirect
287 * @param string $text the redirect title text
288 * @return Title the new object, or NULL if the text is not a
289 * valid redirect
291 public static function newFromRedirect( $text ) {
292 $mwRedir = MagicWord::get( 'redirect' );
293 $rt = NULL;
294 if ( $mwRedir->matchStart( $text ) ) {
295 $m = array();
296 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
297 # categories are escaped using : for example one can enter:
298 # #REDIRECT [[:Category:Music]]. Need to remove it.
299 if ( substr($m[1],0,1) == ':') {
300 # We don't want to keep the ':'
301 $m[1] = substr( $m[1], 1 );
304 $rt = Title::newFromText( $m[1] );
305 # Disallow redirects to Special:Userlogout
306 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
307 $rt = NULL;
311 return $rt;
314 #----------------------------------------------------------------------------
315 # Static functions
316 #----------------------------------------------------------------------------
319 * Get the prefixed DB key associated with an ID
320 * @param int $id the page_id of the article
321 * @return Title an object representing the article, or NULL
322 * if no such article was found
323 * @static
324 * @access public
326 function nameOf( $id ) {
327 $fname = 'Title::nameOf';
328 $dbr = wfGetDB( DB_SLAVE );
330 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
331 if ( $s === false ) { return NULL; }
333 $n = Title::makeName( $s->page_namespace, $s->page_title );
334 return $n;
338 * Get a regex character class describing the legal characters in a link
339 * @return string the list of characters, not delimited
340 * @static
341 * @access public
343 public static function legalChars() {
344 global $wgLegalTitleChars;
345 return $wgLegalTitleChars;
349 * Get a string representation of a title suitable for
350 * including in a search index
352 * @param int $ns a namespace index
353 * @param string $title text-form main part
354 * @return string a stripped-down title string ready for the
355 * search index
357 public static function indexTitle( $ns, $title ) {
358 global $wgContLang;
360 $lc = SearchEngine::legalSearchChars() . '&#;';
361 $t = $wgContLang->stripForSearch( $title );
362 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
363 $t = $wgContLang->lc( $t );
365 # Handle 's, s'
366 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
367 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
369 $t = preg_replace( "/\\s+/", ' ', $t );
371 if ( $ns == NS_IMAGE ) {
372 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
374 return trim( $t );
378 * Make a prefixed DB key from a DB key and a namespace index
379 * @param int $ns numerical representation of the namespace
380 * @param string $title the DB key form the title
381 * @return string the prefixed form of the title
383 public static function makeName( $ns, $title ) {
384 global $wgContLang;
386 $n = $wgContLang->getNsText( $ns );
387 return $n == '' ? $title : "$n:$title";
391 * Returns the URL associated with an interwiki prefix
392 * @param string $key the interwiki prefix (e.g. "MeatBall")
393 * @return the associated URL, containing "$1", which should be
394 * replaced by an article title
395 * @static (arguably)
396 * @access public
398 function getInterwikiLink( $key ) {
399 global $wgMemc, $wgInterwikiExpiry;
400 global $wgInterwikiCache, $wgContLang;
401 $fname = 'Title::getInterwikiLink';
403 $key = $wgContLang->lc( $key );
405 $k = wfMemcKey( 'interwiki', $key );
406 if( array_key_exists( $k, Title::$interwikiCache ) ) {
407 return Title::$interwikiCache[$k]->iw_url;
410 if ($wgInterwikiCache) {
411 return Title::getInterwikiCached( $key );
414 $s = $wgMemc->get( $k );
415 # Ignore old keys with no iw_local
416 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
417 Title::$interwikiCache[$k] = $s;
418 return $s->iw_url;
421 $dbr = wfGetDB( DB_SLAVE );
422 $res = $dbr->select( 'interwiki',
423 array( 'iw_url', 'iw_local', 'iw_trans' ),
424 array( 'iw_prefix' => $key ), $fname );
425 if( !$res ) {
426 return '';
429 $s = $dbr->fetchObject( $res );
430 if( !$s ) {
431 # Cache non-existence: create a blank object and save it to memcached
432 $s = (object)false;
433 $s->iw_url = '';
434 $s->iw_local = 0;
435 $s->iw_trans = 0;
437 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
438 Title::$interwikiCache[$k] = $s;
440 return $s->iw_url;
444 * Fetch interwiki prefix data from local cache in constant database
446 * More logic is explained in DefaultSettings
448 * @return string URL of interwiki site
449 * @access public
451 function getInterwikiCached( $key ) {
452 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
453 static $db, $site;
455 if (!$db)
456 $db=dba_open($wgInterwikiCache,'r','cdb');
457 /* Resolve site name */
458 if ($wgInterwikiScopes>=3 and !$site) {
459 $site = dba_fetch('__sites:' . wfWikiID(), $db);
460 if ($site=="")
461 $site = $wgInterwikiFallbackSite;
463 $value = dba_fetch( wfMemcKey( $key ), $db);
464 if ($value=='' and $wgInterwikiScopes>=3) {
465 /* try site-level */
466 $value = dba_fetch("_{$site}:{$key}", $db);
468 if ($value=='' and $wgInterwikiScopes>=2) {
469 /* try globals */
470 $value = dba_fetch("__global:{$key}", $db);
472 if ($value=='undef')
473 $value='';
474 $s = (object)false;
475 $s->iw_url = '';
476 $s->iw_local = 0;
477 $s->iw_trans = 0;
478 if ($value!='') {
479 list($local,$url)=explode(' ',$value,2);
480 $s->iw_url=$url;
481 $s->iw_local=(int)$local;
483 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
484 return $s->iw_url;
487 * Determine whether the object refers to a page within
488 * this project.
490 * @return bool TRUE if this is an in-project interwiki link
491 * or a wikilink, FALSE otherwise
492 * @access public
494 function isLocal() {
495 if ( $this->mInterwiki != '' ) {
496 # Make sure key is loaded into cache
497 $this->getInterwikiLink( $this->mInterwiki );
498 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
499 return (bool)(Title::$interwikiCache[$k]->iw_local);
500 } else {
501 return true;
506 * Determine whether the object refers to a page within
507 * this project and is transcludable.
509 * @return bool TRUE if this is transcludable
510 * @access public
512 function isTrans() {
513 if ($this->mInterwiki == '')
514 return false;
515 # Make sure key is loaded into cache
516 $this->getInterwikiLink( $this->mInterwiki );
517 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
518 return (bool)(Title::$interwikiCache[$k]->iw_trans);
522 * Update the page_touched field for an array of title objects
523 * @todo Inefficient unless the IDs are already loaded into the
524 * link cache
525 * @param array $titles an array of Title objects to be touched
526 * @param string $timestamp the timestamp to use instead of the
527 * default current time
528 * @static
529 * @access public
531 function touchArray( $titles, $timestamp = '' ) {
533 if ( count( $titles ) == 0 ) {
534 return;
536 $dbw = wfGetDB( DB_MASTER );
537 if ( $timestamp == '' ) {
538 $timestamp = $dbw->timestamp();
541 $page = $dbw->tableName( 'page' );
542 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
543 $first = true;
545 foreach ( $titles as $title ) {
546 if ( $wgUseFileCache ) {
547 $cm = new HTMLFileCache($title);
548 @unlink($cm->fileCacheName());
551 if ( ! $first ) {
552 $sql .= ',';
554 $first = false;
555 $sql .= $title->getArticleID();
557 $sql .= ')';
558 if ( ! $first ) {
559 $dbw->query( $sql, 'Title::touchArray' );
562 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
563 // do them in small chunks:
564 $fname = 'Title::touchArray';
565 foreach( $titles as $title ) {
566 $dbw->update( 'page',
567 array( 'page_touched' => $timestamp ),
568 array(
569 'page_namespace' => $title->getNamespace(),
570 'page_title' => $title->getDBkey() ),
571 $fname );
576 * Escape a text fragment, say from a link, for a URL
578 static function escapeFragmentForURL( $fragment ) {
579 $fragment = str_replace( ' ', '_', $fragment );
580 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
581 $replaceArray = array(
582 '%3A' => ':',
583 '%' => '.'
585 return strtr( $fragment, $replaceArray );
588 #----------------------------------------------------------------------------
589 # Other stuff
590 #----------------------------------------------------------------------------
592 /** Simple accessors */
594 * Get the text form (spaces not underscores) of the main part
595 * @return string
596 * @access public
598 function getText() { return $this->mTextform; }
600 * Get the URL-encoded form of the main part
601 * @return string
602 * @access public
604 function getPartialURL() { return $this->mUrlform; }
606 * Get the main part with underscores
607 * @return string
608 * @access public
610 function getDBkey() { return $this->mDbkeyform; }
612 * Get the namespace index, i.e. one of the NS_xxxx constants
613 * @return int
614 * @access public
616 function getNamespace() { return $this->mNamespace; }
618 * Get the namespace text
619 * @return string
620 * @access public
622 function getNsText() {
623 global $wgContLang, $wgCanonicalNamespaceNames;
625 if ( '' != $this->mInterwiki ) {
626 // This probably shouldn't even happen. ohh man, oh yuck.
627 // But for interwiki transclusion it sometimes does.
628 // Shit. Shit shit shit.
630 // Use the canonical namespaces if possible to try to
631 // resolve a foreign namespace.
632 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
633 return $wgCanonicalNamespaceNames[$this->mNamespace];
636 return $wgContLang->getNsText( $this->mNamespace );
639 * Get the namespace text of the subject (rather than talk) page
640 * @return string
641 * @access public
643 function getSubjectNsText() {
644 global $wgContLang;
645 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
649 * Get the namespace text of the talk page
650 * @return string
652 function getTalkNsText() {
653 global $wgContLang;
654 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
658 * Could this title have a corresponding talk page?
659 * @return bool
661 function canTalk() {
662 return( Namespace::canTalk( $this->mNamespace ) );
666 * Get the interwiki prefix (or null string)
667 * @return string
668 * @access public
670 function getInterwiki() { return $this->mInterwiki; }
672 * Get the Title fragment (i.e. the bit after the #) in text form
673 * @return string
674 * @access public
676 function getFragment() { return $this->mFragment; }
678 * Get the fragment in URL form, including the "#" character if there is one
680 * @return string
681 * @access public
683 function getFragmentForURL() {
684 if ( $this->mFragment == '' ) {
685 return '';
686 } else {
687 return '#' . Title::escapeFragmentForURL( $this->mFragment );
691 * Get the default namespace index, for when there is no namespace
692 * @return int
693 * @access public
695 function getDefaultNamespace() { return $this->mDefaultNamespace; }
698 * Get title for search index
699 * @return string a stripped-down title string ready for the
700 * search index
702 function getIndexTitle() {
703 return Title::indexTitle( $this->mNamespace, $this->mTextform );
707 * Get the prefixed database key form
708 * @return string the prefixed title, with underscores and
709 * any interwiki and namespace prefixes
710 * @access public
712 function getPrefixedDBkey() {
713 $s = $this->prefix( $this->mDbkeyform );
714 $s = str_replace( ' ', '_', $s );
715 return $s;
719 * Get the prefixed title with spaces.
720 * This is the form usually used for display
721 * @return string the prefixed title, with spaces
722 * @access public
724 function getPrefixedText() {
725 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
726 $s = $this->prefix( $this->mTextform );
727 $s = str_replace( '_', ' ', $s );
728 $this->mPrefixedText = $s;
730 return $this->mPrefixedText;
734 * Get the prefixed title with spaces, plus any fragment
735 * (part beginning with '#')
736 * @return string the prefixed title, with spaces and
737 * the fragment, including '#'
738 * @access public
740 function getFullText() {
741 $text = $this->getPrefixedText();
742 if( '' != $this->mFragment ) {
743 $text .= '#' . $this->mFragment;
745 return $text;
749 * Get the base name, i.e. the leftmost parts before the /
750 * @return string Base name
752 function getBaseText() {
753 global $wgNamespacesWithSubpages;
754 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
755 $parts = explode( '/', $this->getText() );
756 # Don't discard the real title if there's no subpage involved
757 if( count( $parts ) > 1 )
758 unset( $parts[ count( $parts ) - 1 ] );
759 return implode( '/', $parts );
760 } else {
761 return $this->getText();
766 * Get the lowest-level subpage name, i.e. the rightmost part after /
767 * @return string Subpage name
769 function getSubpageText() {
770 global $wgNamespacesWithSubpages;
771 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
772 $parts = explode( '/', $this->mTextform );
773 return( $parts[ count( $parts ) - 1 ] );
774 } else {
775 return( $this->mTextform );
780 * Get a URL-encoded form of the subpage text
781 * @return string URL-encoded subpage name
783 function getSubpageUrlForm() {
784 $text = $this->getSubpageText();
785 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
786 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
787 return( $text );
791 * Get a URL-encoded title (not an actual URL) including interwiki
792 * @return string the URL-encoded form
793 * @access public
795 function getPrefixedURL() {
796 $s = $this->prefix( $this->mDbkeyform );
797 $s = str_replace( ' ', '_', $s );
799 $s = wfUrlencode ( $s ) ;
801 # Cleaning up URL to make it look nice -- is this safe?
802 $s = str_replace( '%28', '(', $s );
803 $s = str_replace( '%29', ')', $s );
805 return $s;
809 * Get a real URL referring to this title, with interwiki link and
810 * fragment
812 * @param string $query an optional query string, not used
813 * for interwiki links
814 * @param string $variant language variant of url (for sr, zh..)
815 * @return string the URL
816 * @access public
818 function getFullURL( $query = '', $variant = false ) {
819 global $wgContLang, $wgServer, $wgRequest;
821 if ( '' == $this->mInterwiki ) {
822 $url = $this->getLocalUrl( $query, $variant );
824 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
825 // Correct fix would be to move the prepending elsewhere.
826 if ($wgRequest->getVal('action') != 'render') {
827 $url = $wgServer . $url;
829 } else {
830 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
832 $namespace = wfUrlencode( $this->getNsText() );
833 if ( '' != $namespace ) {
834 # Can this actually happen? Interwikis shouldn't be parsed.
835 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
836 $namespace .= ':';
838 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
839 $url = wfAppendQuery( $url, $query );
842 # Finally, add the fragment.
843 $url .= $this->getFragmentForURL();
845 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
846 return $url;
850 * Get a URL with no fragment or server name. If this page is generated
851 * with action=render, $wgServer is prepended.
852 * @param string $query an optional query string; if not specified,
853 * $wgArticlePath will be used.
854 * @param string $variant language variant of url (for sr, zh..)
855 * @return string the URL
856 * @access public
858 function getLocalURL( $query = '', $variant = false ) {
859 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
860 global $wgVariantArticlePath, $wgContLang, $wgUser;
862 // internal links should point to same variant as current page (only anonymous users)
863 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
864 $pref = $wgContLang->getPreferredVariant(false);
865 if($pref != $wgContLang->getCode())
866 $variant = $pref;
869 if ( $this->isExternal() ) {
870 $url = $this->getFullURL();
871 if ( $query ) {
872 // This is currently only used for edit section links in the
873 // context of interwiki transclusion. In theory we should
874 // append the query to the end of any existing query string,
875 // but interwiki transclusion is already broken in that case.
876 $url .= "?$query";
878 } else {
879 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
880 if ( $query == '' ) {
881 if($variant!=false && $wgContLang->hasVariants()){
882 if($wgVariantArticlePath==false)
883 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
884 else
885 $variantArticlePath = $wgVariantArticlePath;
887 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
888 $url = str_replace( '$1', $dbkey, $url );
891 else
892 $url = str_replace( '$1', $dbkey, $wgArticlePath );
893 } else {
894 global $wgActionPaths;
895 $url = false;
896 $matches = array();
897 if( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
900 $action = urldecode( $matches[2] );
901 if( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if( isset( $matches[4] ) ) $query .= $matches[4];
904 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
905 if( $query != '' ) $url .= '?' . $query;
908 if ( $url === false ) {
909 if ( $query == '-' ) {
910 $query = '';
912 $url = "{$wgScript}?title={$dbkey}&{$query}";
916 // FIXME: this causes breakage in various places when we
917 // actually expected a local URL and end up with dupe prefixes.
918 if ($wgRequest->getVal('action') == 'render') {
919 $url = $wgServer . $url;
922 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
923 return $url;
927 * Get an HTML-escaped version of the URL form, suitable for
928 * using in a link, without a server name or fragment
929 * @param string $query an optional query string
930 * @return string the URL
931 * @access public
933 function escapeLocalURL( $query = '' ) {
934 return htmlspecialchars( $this->getLocalURL( $query ) );
938 * Get an HTML-escaped version of the URL form, suitable for
939 * using in a link, including the server name and fragment
941 * @return string the URL
942 * @param string $query an optional query string
943 * @access public
945 function escapeFullURL( $query = '' ) {
946 return htmlspecialchars( $this->getFullURL( $query ) );
950 * Get the URL form for an internal link.
951 * - Used in various Squid-related code, in case we have a different
952 * internal hostname for the server from the exposed one.
954 * @param string $query an optional query string
955 * @param string $variant language variant of url (for sr, zh..)
956 * @return string the URL
957 * @access public
959 function getInternalURL( $query = '', $variant = false ) {
960 global $wgInternalServer;
961 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
962 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
963 return $url;
967 * Get the edit URL for this Title
968 * @return string the URL, or a null string if this is an
969 * interwiki link
970 * @access public
972 function getEditURL() {
973 if ( '' != $this->mInterwiki ) { return ''; }
974 $s = $this->getLocalURL( 'action=edit' );
976 return $s;
980 * Get the HTML-escaped displayable text form.
981 * Used for the title field in <a> tags.
982 * @return string the text, including any prefixes
983 * @access public
985 function getEscapedText() {
986 return htmlspecialchars( $this->getPrefixedText() );
990 * Is this Title interwiki?
991 * @return boolean
992 * @access public
994 function isExternal() { return ( '' != $this->mInterwiki ); }
997 * Is this page "semi-protected" - the *only* protection is autoconfirm?
999 * @param string Action to check (default: edit)
1000 * @return bool
1002 function isSemiProtected( $action = 'edit' ) {
1003 if( $this->exists() ) {
1004 $restrictions = $this->getRestrictions( $action );
1005 if( count( $restrictions ) > 0 ) {
1006 foreach( $restrictions as $restriction ) {
1007 if( strtolower( $restriction ) != 'autoconfirmed' )
1008 return false;
1010 } else {
1011 # Not protected
1012 return false;
1014 return true;
1015 } else {
1016 # If it doesn't exist, it can't be protected
1017 return false;
1022 * Does the title correspond to a protected article?
1023 * @param string $what the action the page is protected from,
1024 * by default checks move and edit
1025 * @return boolean
1026 * @access public
1028 function isProtected( $action = '' ) {
1029 global $wgRestrictionLevels;
1031 # Special pages have inherent protection
1032 if( $this->getNamespace() == NS_SPECIAL )
1033 return true;
1035 # Check regular protection levels
1036 if( $action == 'edit' || $action == '' ) {
1037 $r = $this->getRestrictions( 'edit' );
1038 foreach( $wgRestrictionLevels as $level ) {
1039 if( in_array( $level, $r ) && $level != '' ) {
1040 return( true );
1045 if( $action == 'move' || $action == '' ) {
1046 $r = $this->getRestrictions( 'move' );
1047 foreach( $wgRestrictionLevels as $level ) {
1048 if( in_array( $level, $r ) && $level != '' ) {
1049 return( true );
1054 return false;
1058 * Is $wgUser is watching this page?
1059 * @return boolean
1060 * @access public
1062 function userIsWatching() {
1063 global $wgUser;
1065 if ( is_null( $this->mWatched ) ) {
1066 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1067 $this->mWatched = false;
1068 } else {
1069 $this->mWatched = $wgUser->isWatched( $this );
1072 return $this->mWatched;
1076 * Can $wgUser perform $action on this page?
1077 * This skips potentially expensive cascading permission checks.
1079 * Suitable for use for nonessential UI controls in common cases, but
1080 * _not_ for functional access control.
1082 * May provide false positives, but should never provide a false negative.
1084 * @param string $action action that permission needs to be checked for
1085 * @return boolean
1087 public function quickUserCan( $action ) {
1088 return $this->userCan( $action, false );
1092 * Can $wgUser perform $action on this page?
1093 * @param string $action action that permission needs to be checked for
1094 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1095 * @return boolean
1097 public function userCan( $action, $doExpensiveQueries = true ) {
1098 $fname = 'Title::userCan';
1099 wfProfileIn( $fname );
1101 global $wgUser, $wgNamespaceProtection;
1103 $result = null;
1104 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1105 if ( $result !== null ) {
1106 wfProfileOut( $fname );
1107 return $result;
1110 if( NS_SPECIAL == $this->mNamespace ) {
1111 wfProfileOut( $fname );
1112 return false;
1115 if ( array_key_exists( $this->mNamespace, $wgNamespaceProtection ) ) {
1116 $nsProt = $wgNamespaceProtection[ $this->mNamespace ];
1117 if ( !is_array($nsProt) ) $nsProt = array($nsProt);
1118 foreach( $nsProt as $right ) {
1119 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1120 wfProfileOut( $fname );
1121 return false;
1126 if( $this->mDbkeyform == '_' ) {
1127 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1128 wfProfileOut( $fname );
1129 return false;
1132 # protect css/js subpages of user pages
1133 # XXX: this might be better using restrictions
1134 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1135 if( $this->isCssJsSubpage()
1136 && !$wgUser->isAllowed('editinterface')
1137 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
1138 wfProfileOut( $fname );
1139 return false;
1142 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1143 # We /could/ use the protection level on the source page, but it's fairly ugly
1144 # as we have to establish a precedence hierarchy for pages included by multiple
1145 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1146 # as they could remove the protection anyway.
1147 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1148 # Cascading protection depends on more than this page...
1149 # Several cascading protected pages may include this page...
1150 # Check each cascading level
1151 # This is only for protection restrictions, not for all actions
1152 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1153 foreach( $restrictions[$action] as $right ) {
1154 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1155 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1156 wfProfileOut( $fname );
1157 return false;
1163 foreach( $this->getRestrictions($action) as $right ) {
1164 // Backwards compatibility, rewrite sysop -> protect
1165 if ( $right == 'sysop' ) {
1166 $right = 'protect';
1168 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1169 wfProfileOut( $fname );
1170 return false;
1174 if( $action == 'move' &&
1175 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1176 wfProfileOut( $fname );
1177 return false;
1180 if( $action == 'create' ) {
1181 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1182 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1183 wfProfileOut( $fname );
1184 return false;
1188 wfProfileOut( $fname );
1189 return true;
1193 * Can $wgUser edit this page?
1194 * @return boolean
1195 * @deprecated use userCan('edit')
1197 public function userCanEdit( $doExpensiveQueries = true ) {
1198 return $this->userCan( 'edit', $doExpensiveQueries );
1202 * Can $wgUser create this page?
1203 * @return boolean
1204 * @deprecated use userCan('create')
1206 public function userCanCreate( $doExpensiveQueries = true ) {
1207 return $this->userCan( 'create', $doExpensiveQueries );
1211 * Can $wgUser move this page?
1212 * @return boolean
1213 * @deprecated use userCan('move')
1215 public function userCanMove( $doExpensiveQueries = true ) {
1216 return $this->userCan( 'move', $doExpensiveQueries );
1220 * Would anybody with sufficient privileges be able to move this page?
1221 * Some pages just aren't movable.
1223 * @return boolean
1224 * @access public
1226 function isMovable() {
1227 return Namespace::isMovable( $this->getNamespace() )
1228 && $this->getInterwiki() == '';
1232 * Can $wgUser read this page?
1233 * @return boolean
1234 * @todo fold these checks into userCan()
1236 public function userCanRead() {
1237 global $wgUser;
1239 $result = null;
1240 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1241 if ( $result !== null ) {
1242 return $result;
1245 if( $wgUser->isAllowed('read') ) {
1246 return true;
1247 } else {
1248 global $wgWhitelistRead;
1250 /**
1251 * Always grant access to the login page.
1252 * Even anons need to be able to log in.
1254 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1255 return true;
1258 /** some pages are explicitly allowed */
1259 $name = $this->getPrefixedText();
1260 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1261 return true;
1264 # Compatibility with old settings
1265 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1266 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1267 return true;
1271 return false;
1275 * Is this a talk page of some sort?
1276 * @return bool
1277 * @access public
1279 function isTalkPage() {
1280 return Namespace::isTalk( $this->getNamespace() );
1284 * Is this a subpage?
1285 * @return bool
1286 * @access public
1288 function isSubpage() {
1289 global $wgNamespacesWithSubpages;
1291 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1292 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1293 } else {
1294 return false;
1299 * Is this a .css or .js subpage of a user page?
1300 * @return bool
1301 * @access public
1303 function isCssJsSubpage() {
1304 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform ) );
1307 * Is this a *valid* .css or .js subpage of a user page?
1308 * Check that the corresponding skin exists
1310 function isValidCssJsSubpage() {
1311 if ( $this->isCssJsSubpage() ) {
1312 $skinNames = Skin::getSkinNames();
1313 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1314 } else {
1315 return false;
1319 * Trim down a .css or .js subpage title to get the corresponding skin name
1321 function getSkinFromCssJsSubpage() {
1322 $subpage = explode( '/', $this->mTextform );
1323 $subpage = $subpage[ count( $subpage ) - 1 ];
1324 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1327 * Is this a .css subpage of a user page?
1328 * @return bool
1329 * @access public
1331 function isCssSubpage() {
1332 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1335 * Is this a .js subpage of a user page?
1336 * @return bool
1337 * @access public
1339 function isJsSubpage() {
1340 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1343 * Protect css/js subpages of user pages: can $wgUser edit
1344 * this page?
1346 * @return boolean
1347 * @todo XXX: this might be better using restrictions
1348 * @access public
1350 function userCanEditCssJsSubpage() {
1351 global $wgUser;
1352 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1356 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1358 * @return bool If the page is subject to cascading restrictions.
1359 * @access public
1361 function isCascadeProtected() {
1362 list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false );
1363 return ( $sources > 0 );
1367 * Cascading protection: Get the source of any cascading restrictions on this page.
1369 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1370 * @return array( mixed title array, restriction array)
1371 * 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.
1372 * The restriction array is an array of each type, each of which contains an array of unique groups
1373 * @access public
1375 function getCascadeProtectionSources( $get_pages = true ) {
1376 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1378 # Define our dimension of restrictions types
1379 $pagerestrictions = array();
1380 foreach( $wgRestrictionTypes as $action )
1381 $pagerestrictions[$action] = array();
1383 if (!$wgEnableCascadingProtection)
1384 return array( false, $pagerestrictions );
1386 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1387 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1388 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1389 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1392 wfProfileIn( __METHOD__ );
1394 $dbr = wfGetDb( DB_SLAVE );
1396 if ( $this->getNamespace() == NS_IMAGE ) {
1397 $tables = array ('imagelinks', 'page_restrictions');
1398 $where_clauses = array(
1399 'il_to' => $this->getDBkey(),
1400 'il_from=pr_page',
1401 'pr_cascade' => 1 );
1402 } else {
1403 $tables = array ('templatelinks', 'page_restrictions');
1404 $where_clauses = array(
1405 'tl_namespace' => $this->getNamespace(),
1406 'tl_title' => $this->getDBkey(),
1407 'tl_from=pr_page',
1408 'pr_cascade' => 1 );
1411 if ( $get_pages ) {
1412 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1413 $where_clauses[] = 'page_id=pr_page';
1414 $tables[] = 'page';
1415 } else {
1416 $cols = array( 'pr_expiry' );
1419 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1421 $sources = $get_pages ? array() : false;
1422 $now = wfTimestampNow();
1423 $purgeExpired = false;
1425 while( $row = $dbr->fetchObject( $res ) ) {
1426 $expiry = Block::decodeExpiry( $row->pr_expiry );
1427 if( $expiry > $now ) {
1428 if ($get_pages) {
1429 $page_id = $row->pr_page;
1430 $page_ns = $row->page_namespace;
1431 $page_title = $row->page_title;
1432 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1433 # Add groups needed for each restriction type if its not already there
1434 # Make sure this restriction type still exists
1435 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1436 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1438 } else {
1439 $sources = true;
1441 } else {
1442 // Trigger lazy purge of expired restrictions from the db
1443 $purgeExpired = true;
1446 if( $purgeExpired ) {
1447 Title::purgeExpiredRestrictions();
1450 wfProfileOut( __METHOD__ );
1452 if ( $get_pages ) {
1453 $this->mCascadeSources = $sources;
1454 $this->mCascadingRestrictions = $pagerestrictions;
1455 } else {
1456 $this->mHasCascadingRestrictions = $sources;
1459 return array( $sources, $pagerestrictions );
1462 function areRestrictionsCascading() {
1463 if (!$this->mRestrictionsLoaded) {
1464 $this->loadRestrictions();
1467 return $this->mCascadeRestriction;
1471 * Loads a string into mRestrictions array
1472 * @param resource $res restrictions as an SQL result.
1473 * @access public
1475 function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1476 $dbr = wfGetDb( DB_SLAVE );
1478 $this->mRestrictions['edit'] = array();
1479 $this->mRestrictions['move'] = array();
1481 # Backwards-compatibility: also load the restrictions from the page record (old format).
1483 if ( $oldFashionedRestrictions == NULL ) {
1484 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1487 if ($oldFashionedRestrictions != '') {
1489 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1490 $temp = explode( '=', trim( $restrict ) );
1491 if(count($temp) == 1) {
1492 // old old format should be treated as edit/move restriction
1493 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1494 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1495 } else {
1496 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1500 $this->mOldRestrictions = true;
1501 $this->mCascadeRestriction = false;
1502 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1506 if( $dbr->numRows( $res ) ) {
1507 # Current system - load second to make them override.
1508 $now = wfTimestampNow();
1509 $purgeExpired = false;
1511 while ($row = $dbr->fetchObject( $res ) ) {
1512 # Cycle through all the restrictions.
1514 // This code should be refactored, now that it's being used more generally,
1515 // But I don't really see any harm in leaving it in Block for now -werdna
1516 $expiry = Block::decodeExpiry( $row->pr_expiry );
1518 // Only apply the restrictions if they haven't expired!
1519 if ( !$expiry || $expiry > $now ) {
1520 $this->mRestrictionsExpiry = $expiry;
1521 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1523 $this->mCascadeRestriction |= $row->pr_cascade;
1524 } else {
1525 // Trigger a lazy purge of expired restrictions
1526 $purgeExpired = true;
1530 if( $purgeExpired ) {
1531 Title::purgeExpiredRestrictions();
1535 $this->mRestrictionsLoaded = true;
1538 function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1539 if( !$this->mRestrictionsLoaded ) {
1540 $dbr = wfGetDB( DB_SLAVE );
1542 $res = $dbr->select( 'page_restrictions', '*',
1543 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1545 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1549 /**
1550 * Purge expired restrictions from the page_restrictions table
1552 static function purgeExpiredRestrictions() {
1553 $dbw = wfGetDB( DB_MASTER );
1554 $dbw->delete( 'page_restrictions',
1555 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1556 __METHOD__ );
1560 * Accessor/initialisation for mRestrictions
1562 * @access public
1563 * @param string $action action that permission needs to be checked for
1564 * @return array the array of groups allowed to edit this article
1566 function getRestrictions( $action ) {
1567 if( $this->exists() ) {
1568 if( !$this->mRestrictionsLoaded ) {
1569 $this->loadRestrictions();
1571 return isset( $this->mRestrictions[$action] )
1572 ? $this->mRestrictions[$action]
1573 : array();
1574 } else {
1575 return array();
1580 * Is there a version of this page in the deletion archive?
1581 * @return int the number of archived revisions
1582 * @access public
1584 function isDeleted() {
1585 $fname = 'Title::isDeleted';
1586 if ( $this->getNamespace() < 0 ) {
1587 $n = 0;
1588 } else {
1589 $dbr = wfGetDB( DB_SLAVE );
1590 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1591 'ar_title' => $this->getDBkey() ), $fname );
1592 if( $this->getNamespace() == NS_IMAGE ) {
1593 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1594 array( 'fa_name' => $this->getDBkey() ), $fname );
1597 return (int)$n;
1601 * Get the article ID for this Title from the link cache,
1602 * adding it if necessary
1603 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1604 * for update
1605 * @return int the ID
1607 public function getArticleID( $flags = 0 ) {
1608 $linkCache =& LinkCache::singleton();
1609 if ( $flags & GAID_FOR_UPDATE ) {
1610 $oldUpdate = $linkCache->forUpdate( true );
1611 $this->mArticleID = $linkCache->addLinkObj( $this );
1612 $linkCache->forUpdate( $oldUpdate );
1613 } else {
1614 if ( -1 == $this->mArticleID ) {
1615 $this->mArticleID = $linkCache->addLinkObj( $this );
1618 return $this->mArticleID;
1621 function getLatestRevID() {
1622 if ($this->mLatestID !== false)
1623 return $this->mLatestID;
1625 $db = wfGetDB(DB_SLAVE);
1626 return $this->mLatestID = $db->selectField( 'revision',
1627 "max(rev_id)",
1628 array('rev_page' => $this->getArticleID()),
1629 'Title::getLatestRevID' );
1633 * This clears some fields in this object, and clears any associated
1634 * keys in the "bad links" section of the link cache.
1636 * - This is called from Article::insertNewArticle() to allow
1637 * loading of the new page_id. It's also called from
1638 * Article::doDeleteArticle()
1640 * @param int $newid the new Article ID
1641 * @access public
1643 function resetArticleID( $newid ) {
1644 $linkCache =& LinkCache::singleton();
1645 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1647 if ( 0 == $newid ) { $this->mArticleID = -1; }
1648 else { $this->mArticleID = $newid; }
1649 $this->mRestrictionsLoaded = false;
1650 $this->mRestrictions = array();
1654 * Updates page_touched for this page; called from LinksUpdate.php
1655 * @return bool true if the update succeded
1656 * @access public
1658 function invalidateCache() {
1659 global $wgUseFileCache;
1661 if ( wfReadOnly() ) {
1662 return;
1665 $dbw = wfGetDB( DB_MASTER );
1666 $success = $dbw->update( 'page',
1667 array( /* SET */
1668 'page_touched' => $dbw->timestamp()
1669 ), array( /* WHERE */
1670 'page_namespace' => $this->getNamespace() ,
1671 'page_title' => $this->getDBkey()
1672 ), 'Title::invalidateCache'
1675 if ($wgUseFileCache) {
1676 $cache = new HTMLFileCache($this);
1677 @unlink($cache->fileCacheName());
1680 return $success;
1684 * Prefix some arbitrary text with the namespace or interwiki prefix
1685 * of this object
1687 * @param string $name the text
1688 * @return string the prefixed text
1689 * @private
1691 /* private */ function prefix( $name ) {
1692 $p = '';
1693 if ( '' != $this->mInterwiki ) {
1694 $p = $this->mInterwiki . ':';
1696 if ( 0 != $this->mNamespace ) {
1697 $p .= $this->getNsText() . ':';
1699 return $p . $name;
1703 * Secure and split - main initialisation function for this object
1705 * Assumes that mDbkeyform has been set, and is urldecoded
1706 * and uses underscores, but not otherwise munged. This function
1707 * removes illegal characters, splits off the interwiki and
1708 * namespace prefixes, sets the other forms, and canonicalizes
1709 * everything.
1710 * @return bool true on success
1711 * @private
1713 /* private */ function secureAndSplit() {
1714 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1716 # Initialisation
1717 static $rxTc = false;
1718 if( !$rxTc ) {
1719 # % is needed as well
1720 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1723 $this->mInterwiki = $this->mFragment = '';
1724 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1726 $dbkey = $this->mDbkeyform;
1728 # Strip Unicode bidi override characters.
1729 # Sometimes they slip into cut-n-pasted page titles, where the
1730 # override chars get included in list displays.
1731 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1732 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1734 # Clean up whitespace
1736 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1737 $dbkey = trim( $dbkey, '_' );
1739 if ( '' == $dbkey ) {
1740 return false;
1743 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1744 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1745 return false;
1748 $this->mDbkeyform = $dbkey;
1750 # Initial colon indicates main namespace rather than specified default
1751 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1752 if ( ':' == $dbkey{0} ) {
1753 $this->mNamespace = NS_MAIN;
1754 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1757 # Namespace or interwiki prefix
1758 $firstPass = true;
1759 do {
1760 $m = array();
1761 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1762 $p = $m[1];
1763 $lowerNs = $wgContLang->lc( $p );
1764 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1765 # Canonical namespace
1766 $dbkey = $m[2];
1767 $this->mNamespace = $ns;
1768 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1769 # Ordinary namespace
1770 $dbkey = $m[2];
1771 $this->mNamespace = $ns;
1772 } elseif( $this->getInterwikiLink( $p ) ) {
1773 if( !$firstPass ) {
1774 # Can't make a local interwiki link to an interwiki link.
1775 # That's just crazy!
1776 return false;
1779 # Interwiki link
1780 $dbkey = $m[2];
1781 $this->mInterwiki = $wgContLang->lc( $p );
1783 # Redundant interwiki prefix to the local wiki
1784 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1785 if( $dbkey == '' ) {
1786 # Can't have an empty self-link
1787 return false;
1789 $this->mInterwiki = '';
1790 $firstPass = false;
1791 # Do another namespace split...
1792 continue;
1795 # If there's an initial colon after the interwiki, that also
1796 # resets the default namespace
1797 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1798 $this->mNamespace = NS_MAIN;
1799 $dbkey = substr( $dbkey, 1 );
1802 # If there's no recognized interwiki or namespace,
1803 # then let the colon expression be part of the title.
1805 break;
1806 } while( true );
1808 # We already know that some pages won't be in the database!
1810 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1811 $this->mArticleID = 0;
1813 $fragment = strstr( $dbkey, '#' );
1814 if ( false !== $fragment ) {
1815 $this->setFragment( $fragment );
1816 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1817 # remove whitespace again: prevents "Foo_bar_#"
1818 # becoming "Foo_bar_"
1819 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1822 # Reject illegal characters.
1824 if( preg_match( $rxTc, $dbkey ) ) {
1825 return false;
1829 * Pages with "/./" or "/../" appearing in the URLs will
1830 * often be unreachable due to the way web browsers deal
1831 * with 'relative' URLs. Forbid them explicitly.
1833 if ( strpos( $dbkey, '.' ) !== false &&
1834 ( $dbkey === '.' || $dbkey === '..' ||
1835 strpos( $dbkey, './' ) === 0 ||
1836 strpos( $dbkey, '../' ) === 0 ||
1837 strpos( $dbkey, '/./' ) !== false ||
1838 strpos( $dbkey, '/../' ) !== false ) )
1840 return false;
1844 * Magic tilde sequences? Nu-uh!
1846 if( strpos( $dbkey, '~~~' ) !== false ) {
1847 return false;
1851 * Limit the size of titles to 255 bytes.
1852 * This is typically the size of the underlying database field.
1853 * We make an exception for special pages, which don't need to be stored
1854 * in the database, and may edge over 255 bytes due to subpage syntax
1855 * for long titles, e.g. [[Special:Block/Long name]]
1857 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1858 strlen( $dbkey ) > 512 )
1860 return false;
1864 * Normally, all wiki links are forced to have
1865 * an initial capital letter so [[foo]] and [[Foo]]
1866 * point to the same place.
1868 * Don't force it for interwikis, since the other
1869 * site might be case-sensitive.
1871 if( $wgCapitalLinks && $this->mInterwiki == '') {
1872 $dbkey = $wgContLang->ucfirst( $dbkey );
1876 * Can't make a link to a namespace alone...
1877 * "empty" local links can only be self-links
1878 * with a fragment identifier.
1880 if( $dbkey == '' &&
1881 $this->mInterwiki == '' &&
1882 $this->mNamespace != NS_MAIN ) {
1883 return false;
1886 // Any remaining initial :s are illegal.
1887 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1888 return false;
1891 # Fill fields
1892 $this->mDbkeyform = $dbkey;
1893 $this->mUrlform = wfUrlencode( $dbkey );
1895 $this->mTextform = str_replace( '_', ' ', $dbkey );
1897 return true;
1901 * Set the fragment for this title
1902 * This is kind of bad, since except for this rarely-used function, Title objects
1903 * are immutable. The reason this is here is because it's better than setting the
1904 * members directly, which is what Linker::formatComment was doing previously.
1906 * @param string $fragment text
1907 * @access public
1908 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1910 function setFragment( $fragment ) {
1911 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1915 * Get a Title object associated with the talk page of this article
1916 * @return Title the object for the talk page
1917 * @access public
1919 function getTalkPage() {
1920 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1924 * Get a title object associated with the subject page of this
1925 * talk page
1927 * @return Title the object for the subject page
1928 * @access public
1930 function getSubjectPage() {
1931 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1935 * Get an array of Title objects linking to this Title
1936 * Also stores the IDs in the link cache.
1938 * WARNING: do not use this function on arbitrary user-supplied titles!
1939 * On heavily-used templates it will max out the memory.
1941 * @param string $options may be FOR UPDATE
1942 * @return array the Title objects linking here
1943 * @access public
1945 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1946 $linkCache =& LinkCache::singleton();
1948 if ( $options ) {
1949 $db = wfGetDB( DB_MASTER );
1950 } else {
1951 $db = wfGetDB( DB_SLAVE );
1954 $res = $db->select( array( 'page', $table ),
1955 array( 'page_namespace', 'page_title', 'page_id' ),
1956 array(
1957 "{$prefix}_from=page_id",
1958 "{$prefix}_namespace" => $this->getNamespace(),
1959 "{$prefix}_title" => $this->getDbKey() ),
1960 'Title::getLinksTo',
1961 $options );
1963 $retVal = array();
1964 if ( $db->numRows( $res ) ) {
1965 while ( $row = $db->fetchObject( $res ) ) {
1966 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1967 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1968 $retVal[] = $titleObj;
1972 $db->freeResult( $res );
1973 return $retVal;
1977 * Get an array of Title objects using this Title as a template
1978 * Also stores the IDs in the link cache.
1980 * WARNING: do not use this function on arbitrary user-supplied titles!
1981 * On heavily-used templates it will max out the memory.
1983 * @param string $options may be FOR UPDATE
1984 * @return array the Title objects linking here
1985 * @access public
1987 function getTemplateLinksTo( $options = '' ) {
1988 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1992 * Get an array of Title objects referring to non-existent articles linked from this page
1994 * @param string $options may be FOR UPDATE
1995 * @return array the Title objects
1996 * @access public
1998 function getBrokenLinksFrom( $options = '' ) {
1999 if ( $options ) {
2000 $db = wfGetDB( DB_MASTER );
2001 } else {
2002 $db = wfGetDB( DB_SLAVE );
2005 $res = $db->safeQuery(
2006 "SELECT pl_namespace, pl_title
2007 FROM !
2008 LEFT JOIN !
2009 ON pl_namespace=page_namespace
2010 AND pl_title=page_title
2011 WHERE pl_from=?
2012 AND page_namespace IS NULL
2014 $db->tableName( 'pagelinks' ),
2015 $db->tableName( 'page' ),
2016 $this->getArticleId(),
2017 $options );
2019 $retVal = array();
2020 if ( $db->numRows( $res ) ) {
2021 while ( $row = $db->fetchObject( $res ) ) {
2022 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2025 $db->freeResult( $res );
2026 return $retVal;
2031 * Get a list of URLs to purge from the Squid cache when this
2032 * page changes
2034 * @return array the URLs
2035 * @access public
2037 function getSquidURLs() {
2038 global $wgContLang;
2040 $urls = array(
2041 $this->getInternalURL(),
2042 $this->getInternalURL( 'action=history' )
2045 // purge variant urls as well
2046 if($wgContLang->hasVariants()){
2047 $variants = $wgContLang->getVariants();
2048 foreach($variants as $vCode){
2049 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2050 $urls[] = $this->getInternalURL('',$vCode);
2054 return $urls;
2057 function purgeSquid() {
2058 global $wgUseSquid;
2059 if ( $wgUseSquid ) {
2060 $urls = $this->getSquidURLs();
2061 $u = new SquidUpdate( $urls );
2062 $u->doUpdate();
2067 * Move this page without authentication
2068 * @param Title &$nt the new page Title
2069 * @access public
2071 function moveNoAuth( &$nt ) {
2072 return $this->moveTo( $nt, false );
2076 * Check whether a given move operation would be valid.
2077 * Returns true if ok, or a message key string for an error message
2078 * if invalid. (Scarrrrry ugly interface this.)
2079 * @param Title &$nt the new title
2080 * @param bool $auth indicates whether $wgUser's permissions
2081 * should be checked
2082 * @return mixed true on success, message name on failure
2083 * @access public
2085 function isValidMoveOperation( &$nt, $auth = true ) {
2086 if( !$this or !$nt ) {
2087 return 'badtitletext';
2089 if( $this->equals( $nt ) ) {
2090 return 'selfmove';
2092 if( !$this->isMovable() || !$nt->isMovable() ) {
2093 return 'immobile_namespace';
2096 $oldid = $this->getArticleID();
2097 $newid = $nt->getArticleID();
2099 if ( strlen( $nt->getDBkey() ) < 1 ) {
2100 return 'articleexists';
2102 if ( ( '' == $this->getDBkey() ) ||
2103 ( !$oldid ) ||
2104 ( '' == $nt->getDBkey() ) ) {
2105 return 'badarticleerror';
2108 if ( $auth && (
2109 !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
2110 !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
2111 return 'protectedpage';
2114 # The move is allowed only if (1) the target doesn't exist, or
2115 # (2) the target is a redirect to the source, and has no history
2116 # (so we can undo bad moves right after they're done).
2118 if ( 0 != $newid ) { # Target exists; check for validity
2119 if ( ! $this->isValidMoveTarget( $nt ) ) {
2120 return 'articleexists';
2123 return true;
2127 * Move a title to a new location
2128 * @param Title &$nt the new title
2129 * @param bool $auth indicates whether $wgUser's permissions
2130 * should be checked
2131 * @return mixed true on success, message name on failure
2132 * @access public
2134 function moveTo( &$nt, $auth = true, $reason = '' ) {
2135 $err = $this->isValidMoveOperation( $nt, $auth );
2136 if( is_string( $err ) ) {
2137 return $err;
2140 $pageid = $this->getArticleID();
2141 if( $nt->exists() ) {
2142 $this->moveOverExistingRedirect( $nt, $reason );
2143 $pageCountChange = 0;
2144 } else { # Target didn't exist, do normal move.
2145 $this->moveToNewTitle( $nt, $reason );
2146 $pageCountChange = 1;
2148 $redirid = $this->getArticleID();
2150 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2151 $dbw = wfGetDB( DB_MASTER );
2152 $categorylinks = $dbw->tableName( 'categorylinks' );
2153 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2154 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2155 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2156 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2158 # Update watchlists
2160 $oldnamespace = $this->getNamespace() & ~1;
2161 $newnamespace = $nt->getNamespace() & ~1;
2162 $oldtitle = $this->getDBkey();
2163 $newtitle = $nt->getDBkey();
2165 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2166 WatchedItem::duplicateEntries( $this, $nt );
2169 # Update search engine
2170 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2171 $u->doUpdate();
2172 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2173 $u->doUpdate();
2175 # Update site_stats
2176 if( $this->isContentPage() && !$nt->isContentPage() ) {
2177 # No longer a content page
2178 # Not viewed, edited, removing
2179 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2180 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2181 # Now a content page
2182 # Not viewed, edited, adding
2183 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2184 } elseif( $pageCountChange ) {
2185 # Redirect added
2186 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2187 } else {
2188 # Nothing special
2189 $u = false;
2191 if( $u )
2192 $u->doUpdate();
2194 global $wgUser;
2195 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2196 return true;
2200 * Move page to a title which is at present a redirect to the
2201 * source page
2203 * @param Title &$nt the page to move to, which should currently
2204 * be a redirect
2205 * @private
2207 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2208 global $wgUseSquid;
2209 $fname = 'Title::moveOverExistingRedirect';
2210 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2212 if ( $reason ) {
2213 $comment .= ": $reason";
2216 $now = wfTimestampNow();
2217 $newid = $nt->getArticleID();
2218 $oldid = $this->getArticleID();
2219 $dbw = wfGetDB( DB_MASTER );
2220 $linkCache =& LinkCache::singleton();
2222 # Delete the old redirect. We don't save it to history since
2223 # by definition if we've got here it's rather uninteresting.
2224 # We have to remove it so that the next step doesn't trigger
2225 # a conflict on the unique namespace+title index...
2226 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2228 # Save a null revision in the page's history notifying of the move
2229 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2230 $nullRevId = $nullRevision->insertOn( $dbw );
2232 # Change the name of the target page:
2233 $dbw->update( 'page',
2234 /* SET */ array(
2235 'page_touched' => $dbw->timestamp($now),
2236 'page_namespace' => $nt->getNamespace(),
2237 'page_title' => $nt->getDBkey(),
2238 'page_latest' => $nullRevId,
2240 /* WHERE */ array( 'page_id' => $oldid ),
2241 $fname
2243 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2245 # Recreate the redirect, this time in the other direction.
2246 $mwRedir = MagicWord::get( 'redirect' );
2247 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2248 $redirectArticle = new Article( $this );
2249 $newid = $redirectArticle->insertOn( $dbw );
2250 $redirectRevision = new Revision( array(
2251 'page' => $newid,
2252 'comment' => $comment,
2253 'text' => $redirectText ) );
2254 $redirectRevision->insertOn( $dbw );
2255 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2256 $linkCache->clearLink( $this->getPrefixedDBkey() );
2258 # Log the move
2259 $log = new LogPage( 'move' );
2260 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2262 # Now, we record the link from the redirect to the new title.
2263 # It should have no other outgoing links...
2264 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2265 $dbw->insert( 'pagelinks',
2266 array(
2267 'pl_from' => $newid,
2268 'pl_namespace' => $nt->getNamespace(),
2269 'pl_title' => $nt->getDbKey() ),
2270 $fname );
2272 # Purge squid
2273 if ( $wgUseSquid ) {
2274 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2275 $u = new SquidUpdate( $urls );
2276 $u->doUpdate();
2281 * Move page to non-existing title.
2282 * @param Title &$nt the new Title
2283 * @private
2285 function moveToNewTitle( &$nt, $reason = '' ) {
2286 global $wgUseSquid;
2287 $fname = 'MovePageForm::moveToNewTitle';
2288 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2289 if ( $reason ) {
2290 $comment .= ": $reason";
2293 $newid = $nt->getArticleID();
2294 $oldid = $this->getArticleID();
2295 $dbw = wfGetDB( DB_MASTER );
2296 $now = $dbw->timestamp();
2297 $linkCache =& LinkCache::singleton();
2299 # Save a null revision in the page's history notifying of the move
2300 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2301 $nullRevId = $nullRevision->insertOn( $dbw );
2303 # Rename cur entry
2304 $dbw->update( 'page',
2305 /* SET */ array(
2306 'page_touched' => $now,
2307 'page_namespace' => $nt->getNamespace(),
2308 'page_title' => $nt->getDBkey(),
2309 'page_latest' => $nullRevId,
2311 /* WHERE */ array( 'page_id' => $oldid ),
2312 $fname
2315 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2317 # Insert redirect
2318 $mwRedir = MagicWord::get( 'redirect' );
2319 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2320 $redirectArticle = new Article( $this );
2321 $newid = $redirectArticle->insertOn( $dbw );
2322 $redirectRevision = new Revision( array(
2323 'page' => $newid,
2324 'comment' => $comment,
2325 'text' => $redirectText ) );
2326 $redirectRevision->insertOn( $dbw );
2327 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2328 $linkCache->clearLink( $this->getPrefixedDBkey() );
2330 # Log the move
2331 $log = new LogPage( 'move' );
2332 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2334 # Purge caches as per article creation
2335 Article::onArticleCreate( $nt );
2337 # Record the just-created redirect's linking to the page
2338 $dbw->insert( 'pagelinks',
2339 array(
2340 'pl_from' => $newid,
2341 'pl_namespace' => $nt->getNamespace(),
2342 'pl_title' => $nt->getDBkey() ),
2343 $fname );
2345 # Purge old title from squid
2346 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2347 $this->purgeSquid();
2351 * Checks if $this can be moved to a given Title
2352 * - Selects for update, so don't call it unless you mean business
2354 * @param Title &$nt the new title to check
2355 * @access public
2357 function isValidMoveTarget( $nt ) {
2359 $fname = 'Title::isValidMoveTarget';
2360 $dbw = wfGetDB( DB_MASTER );
2362 # Is it a redirect?
2363 $id = $nt->getArticleID();
2364 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2365 array( 'page_is_redirect','old_text','old_flags' ),
2366 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2367 $fname, 'FOR UPDATE' );
2369 if ( !$obj || 0 == $obj->page_is_redirect ) {
2370 # Not a redirect
2371 wfDebug( __METHOD__ . ": not a redirect\n" );
2372 return false;
2374 $text = Revision::getRevisionText( $obj );
2376 # Does the redirect point to the source?
2377 # Or is it a broken self-redirect, usually caused by namespace collisions?
2378 $m = array();
2379 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2380 $redirTitle = Title::newFromText( $m[1] );
2381 if( !is_object( $redirTitle ) ||
2382 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2383 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2384 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2385 return false;
2387 } else {
2388 # Fail safe
2389 wfDebug( __METHOD__ . ": failsafe\n" );
2390 return false;
2393 # Does the article have a history?
2394 $row = $dbw->selectRow( array( 'page', 'revision'),
2395 array( 'rev_id' ),
2396 array( 'page_namespace' => $nt->getNamespace(),
2397 'page_title' => $nt->getDBkey(),
2398 'page_id=rev_page AND page_latest != rev_id'
2399 ), $fname, 'FOR UPDATE'
2402 # Return true if there was no history
2403 return $row === false;
2407 * Get categories to which this Title belongs and return an array of
2408 * categories' names.
2410 * @return array an array of parents in the form:
2411 * $parent => $currentarticle
2412 * @access public
2414 function getParentCategories() {
2415 global $wgContLang;
2417 $titlekey = $this->getArticleId();
2418 $dbr = wfGetDB( DB_SLAVE );
2419 $categorylinks = $dbr->tableName( 'categorylinks' );
2421 # NEW SQL
2422 $sql = "SELECT * FROM $categorylinks"
2423 ." WHERE cl_from='$titlekey'"
2424 ." AND cl_from <> '0'"
2425 ." ORDER BY cl_sortkey";
2427 $res = $dbr->query ( $sql ) ;
2429 if($dbr->numRows($res) > 0) {
2430 while ( $x = $dbr->fetchObject ( $res ) )
2431 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2432 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2433 $dbr->freeResult ( $res ) ;
2434 } else {
2435 $data = '';
2437 return $data;
2441 * Get a tree of parent categories
2442 * @param array $children an array with the children in the keys, to check for circular refs
2443 * @return array
2444 * @access public
2446 function getParentCategoryTree( $children = array() ) {
2447 $parents = $this->getParentCategories();
2449 if($parents != '') {
2450 foreach($parents as $parent => $current) {
2451 if ( array_key_exists( $parent, $children ) ) {
2452 # Circular reference
2453 $stack[$parent] = array();
2454 } else {
2455 $nt = Title::newFromText($parent);
2456 if ( $nt ) {
2457 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2461 return $stack;
2462 } else {
2463 return array();
2469 * Get an associative array for selecting this title from
2470 * the "page" table
2472 * @return array
2473 * @access public
2475 function pageCond() {
2476 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2480 * Get the revision ID of the previous revision
2482 * @param integer $revision Revision ID. Get the revision that was before this one.
2483 * @return integer $oldrevision|false
2485 function getPreviousRevisionID( $revision ) {
2486 $dbr = wfGetDB( DB_SLAVE );
2487 return $dbr->selectField( 'revision', 'rev_id',
2488 'rev_page=' . intval( $this->getArticleId() ) .
2489 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2493 * Get the revision ID of the next revision
2495 * @param integer $revision Revision ID. Get the revision that was after this one.
2496 * @return integer $oldrevision|false
2498 function getNextRevisionID( $revision ) {
2499 $dbr = wfGetDB( DB_SLAVE );
2500 return $dbr->selectField( 'revision', 'rev_id',
2501 'rev_page=' . intval( $this->getArticleId() ) .
2502 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2506 * Get the number of revisions between the given revision IDs.
2508 * @param integer $old Revision ID.
2509 * @param integer $new Revision ID.
2510 * @return integer Number of revisions between these IDs.
2512 function countRevisionsBetween( $old, $new ) {
2513 $dbr = wfGetDB( DB_SLAVE );
2514 return $dbr->selectField( 'revision', 'count(*)',
2515 'rev_page = ' . intval( $this->getArticleId() ) .
2516 ' AND rev_id > ' . intval( $old ) .
2517 ' AND rev_id < ' . intval( $new ) );
2521 * Compare with another title.
2523 * @param Title $title
2524 * @return bool
2526 function equals( $title ) {
2527 // Note: === is necessary for proper matching of number-like titles.
2528 return $this->getInterwiki() === $title->getInterwiki()
2529 && $this->getNamespace() == $title->getNamespace()
2530 && $this->getDbkey() === $title->getDbkey();
2534 * Check if page exists
2535 * @return bool
2537 function exists() {
2538 return $this->getArticleId() != 0;
2542 * Should a link should be displayed as a known link, just based on its title?
2544 * Currently, a self-link with a fragment and special pages are in
2545 * this category. Special pages never exist in the database.
2547 function isAlwaysKnown() {
2548 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2549 || NS_SPECIAL == $this->mNamespace;
2553 * Update page_touched timestamps and send squid purge messages for
2554 * pages linking to this title. May be sent to the job queue depending
2555 * on the number of links. Typically called on create and delete.
2557 function touchLinks() {
2558 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2559 $u->doUpdate();
2561 if ( $this->getNamespace() == NS_CATEGORY ) {
2562 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2563 $u->doUpdate();
2568 * Get the last touched timestamp
2570 function getTouched() {
2571 $dbr = wfGetDB( DB_SLAVE );
2572 $touched = $dbr->selectField( 'page', 'page_touched',
2573 array(
2574 'page_namespace' => $this->getNamespace(),
2575 'page_title' => $this->getDBkey()
2576 ), __METHOD__
2578 return $touched;
2582 * Get a cached value from a global cache that is invalidated when this page changes
2583 * @param string $key the key
2584 * @param callback $callback A callback function which generates the value on cache miss
2586 * @deprecated use DependencyWrapper
2588 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2589 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2590 $params, new TitleDependency( $this ) );
2593 function trackbackURL() {
2594 global $wgTitle, $wgScriptPath, $wgServer;
2596 return "$wgServer$wgScriptPath/trackback.php?article="
2597 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2600 function trackbackRDF() {
2601 $url = htmlspecialchars($this->getFullURL());
2602 $title = htmlspecialchars($this->getText());
2603 $tburl = $this->trackbackURL();
2605 return "
2606 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2607 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2608 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2609 <rdf:Description
2610 rdf:about=\"$url\"
2611 dc:identifier=\"$url\"
2612 dc:title=\"$title\"
2613 trackback:ping=\"$tburl\" />
2614 </rdf:RDF>";
2618 * Generate strings used for xml 'id' names in monobook tabs
2619 * @return string
2621 function getNamespaceKey() {
2622 global $wgContLang;
2623 switch ($this->getNamespace()) {
2624 case NS_MAIN:
2625 case NS_TALK:
2626 return 'nstab-main';
2627 case NS_USER:
2628 case NS_USER_TALK:
2629 return 'nstab-user';
2630 case NS_MEDIA:
2631 return 'nstab-media';
2632 case NS_SPECIAL:
2633 return 'nstab-special';
2634 case NS_PROJECT:
2635 case NS_PROJECT_TALK:
2636 return 'nstab-project';
2637 case NS_IMAGE:
2638 case NS_IMAGE_TALK:
2639 return 'nstab-image';
2640 case NS_MEDIAWIKI:
2641 case NS_MEDIAWIKI_TALK:
2642 return 'nstab-mediawiki';
2643 case NS_TEMPLATE:
2644 case NS_TEMPLATE_TALK:
2645 return 'nstab-template';
2646 case NS_HELP:
2647 case NS_HELP_TALK:
2648 return 'nstab-help';
2649 case NS_CATEGORY:
2650 case NS_CATEGORY_TALK:
2651 return 'nstab-category';
2652 default:
2653 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2658 * Returns true if this title resolves to the named special page
2659 * @param string $name The special page name
2660 * @access public
2662 function isSpecial( $name ) {
2663 if ( $this->getNamespace() == NS_SPECIAL ) {
2664 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2665 if ( $name == $thisName ) {
2666 return true;
2669 return false;
2673 * If the Title refers to a special page alias which is not the local default,
2674 * returns a new Title which points to the local default. Otherwise, returns $this.
2676 function fixSpecialName() {
2677 if ( $this->getNamespace() == NS_SPECIAL ) {
2678 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2679 if ( $canonicalName ) {
2680 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2681 if ( $localName != $this->mDbkeyform ) {
2682 return Title::makeTitle( NS_SPECIAL, $localName );
2686 return $this;
2690 * Is this Title in a namespace which contains content?
2691 * In other words, is this a content page, for the purposes of calculating
2692 * statistics, etc?
2694 * @return bool
2696 public function isContentPage() {
2697 return Namespace::isContent( $this->getNamespace() );