* Remove legacy PHPTal code, hasn't been maintained in ages.
[mediawiki.git] / includes / Title.php
blob2c1932529acf18de931018605ba215a6da35cb38
1 <?php
2 /**
3 * See title.txt
5 * @package MediaWiki
6 */
8 /** */
9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 $wgTitleCache = array();
14 define ( 'GAID_FOR_UPDATE', 1 );
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
20 # reset the cache.
21 define( 'MW_TITLECACHE_MAX', 1000 );
23 /**
24 * Title class
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
28 * @package MediaWiki
30 class Title {
31 /**
32 * All member variables should be considered private
33 * Please use the accessor functions
36 /**#@+
37 * @access private
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
55 /**#@-*/
58 /**
59 * Constructor
60 * @access private
62 /* private */ function Title() {
63 $this->mInterwiki = $this->mUrlform =
64 $this->mTextform = $this->mDbkeyform = '';
65 $this->mArticleID = -1;
66 $this->mNamespace = NS_MAIN;
67 $this->mRestrictionsLoaded = false;
68 $this->mRestrictions = array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
70 # See bug #696
71 $this->mDefaultNamespace = NS_MAIN;
72 $this->mWatched = NULL;
73 $this->mLatestID = false;
76 /**
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
80 * interwiki prefixes
81 * @return Title the new object, or NULL on an error
82 * @static
83 * @access public
85 /* static */ function newFromDBkey( $key ) {
86 $t = new Title();
87 $t->mDbkeyform = $key;
88 if( $t->secureAndSplit() )
89 return $t;
90 else
91 return NULL;
94 /**
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
100 * are accepted
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
104 * @static
105 * @access public
107 function newFromText( $text, $defaultNamespace = NS_MAIN ) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
111 if( is_object( $text ) ) {
112 wfDebugDieBacktrace( 'Title::newFromText given an object' );
116 * Wiki pages often contain multiple links to the same page.
117 * Title normalization and parsing can become expensive on
118 * pages with many links, so we can save a little time by
119 * caching them.
121 * In theory these are value objects and won't get changed...
123 if( $defaultNamespace == NS_MAIN && isset( $wgTitleCache[$text] ) ) {
124 return $wgTitleCache[$text];
128 * Convert things like &eacute; &#257; or &#x3017; into real text...
130 $filteredText = Sanitizer::decodeCharReferences( $text );
132 $t =& new Title();
133 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace = $defaultNamespace;
136 static $cachedcount = 0 ;
137 if( $t->secureAndSplit() ) {
138 if( $defaultNamespace == NS_MAIN ) {
139 if( $cachedcount >= MW_TITLECACHE_MAX ) {
140 # Avoid memory leaks on mass operations...
141 $wgTitleCache = array();
142 $cachedcount=0;
144 $cachedcount++;
145 $wgTitleCache[$text] =& $t;
147 return $t;
148 } else {
149 $ret = NULL;
150 return $ret;
155 * Create a new Title from URL-encoded text. Ensures that
156 * the given title's length does not exceed the maximum.
157 * @param string $url the title, as might be taken from a URL
158 * @return Title the new object, or NULL on an error
159 * @static
160 * @access public
162 function newFromURL( $url ) {
163 global $wgLegalTitleChars;
164 $t = new Title();
166 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
167 # but some URLs used it as a space replacement and they still come
168 # from some external search tools.
169 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
170 $url = str_replace( '+', ' ', $url );
173 $t->mDbkeyform = str_replace( ' ', '_', $url );
174 if( $t->secureAndSplit() ) {
175 return $t;
176 } else {
177 return NULL;
182 * Create a new Title from an article ID
184 * @todo This is inefficiently implemented, the page row is requested
185 * but not used for anything else
187 * @param int $id the page_id corresponding to the Title to create
188 * @return Title the new object, or NULL on an error
189 * @access public
190 * @static
192 function newFromID( $id ) {
193 $fname = 'Title::newFromID';
194 $dbr =& wfGetDB( DB_SLAVE );
195 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
196 array( 'page_id' => $id ), $fname );
197 if ( $row !== false ) {
198 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
199 } else {
200 $title = NULL;
202 return $title;
206 * Create a new Title from a namespace index and a DB key.
207 * It's assumed that $ns and $title are *valid*, for instance when
208 * they came directly from the database or a special page name.
209 * For convenience, spaces are converted to underscores so that
210 * eg user_text fields can be used directly.
212 * @param int $ns the namespace of the article
213 * @param string $title the unprefixed database key form
214 * @return Title the new object
215 * @static
216 * @access public
218 function &makeTitle( $ns, $title ) {
219 $t =& new Title();
220 $t->mInterwiki = '';
221 $t->mFragment = '';
222 $t->mNamespace = intval( $ns );
223 $t->mDbkeyform = str_replace( ' ', '_', $title );
224 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
225 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
226 $t->mTextform = str_replace( '_', ' ', $title );
227 return $t;
231 * Create a new Title frrom a namespace index and a DB key.
232 * The parameters will be checked for validity, which is a bit slower
233 * than makeTitle() but safer for user-provided data.
235 * @param int $ns the namespace of the article
236 * @param string $title the database key form
237 * @return Title the new object, or NULL on an error
238 * @static
239 * @access public
241 function makeTitleSafe( $ns, $title ) {
242 $t = new Title();
243 $t->mDbkeyform = Title::makeName( $ns, $title );
244 if( $t->secureAndSplit() ) {
245 return $t;
246 } else {
247 return NULL;
252 * Create a new Title for the Main Page
254 * @static
255 * @return Title the new object
256 * @access public
258 function newMainPage() {
259 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
263 * Create a new Title for a redirect
264 * @param string $text the redirect title text
265 * @return Title the new object, or NULL if the text is not a
266 * valid redirect
267 * @static
268 * @access public
270 function newFromRedirect( $text ) {
271 global $wgMwRedir;
272 $rt = NULL;
273 if ( $wgMwRedir->matchStart( $text ) ) {
274 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
275 # categories are escaped using : for example one can enter:
276 # #REDIRECT [[:Category:Music]]. Need to remove it.
277 if ( substr($m[1],0,1) == ':') {
278 # We don't want to keep the ':'
279 $m[1] = substr( $m[1], 1 );
282 $rt = Title::newFromText( $m[1] );
283 # Disallow redirects to Special:Userlogout
284 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
285 $rt = NULL;
289 return $rt;
292 #----------------------------------------------------------------------------
293 # Static functions
294 #----------------------------------------------------------------------------
297 * Get the prefixed DB key associated with an ID
298 * @param int $id the page_id of the article
299 * @return Title an object representing the article, or NULL
300 * if no such article was found
301 * @static
302 * @access public
304 function nameOf( $id ) {
305 $fname = 'Title::nameOf';
306 $dbr =& wfGetDB( DB_SLAVE );
308 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
309 if ( $s === false ) { return NULL; }
311 $n = Title::makeName( $s->page_namespace, $s->page_title );
312 return $n;
316 * Get a regex character class describing the legal characters in a link
317 * @return string the list of characters, not delimited
318 * @static
319 * @access public
321 function legalChars() {
322 global $wgLegalTitleChars;
323 return $wgLegalTitleChars;
327 * Get a string representation of a title suitable for
328 * including in a search index
330 * @param int $ns a namespace index
331 * @param string $title text-form main part
332 * @return string a stripped-down title string ready for the
333 * search index
335 /* static */ function indexTitle( $ns, $title ) {
336 global $wgContLang;
337 require_once( 'SearchEngine.php' );
339 $lc = SearchEngine::legalSearchChars() . '&#;';
340 $t = $wgContLang->stripForSearch( $title );
341 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
342 $t = strtolower( $t );
344 # Handle 's, s'
345 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
346 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
348 $t = preg_replace( "/\\s+/", ' ', $t );
350 if ( $ns == NS_IMAGE ) {
351 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
353 return trim( $t );
357 * Make a prefixed DB key from a DB key and a namespace index
358 * @param int $ns numerical representation of the namespace
359 * @param string $title the DB key form the title
360 * @return string the prefixed form of the title
362 /* static */ function makeName( $ns, $title ) {
363 global $wgContLang;
365 $n = $wgContLang->getNsText( $ns );
366 return $n == '' ? $title : "$n:$title";
370 * Returns the URL associated with an interwiki prefix
371 * @param string $key the interwiki prefix (e.g. "MeatBall")
372 * @return the associated URL, containing "$1", which should be
373 * replaced by an article title
374 * @static (arguably)
375 * @access public
377 function getInterwikiLink( $key ) {
378 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
379 global $wgInterwikiCache;
380 $fname = 'Title::getInterwikiLink';
382 $key = strtolower( $key );
384 $k = $wgDBname.':interwiki:'.$key;
385 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
386 return $wgTitleInterwikiCache[$k]->iw_url;
389 if ($wgInterwikiCache) {
390 return Title::getInterwikiCached( $key );
393 $s = $wgMemc->get( $k );
394 # Ignore old keys with no iw_local
395 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
396 $wgTitleInterwikiCache[$k] = $s;
397 return $s->iw_url;
400 $dbr =& wfGetDB( DB_SLAVE );
401 $res = $dbr->select( 'interwiki',
402 array( 'iw_url', 'iw_local', 'iw_trans' ),
403 array( 'iw_prefix' => $key ), $fname );
404 if( !$res ) {
405 return '';
408 $s = $dbr->fetchObject( $res );
409 if( !$s ) {
410 # Cache non-existence: create a blank object and save it to memcached
411 $s = (object)false;
412 $s->iw_url = '';
413 $s->iw_local = 0;
414 $s->iw_trans = 0;
416 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
417 $wgTitleInterwikiCache[$k] = $s;
419 return $s->iw_url;
423 * Fetch interwiki prefix data from local cache in constant database
425 * More logic is explained in DefaultSettings
427 * @return string URL of interwiki site
428 * @access public
430 function getInterwikiCached( $key ) {
431 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
432 global $wgTitleInterwikiCache;
433 static $db, $site;
435 if (!$db)
436 $db=dba_open($wgInterwikiCache,'r','cdb');
437 /* Resolve site name */
438 if ($wgInterwikiScopes>=3 and !$site) {
439 $site = dba_fetch("__sites:{$wgDBname}", $db);
440 if ($site=="")
441 $site = $wgInterwikiFallbackSite;
443 $value = dba_fetch("{$wgDBname}:{$key}", $db);
444 if ($value=='' and $wgInterwikiScopes>=3) {
445 /* try site-level */
446 $value = dba_fetch("_{$site}:{$key}", $db);
448 if ($value=='' and $wgInterwikiScopes>=2) {
449 /* try globals */
450 $value = dba_fetch("__global:{$key}", $db);
452 if ($value=='undef')
453 $value='';
454 $s = (object)false;
455 $s->iw_url = '';
456 $s->iw_local = 0;
457 $s->iw_trans = 0;
458 if ($value!='') {
459 list($local,$url)=explode(' ',$value,2);
460 $s->iw_url=$url;
461 $s->iw_local=(int)$local;
463 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
464 return $s->iw_url;
467 * Determine whether the object refers to a page within
468 * this project.
470 * @return bool TRUE if this is an in-project interwiki link
471 * or a wikilink, FALSE otherwise
472 * @access public
474 function isLocal() {
475 global $wgTitleInterwikiCache, $wgDBname;
477 if ( $this->mInterwiki != '' ) {
478 # Make sure key is loaded into cache
479 $this->getInterwikiLink( $this->mInterwiki );
480 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
481 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
482 } else {
483 return true;
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return bool TRUE if this is transcludable
492 * @access public
494 function isTrans() {
495 global $wgTitleInterwikiCache, $wgDBname;
497 if ($this->mInterwiki == '')
498 return false;
499 # Make sure key is loaded into cache
500 $this->getInterwikiLink( $this->mInterwiki );
501 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
502 return (bool)($wgTitleInterwikiCache[$k]->iw_trans);
506 * Update the page_touched field for an array of title objects
507 * @todo Inefficient unless the IDs are already loaded into the
508 * link cache
509 * @param array $titles an array of Title objects to be touched
510 * @param string $timestamp the timestamp to use instead of the
511 * default current time
512 * @static
513 * @access public
515 function touchArray( $titles, $timestamp = '' ) {
517 if ( count( $titles ) == 0 ) {
518 return;
520 $dbw =& wfGetDB( DB_MASTER );
521 if ( $timestamp == '' ) {
522 $timestamp = $dbw->timestamp();
525 $page = $dbw->tableName( 'page' );
526 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
527 $first = true;
529 foreach ( $titles as $title ) {
530 if ( $wgUseFileCache ) {
531 $cm = new CacheManager($title);
532 @unlink($cm->fileCacheName());
535 if ( ! $first ) {
536 $sql .= ',';
538 $first = false;
539 $sql .= $title->getArticleID();
541 $sql .= ')';
542 if ( ! $first ) {
543 $dbw->query( $sql, 'Title::touchArray' );
546 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
547 // do them in small chunks:
548 $fname = 'Title::touchArray';
549 foreach( $titles as $title ) {
550 $dbw->update( 'page',
551 array( 'page_touched' => $timestamp ),
552 array(
553 'page_namespace' => $title->getNamespace(),
554 'page_title' => $title->getDBkey() ),
555 $fname );
559 #----------------------------------------------------------------------------
560 # Other stuff
561 #----------------------------------------------------------------------------
563 /** Simple accessors */
565 * Get the text form (spaces not underscores) of the main part
566 * @return string
567 * @access public
569 function getText() { return $this->mTextform; }
571 * Get the URL-encoded form of the main part
572 * @return string
573 * @access public
575 function getPartialURL() { return $this->mUrlform; }
577 * Get the main part with underscores
578 * @return string
579 * @access public
581 function getDBkey() { return $this->mDbkeyform; }
583 * Get the namespace index, i.e. one of the NS_xxxx constants
584 * @return int
585 * @access public
587 function getNamespace() { return $this->mNamespace; }
589 * Get the namespace text
590 * @return string
591 * @access public
593 function getNsText() {
594 global $wgContLang;
595 return $wgContLang->getNsText( $this->mNamespace );
598 * Get the namespace text of the subject (rather than talk) page
599 * @return string
600 * @access public
602 function getSubjectNsText() {
603 global $wgContLang;
604 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
608 * Get the interwiki prefix (or null string)
609 * @return string
610 * @access public
612 function getInterwiki() { return $this->mInterwiki; }
614 * Get the Title fragment (i.e. the bit after the #)
615 * @return string
616 * @access public
618 function getFragment() { return $this->mFragment; }
620 * Get the default namespace index, for when there is no namespace
621 * @return int
622 * @access public
624 function getDefaultNamespace() { return $this->mDefaultNamespace; }
627 * Get title for search index
628 * @return string a stripped-down title string ready for the
629 * search index
631 function getIndexTitle() {
632 return Title::indexTitle( $this->mNamespace, $this->mTextform );
636 * Get the prefixed database key form
637 * @return string the prefixed title, with underscores and
638 * any interwiki and namespace prefixes
639 * @access public
641 function getPrefixedDBkey() {
642 $s = $this->prefix( $this->mDbkeyform );
643 $s = str_replace( ' ', '_', $s );
644 return $s;
648 * Get the prefixed title with spaces.
649 * This is the form usually used for display
650 * @return string the prefixed title, with spaces
651 * @access public
653 function getPrefixedText() {
654 global $wgContLang;
655 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
656 $s = $this->prefix( $this->mTextform );
657 $s = str_replace( '_', ' ', $s );
658 $this->mPrefixedText = $s;
660 return $this->mPrefixedText;
664 * Get the prefixed title with spaces, plus any fragment
665 * (part beginning with '#')
666 * @return string the prefixed title, with spaces and
667 * the fragment, including '#'
668 * @access public
670 function getFullText() {
671 global $wgContLang;
672 $text = $this->getPrefixedText();
673 if( '' != $this->mFragment ) {
674 $text .= '#' . $this->mFragment;
676 return $text;
680 * Get a URL-encoded title (not an actual URL) including interwiki
681 * @return string the URL-encoded form
682 * @access public
684 function getPrefixedURL() {
685 $s = $this->prefix( $this->mDbkeyform );
686 $s = str_replace( ' ', '_', $s );
688 $s = wfUrlencode ( $s ) ;
690 # Cleaning up URL to make it look nice -- is this safe?
691 $s = str_replace( '%28', '(', $s );
692 $s = str_replace( '%29', ')', $s );
694 return $s;
698 * Get a real URL referring to this title, with interwiki link and
699 * fragment
701 * @param string $query an optional query string, not used
702 * for interwiki links
703 * @return string the URL
704 * @access public
706 function getFullURL( $query = '' ) {
707 global $wgContLang, $wgServer, $wgRequest;
709 if ( '' == $this->mInterwiki ) {
710 $url = $this->getLocalUrl( $query );
712 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
713 // Correct fix would be to move the prepending elsewhere.
714 if ($wgRequest->getVal('action') != 'render') {
715 $url = $wgServer . $url;
717 } else {
718 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
720 $namespace = $wgContLang->getNsText( $this->mNamespace );
721 if ( '' != $namespace ) {
722 # Can this actually happen? Interwikis shouldn't be parsed.
723 $namespace .= ':';
725 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
726 if( $query != '' ) {
727 if( false === strpos( $url, '?' ) ) {
728 $url .= '?';
729 } else {
730 $url .= '&';
732 $url .= $query;
734 if ( '' != $this->mFragment ) {
735 $url .= '#' . $this->mFragment;
738 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
739 return $url;
743 * Get a URL with no fragment or server name. If this page is generated
744 * with action=render, $wgServer is prepended.
745 * @param string $query an optional query string; if not specified,
746 * $wgArticlePath will be used.
747 * @return string the URL
748 * @access public
750 function getLocalURL( $query = '' ) {
751 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
753 if ( $this->isExternal() ) {
754 $url = $this->getFullURL();
755 if ( $query ) {
756 // This is currently only used for edit section links in the
757 // context of interwiki transclusion. In theory we should
758 // append the query to the end of any existing query string,
759 // but interwiki transclusion is already broken in that case.
760 $url .= "?$query";
762 } else {
763 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
764 if ( $query == '' ) {
765 $url = str_replace( '$1', $dbkey, $wgArticlePath );
766 } else {
767 global $wgActionPaths;
768 $url = false;
769 if( !empty( $wgActionPaths ) &&
770 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
772 $action = urldecode( $matches[2] );
773 if( isset( $wgActionPaths[$action] ) ) {
774 $query = $matches[1];
775 if( isset( $matches[4] ) ) $query .= $matches[4];
776 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
777 if( $query != '' ) $url .= '?' . $query;
780 if ( $url === false ) {
781 if ( $query == '-' ) {
782 $query = '';
784 $url = "{$wgScript}?title={$dbkey}&{$query}";
788 // FIXME: this causes breakage in various places when we
789 // actually expected a local URL and end up with dupe prefixes.
790 if ($wgRequest->getVal('action') == 'render') {
791 $url = $wgServer . $url;
794 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
795 return $url;
799 * Get an HTML-escaped version of the URL form, suitable for
800 * using in a link, without a server name or fragment
801 * @param string $query an optional query string
802 * @return string the URL
803 * @access public
805 function escapeLocalURL( $query = '' ) {
806 return htmlspecialchars( $this->getLocalURL( $query ) );
810 * Get an HTML-escaped version of the URL form, suitable for
811 * using in a link, including the server name and fragment
813 * @return string the URL
814 * @param string $query an optional query string
815 * @access public
817 function escapeFullURL( $query = '' ) {
818 return htmlspecialchars( $this->getFullURL( $query ) );
822 * Get the URL form for an internal link.
823 * - Used in various Squid-related code, in case we have a different
824 * internal hostname for the server from the exposed one.
826 * @param string $query an optional query string
827 * @return string the URL
828 * @access public
830 function getInternalURL( $query = '' ) {
831 global $wgInternalServer;
832 $url = $wgInternalServer . $this->getLocalURL( $query );
833 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
834 return $url;
838 * Get the edit URL for this Title
839 * @return string the URL, or a null string if this is an
840 * interwiki link
841 * @access public
843 function getEditURL() {
844 global $wgServer, $wgScript;
846 if ( '' != $this->mInterwiki ) { return ''; }
847 $s = $this->getLocalURL( 'action=edit' );
849 return $s;
853 * Get the HTML-escaped displayable text form.
854 * Used for the title field in <a> tags.
855 * @return string the text, including any prefixes
856 * @access public
858 function getEscapedText() {
859 return htmlspecialchars( $this->getPrefixedText() );
863 * Is this Title interwiki?
864 * @return boolean
865 * @access public
867 function isExternal() { return ( '' != $this->mInterwiki ); }
870 * Is this page "semi-protected" - the *only* protection is autoconfirm?
872 * @param string Action to check (default: edit)
873 * @return bool
875 function isSemiProtected( $action = 'edit' ) {
876 $restrictions = $this->getRestrictions( $action );
877 # We do a full compare because this could be an array
878 foreach( $restrictions as $restriction ) {
879 if( strtolower( $restriction ) != 'autoconfirmed' ) {
880 return( false );
883 return( true );
887 * Does the title correspond to a protected article?
888 * @param string $what the action the page is protected from,
889 * by default checks move and edit
890 * @return boolean
891 * @access public
893 function isProtected( $action = '' ) {
894 global $wgRestrictionLevels;
895 if ( -1 == $this->mNamespace ) { return true; }
897 if( $action == 'edit' || $action == '' ) {
898 $r = $this->getRestrictions( 'edit' );
899 foreach( $wgRestrictionLevels as $level ) {
900 if( in_array( $level, $r ) && $level != '' ) {
901 return( true );
906 if( $action == 'move' || $action == '' ) {
907 $r = $this->getRestrictions( 'move' );
908 foreach( $wgRestrictionLevels as $level ) {
909 if( in_array( $level, $r ) && $level != '' ) {
910 return( true );
915 return false;
919 * Is $wgUser is watching this page?
920 * @return boolean
921 * @access public
923 function userIsWatching() {
924 global $wgUser;
926 if ( is_null( $this->mWatched ) ) {
927 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
928 $this->mWatched = false;
929 } else {
930 $this->mWatched = $wgUser->isWatched( $this );
933 return $this->mWatched;
937 * Can $wgUser perform $action this page?
938 * @param string $action action that permission needs to be checked for
939 * @return boolean
940 * @access private
942 function userCan($action) {
943 $fname = 'Title::userCan';
944 wfProfileIn( $fname );
946 global $wgUser;
948 $result = true;
949 if ( !wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) ) ) {
950 wfProfileOut( $fname );
951 return $result;
954 if( NS_SPECIAL == $this->mNamespace ) {
955 wfProfileOut( $fname );
956 return false;
958 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
959 // from taking effect -ævar
960 if( NS_MEDIAWIKI == $this->mNamespace &&
961 !$wgUser->isAllowed('editinterface') ) {
962 wfProfileOut( $fname );
963 return false;
966 if( $this->mDbkeyform == '_' ) {
967 # FIXME: Is this necessary? Shouldn't be allowed anyway...
968 wfProfileOut( $fname );
969 return false;
972 # protect global styles and js
973 if ( NS_MEDIAWIKI == $this->mNamespace
974 && preg_match("/\\.(css|js)$/", $this->mTextform )
975 && !$wgUser->isAllowed('editinterface') ) {
976 wfProfileOut( $fname );
977 return false;
980 # protect css/js subpages of user pages
981 # XXX: this might be better using restrictions
982 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
983 if( NS_USER == $this->mNamespace
984 && preg_match("/\\.(css|js)$/", $this->mTextform )
985 && !$wgUser->isAllowed('editinterface')
986 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
987 wfProfileOut( $fname );
988 return false;
991 foreach( $this->getRestrictions($action) as $right ) {
992 // Backwards compatibility, rewrite sysop -> protect
993 if ( $right == 'sysop' ) {
994 $right = 'protect';
996 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
997 wfProfileOut( $fname );
998 return false;
1002 if( $action == 'move' &&
1003 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1004 wfProfileOut( $fname );
1005 return false;
1008 if( $action == 'create' ) {
1009 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1010 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1011 return false;
1015 wfProfileOut( $fname );
1016 return true;
1020 * Can $wgUser edit this page?
1021 * @return boolean
1022 * @access public
1024 function userCanEdit() {
1025 return $this->userCan('edit');
1029 * Can $wgUser move this page?
1030 * @return boolean
1031 * @access public
1033 function userCanMove() {
1034 return $this->userCan('move');
1038 * Would anybody with sufficient privileges be able to move this page?
1039 * Some pages just aren't movable.
1041 * @return boolean
1042 * @access public
1044 function isMovable() {
1045 return Namespace::isMovable( $this->getNamespace() )
1046 && $this->getInterwiki() == '';
1050 * Can $wgUser read this page?
1051 * @return boolean
1052 * @access public
1054 function userCanRead() {
1055 global $wgUser;
1057 $result = true;
1058 if ( !wfRunHooks( 'userCan', array( &$this, &$wgUser, "read", &$result ) ) ) {
1059 return $result;
1062 if( $wgUser->isAllowed('read') ) {
1063 return true;
1064 } else {
1065 global $wgWhitelistRead;
1067 /** If anon users can create an account,
1068 they need to reach the login page first! */
1069 if( $wgUser->isAllowed( 'createaccount' )
1070 && $this->getNamespace() == NS_SPECIAL
1071 && $this->getText() == 'Userlogin' ) {
1072 return true;
1075 /** some pages are explicitly allowed */
1076 $name = $this->getPrefixedText();
1077 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1078 return true;
1081 # Compatibility with old settings
1082 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1083 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1084 return true;
1088 return false;
1092 * Is this a talk page of some sort?
1093 * @return bool
1094 * @access public
1096 function isTalkPage() {
1097 return Namespace::isTalk( $this->getNamespace() );
1101 * Is this a .css or .js subpage of a user page?
1102 * @return bool
1103 * @access public
1105 function isCssJsSubpage() {
1106 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1109 * Is this a .css subpage of a user page?
1110 * @return bool
1111 * @access public
1113 function isCssSubpage() {
1114 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1117 * Is this a .js subpage of a user page?
1118 * @return bool
1119 * @access public
1121 function isJsSubpage() {
1122 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1125 * Protect css/js subpages of user pages: can $wgUser edit
1126 * this page?
1128 * @return boolean
1129 * @todo XXX: this might be better using restrictions
1130 * @access public
1132 function userCanEditCssJsSubpage() {
1133 global $wgUser;
1134 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1138 * Loads a string into mRestrictions array
1139 * @param string $res restrictions in string format
1140 * @access public
1142 function loadRestrictions( $res ) {
1143 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1144 $temp = explode( '=', trim( $restrict ) );
1145 if(count($temp) == 1) {
1146 // old format should be treated as edit/move restriction
1147 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1148 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1149 } else {
1150 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1153 $this->mRestrictionsLoaded = true;
1157 * Accessor/initialisation for mRestrictions
1158 * @param string $action action that permission needs to be checked for
1159 * @return array the array of groups allowed to edit this article
1160 * @access public
1162 function getRestrictions($action) {
1163 $id = $this->getArticleID();
1164 if ( 0 == $id ) { return array(); }
1166 if ( ! $this->mRestrictionsLoaded ) {
1167 $dbr =& wfGetDB( DB_SLAVE );
1168 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1169 $this->loadRestrictions( $res );
1171 if( isset( $this->mRestrictions[$action] ) ) {
1172 return $this->mRestrictions[$action];
1174 return array();
1178 * Is there a version of this page in the deletion archive?
1179 * @return int the number of archived revisions
1180 * @access public
1182 function isDeleted() {
1183 $fname = 'Title::isDeleted';
1184 if ( $this->getNamespace() < 0 ) {
1185 $n = 0;
1186 } else {
1187 $dbr =& wfGetDB( DB_SLAVE );
1188 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1189 'ar_title' => $this->getDBkey() ), $fname );
1191 return (int)$n;
1195 * Get the article ID for this Title from the link cache,
1196 * adding it if necessary
1197 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1198 * for update
1199 * @return int the ID
1200 * @access public
1202 function getArticleID( $flags = 0 ) {
1203 $linkCache =& LinkCache::singleton();
1204 if ( $flags & GAID_FOR_UPDATE ) {
1205 $oldUpdate = $linkCache->forUpdate( true );
1206 $this->mArticleID = $linkCache->addLinkObj( $this );
1207 $linkCache->forUpdate( $oldUpdate );
1208 } else {
1209 if ( -1 == $this->mArticleID ) {
1210 $this->mArticleID = $linkCache->addLinkObj( $this );
1213 return $this->mArticleID;
1216 function getLatestRevID() {
1217 if ($this->mLatestID !== false)
1218 return $this->mLatestID;
1220 $db =& wfGetDB(DB_SLAVE);
1221 return $this->mLatestID = $db->selectField( 'revision',
1222 "max(rev_id)",
1223 array('rev_page' => $this->getArticleID()),
1224 'Title::getLatestRevID' );
1228 * This clears some fields in this object, and clears any associated
1229 * keys in the "bad links" section of the link cache.
1231 * - This is called from Article::insertNewArticle() to allow
1232 * loading of the new page_id. It's also called from
1233 * Article::doDeleteArticle()
1235 * @param int $newid the new Article ID
1236 * @access public
1238 function resetArticleID( $newid ) {
1239 $linkCache =& LinkCache::singleton();
1240 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1242 if ( 0 == $newid ) { $this->mArticleID = -1; }
1243 else { $this->mArticleID = $newid; }
1244 $this->mRestrictionsLoaded = false;
1245 $this->mRestrictions = array();
1249 * Updates page_touched for this page; called from LinksUpdate.php
1250 * @return bool true if the update succeded
1251 * @access public
1253 function invalidateCache() {
1254 global $wgUseFileCache;
1256 if ( wfReadOnly() ) {
1257 return;
1260 $dbw =& wfGetDB( DB_MASTER );
1261 $success = $dbw->update( 'page',
1262 array( /* SET */
1263 'page_touched' => $dbw->timestamp()
1264 ), array( /* WHERE */
1265 'page_namespace' => $this->getNamespace() ,
1266 'page_title' => $this->getDBkey()
1267 ), 'Title::invalidateCache'
1270 if ($wgUseFileCache) {
1271 $cache = new CacheManager($this);
1272 @unlink($cache->fileCacheName());
1275 return $success;
1279 * Prefix some arbitrary text with the namespace or interwiki prefix
1280 * of this object
1282 * @param string $name the text
1283 * @return string the prefixed text
1284 * @access private
1286 /* private */ function prefix( $name ) {
1287 global $wgContLang;
1289 $p = '';
1290 if ( '' != $this->mInterwiki ) {
1291 $p = $this->mInterwiki . ':';
1293 if ( 0 != $this->mNamespace ) {
1294 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1296 return $p . $name;
1300 * Secure and split - main initialisation function for this object
1302 * Assumes that mDbkeyform has been set, and is urldecoded
1303 * and uses underscores, but not otherwise munged. This function
1304 * removes illegal characters, splits off the interwiki and
1305 * namespace prefixes, sets the other forms, and canonicalizes
1306 * everything.
1307 * @return bool true on success
1308 * @access private
1310 /* private */ function secureAndSplit() {
1311 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1312 $fname = 'Title::secureAndSplit';
1314 # Initialisation
1315 static $rxTc = false;
1316 if( !$rxTc ) {
1317 # % is needed as well
1318 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1321 $this->mInterwiki = $this->mFragment = '';
1322 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1324 # Clean up whitespace
1326 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1327 $t = trim( $t, '_' );
1329 if ( '' == $t ) {
1330 return false;
1333 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1334 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1335 return false;
1338 $this->mDbkeyform = $t;
1340 # Initial colon indicates main namespace rather than specified default
1341 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1342 if ( ':' == $t{0} ) {
1343 $this->mNamespace = NS_MAIN;
1344 $t = substr( $t, 1 ); # remove the colon but continue processing
1347 # Namespace or interwiki prefix
1348 $firstPass = true;
1349 do {
1350 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1351 $p = $m[1];
1352 $lowerNs = strtolower( $p );
1353 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1354 # Canonical namespace
1355 $t = $m[2];
1356 $this->mNamespace = $ns;
1357 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1358 # Ordinary namespace
1359 $t = $m[2];
1360 $this->mNamespace = $ns;
1361 } elseif( $this->getInterwikiLink( $p ) ) {
1362 if( !$firstPass ) {
1363 # Can't make a local interwiki link to an interwiki link.
1364 # That's just crazy!
1365 return false;
1368 # Interwiki link
1369 $t = $m[2];
1370 $this->mInterwiki = strtolower( $p );
1372 # Redundant interwiki prefix to the local wiki
1373 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1374 if( $t == '' ) {
1375 # Can't have an empty self-link
1376 return false;
1378 $this->mInterwiki = '';
1379 $firstPass = false;
1380 # Do another namespace split...
1381 continue;
1384 # If there's an initial colon after the interwiki, that also
1385 # resets the default namespace
1386 if ( $t !== '' && $t[0] == ':' ) {
1387 $this->mNamespace = NS_MAIN;
1388 $t = substr( $t, 1 );
1391 # If there's no recognized interwiki or namespace,
1392 # then let the colon expression be part of the title.
1394 break;
1395 } while( true );
1396 $r = $t;
1398 # We already know that some pages won't be in the database!
1400 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1401 $this->mArticleID = 0;
1403 $f = strstr( $r, '#' );
1404 if ( false !== $f ) {
1405 $this->mFragment = substr( $f, 1 );
1406 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1407 # remove whitespace again: prevents "Foo_bar_#"
1408 # becoming "Foo_bar_"
1409 $r = preg_replace( '/_*$/', '', $r );
1412 # Reject illegal characters.
1414 if( preg_match( $rxTc, $r ) ) {
1415 return false;
1419 * Pages with "/./" or "/../" appearing in the URLs will
1420 * often be unreachable due to the way web browsers deal
1421 * with 'relative' URLs. Forbid them explicitly.
1423 if ( strpos( $r, '.' ) !== false &&
1424 ( $r === '.' || $r === '..' ||
1425 strpos( $r, './' ) === 0 ||
1426 strpos( $r, '../' ) === 0 ||
1427 strpos( $r, '/./' ) !== false ||
1428 strpos( $r, '/../' ) !== false ) )
1430 return false;
1433 # We shouldn't need to query the DB for the size.
1434 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1435 if ( strlen( $r ) > 255 ) {
1436 return false;
1440 * Normally, all wiki links are forced to have
1441 * an initial capital letter so [[foo]] and [[Foo]]
1442 * point to the same place.
1444 * Don't force it for interwikis, since the other
1445 * site might be case-sensitive.
1447 if( $wgCapitalLinks && $this->mInterwiki == '') {
1448 $t = $wgContLang->ucfirst( $r );
1449 } else {
1450 $t = $r;
1454 * Can't make a link to a namespace alone...
1455 * "empty" local links can only be self-links
1456 * with a fragment identifier.
1458 if( $t == '' &&
1459 $this->mInterwiki == '' &&
1460 $this->mNamespace != NS_MAIN ) {
1461 return false;
1464 # Fill fields
1465 $this->mDbkeyform = $t;
1466 $this->mUrlform = wfUrlencode( $t );
1468 $this->mTextform = str_replace( '_', ' ', $t );
1470 return true;
1474 * Get a Title object associated with the talk page of this article
1475 * @return Title the object for the talk page
1476 * @access public
1478 function getTalkPage() {
1479 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1483 * Get a title object associated with the subject page of this
1484 * talk page
1486 * @return Title the object for the subject page
1487 * @access public
1489 function getSubjectPage() {
1490 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1494 * Get an array of Title objects linking to this Title
1495 * Also stores the IDs in the link cache.
1497 * @param string $options may be FOR UPDATE
1498 * @return array the Title objects linking here
1499 * @access public
1501 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1502 $linkCache =& LinkCache::singleton();
1503 $id = $this->getArticleID();
1505 if ( $options ) {
1506 $db =& wfGetDB( DB_MASTER );
1507 } else {
1508 $db =& wfGetDB( DB_SLAVE );
1511 $res = $db->select( array( 'page', $table ),
1512 array( 'page_namespace', 'page_title', 'page_id' ),
1513 array(
1514 "{$prefix}_from=page_id",
1515 "{$prefix}_namespace" => $this->getNamespace(),
1516 "{$prefix}_title" => $this->getDbKey() ),
1517 'Title::getLinksTo',
1518 $options );
1520 $retVal = array();
1521 if ( $db->numRows( $res ) ) {
1522 while ( $row = $db->fetchObject( $res ) ) {
1523 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1524 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1525 $retVal[] = $titleObj;
1529 $db->freeResult( $res );
1530 return $retVal;
1534 * Get an array of Title objects using this Title as a template
1535 * Also stores the IDs in the link cache.
1537 * @param string $options may be FOR UPDATE
1538 * @return array the Title objects linking here
1539 * @access public
1541 function getTemplateLinksTo( $options = '' ) {
1542 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1546 * Get an array of Title objects referring to non-existent articles linked from this page
1548 * @param string $options may be FOR UPDATE
1549 * @return array the Title objects
1550 * @access public
1552 function getBrokenLinksFrom( $options = '' ) {
1553 if ( $options ) {
1554 $db =& wfGetDB( DB_MASTER );
1555 } else {
1556 $db =& wfGetDB( DB_SLAVE );
1559 $res = $db->safeQuery(
1560 "SELECT pl_namespace, pl_title
1561 FROM !
1562 LEFT JOIN !
1563 ON pl_namespace=page_namespace
1564 AND pl_title=page_title
1565 WHERE pl_from=?
1566 AND page_namespace IS NULL
1568 $db->tableName( 'pagelinks' ),
1569 $db->tableName( 'page' ),
1570 $this->getArticleId(),
1571 $options );
1573 $retVal = array();
1574 if ( $db->numRows( $res ) ) {
1575 while ( $row = $db->fetchObject( $res ) ) {
1576 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1579 $db->freeResult( $res );
1580 return $retVal;
1585 * Get a list of URLs to purge from the Squid cache when this
1586 * page changes
1588 * @return array the URLs
1589 * @access public
1591 function getSquidURLs() {
1592 return array(
1593 $this->getInternalURL(),
1594 $this->getInternalURL( 'action=history' )
1599 * Move this page without authentication
1600 * @param Title &$nt the new page Title
1601 * @access public
1603 function moveNoAuth( &$nt ) {
1604 return $this->moveTo( $nt, false );
1608 * Check whether a given move operation would be valid.
1609 * Returns true if ok, or a message key string for an error message
1610 * if invalid. (Scarrrrry ugly interface this.)
1611 * @param Title &$nt the new title
1612 * @param bool $auth indicates whether $wgUser's permissions
1613 * should be checked
1614 * @return mixed true on success, message name on failure
1615 * @access public
1617 function isValidMoveOperation( &$nt, $auth = true ) {
1618 global $wgUser;
1619 if( !$this or !$nt ) {
1620 return 'badtitletext';
1622 if( $this->equals( $nt ) ) {
1623 return 'selfmove';
1625 if( !$this->isMovable() || !$nt->isMovable() ) {
1626 return 'immobile_namespace';
1629 $oldid = $this->getArticleID();
1630 $newid = $nt->getArticleID();
1632 if ( strlen( $nt->getDBkey() ) < 1 ) {
1633 return 'articleexists';
1635 if ( ( '' == $this->getDBkey() ) ||
1636 ( !$oldid ) ||
1637 ( '' == $nt->getDBkey() ) ) {
1638 return 'badarticleerror';
1641 if ( $auth && (
1642 !$this->userCanEdit() || !$nt->userCanEdit() ||
1643 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1644 return 'protectedpage';
1647 # The move is allowed only if (1) the target doesn't exist, or
1648 # (2) the target is a redirect to the source, and has no history
1649 # (so we can undo bad moves right after they're done).
1651 if ( 0 != $newid ) { # Target exists; check for validity
1652 if ( ! $this->isValidMoveTarget( $nt ) ) {
1653 return 'articleexists';
1656 return true;
1660 * Move a title to a new location
1661 * @param Title &$nt the new title
1662 * @param bool $auth indicates whether $wgUser's permissions
1663 * should be checked
1664 * @return mixed true on success, message name on failure
1665 * @access public
1667 function moveTo( &$nt, $auth = true, $reason = '' ) {
1668 $err = $this->isValidMoveOperation( $nt, $auth );
1669 if( is_string( $err ) ) {
1670 return $err;
1673 $pageid = $this->getArticleID();
1674 if( $nt->exists() ) {
1675 $this->moveOverExistingRedirect( $nt, $reason );
1676 $pageCountChange = 0;
1677 } else { # Target didn't exist, do normal move.
1678 $this->moveToNewTitle( $nt, $reason );
1679 $pageCountChange = 1;
1681 $redirid = $this->getArticleID();
1683 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1684 $dbw =& wfGetDB( DB_MASTER );
1685 $categorylinks = $dbw->tableName( 'categorylinks' );
1686 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1687 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1688 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1689 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1691 # Update watchlists
1693 $oldnamespace = $this->getNamespace() & ~1;
1694 $newnamespace = $nt->getNamespace() & ~1;
1695 $oldtitle = $this->getDBkey();
1696 $newtitle = $nt->getDBkey();
1698 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1699 WatchedItem::duplicateEntries( $this, $nt );
1702 # Update search engine
1703 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1704 $u->doUpdate();
1705 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1706 $u->doUpdate();
1708 # Update site_stats
1709 if ( $this->getNamespace() == NS_MAIN and $nt->getNamespace() != NS_MAIN ) {
1710 # Moved out of main namespace
1711 # not viewed, edited, removing
1712 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1713 } elseif ( $this->getNamespace() != NS_MAIN and $nt->getNamespace() == NS_MAIN ) {
1714 # Moved into main namespace
1715 # not viewed, edited, adding
1716 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1717 } elseif ( $pageCountChange ) {
1718 # Added redirect
1719 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1720 } else{
1721 $u = false;
1723 if ( $u ) {
1724 $u->doUpdate();
1727 global $wgUser;
1728 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1729 return true;
1733 * Move page to a title which is at present a redirect to the
1734 * source page
1736 * @param Title &$nt the page to move to, which should currently
1737 * be a redirect
1738 * @access private
1740 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1741 global $wgUser, $wgUseSquid, $wgMwRedir;
1742 $fname = 'Title::moveOverExistingRedirect';
1743 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1745 if ( $reason ) {
1746 $comment .= ": $reason";
1749 $now = wfTimestampNow();
1750 $rand = wfRandom();
1751 $newid = $nt->getArticleID();
1752 $oldid = $this->getArticleID();
1753 $dbw =& wfGetDB( DB_MASTER );
1754 $linkCache =& LinkCache::singleton();
1756 # Delete the old redirect. We don't save it to history since
1757 # by definition if we've got here it's rather uninteresting.
1758 # We have to remove it so that the next step doesn't trigger
1759 # a conflict on the unique namespace+title index...
1760 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1762 # Save a null revision in the page's history notifying of the move
1763 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1764 $nullRevId = $nullRevision->insertOn( $dbw );
1766 # Change the name of the target page:
1767 $dbw->update( 'page',
1768 /* SET */ array(
1769 'page_touched' => $dbw->timestamp($now),
1770 'page_namespace' => $nt->getNamespace(),
1771 'page_title' => $nt->getDBkey(),
1772 'page_latest' => $nullRevId,
1774 /* WHERE */ array( 'page_id' => $oldid ),
1775 $fname
1777 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1779 # Recreate the redirect, this time in the other direction.
1780 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1781 $redirectArticle = new Article( $this );
1782 $newid = $redirectArticle->insertOn( $dbw );
1783 $redirectRevision = new Revision( array(
1784 'page' => $newid,
1785 'comment' => $comment,
1786 'text' => $redirectText ) );
1787 $revid = $redirectRevision->insertOn( $dbw );
1788 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1789 $linkCache->clearLink( $this->getPrefixedDBkey() );
1791 # Log the move
1792 $log = new LogPage( 'move' );
1793 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1795 # Now, we record the link from the redirect to the new title.
1796 # It should have no other outgoing links...
1797 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1798 $dbw->insert( 'pagelinks',
1799 array(
1800 'pl_from' => $newid,
1801 'pl_namespace' => $nt->getNamespace(),
1802 'pl_title' => $nt->getDbKey() ),
1803 $fname );
1805 # Purge squid
1806 if ( $wgUseSquid ) {
1807 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1808 $u = new SquidUpdate( $urls );
1809 $u->doUpdate();
1814 * Move page to non-existing title.
1815 * @param Title &$nt the new Title
1816 * @access private
1818 function moveToNewTitle( &$nt, $reason = '' ) {
1819 global $wgUser, $wgUseSquid;
1820 global $wgMwRedir;
1821 $fname = 'MovePageForm::moveToNewTitle';
1822 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1823 if ( $reason ) {
1824 $comment .= ": $reason";
1827 $newid = $nt->getArticleID();
1828 $oldid = $this->getArticleID();
1829 $dbw =& wfGetDB( DB_MASTER );
1830 $now = $dbw->timestamp();
1831 $rand = wfRandom();
1832 $linkCache =& LinkCache::singleton();
1834 # Save a null revision in the page's history notifying of the move
1835 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1836 $nullRevId = $nullRevision->insertOn( $dbw );
1838 # Rename cur entry
1839 $dbw->update( 'page',
1840 /* SET */ array(
1841 'page_touched' => $now,
1842 'page_namespace' => $nt->getNamespace(),
1843 'page_title' => $nt->getDBkey(),
1844 'page_latest' => $nullRevId,
1846 /* WHERE */ array( 'page_id' => $oldid ),
1847 $fname
1850 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1852 # Insert redirect
1853 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1854 $redirectArticle = new Article( $this );
1855 $newid = $redirectArticle->insertOn( $dbw );
1856 $redirectRevision = new Revision( array(
1857 'page' => $newid,
1858 'comment' => $comment,
1859 'text' => $redirectText ) );
1860 $revid = $redirectRevision->insertOn( $dbw );
1861 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1862 $linkCache->clearLink( $this->getPrefixedDBkey() );
1864 # Log the move
1865 $log = new LogPage( 'move' );
1866 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1868 # Purge caches as per article creation
1869 Article::onArticleCreate( $nt );
1871 # Record the just-created redirect's linking to the page
1872 $dbw->insert( 'pagelinks',
1873 array(
1874 'pl_from' => $newid,
1875 'pl_namespace' => $nt->getNamespace(),
1876 'pl_title' => $nt->getDBkey() ),
1877 $fname );
1879 # Non-existent target may have had broken links to it; these must
1880 # now be touched to update link coloring.
1881 $nt->touchLinks();
1883 # Purge old title from squid
1884 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1885 $titles = $nt->getLinksTo();
1886 if ( $wgUseSquid ) {
1887 $urls = $this->getSquidURLs();
1888 foreach ( $titles as $linkTitle ) {
1889 $urls[] = $linkTitle->getInternalURL();
1891 $u = new SquidUpdate( $urls );
1892 $u->doUpdate();
1897 * Checks if $this can be moved to a given Title
1898 * - Selects for update, so don't call it unless you mean business
1900 * @param Title &$nt the new title to check
1901 * @access public
1903 function isValidMoveTarget( $nt ) {
1905 $fname = 'Title::isValidMoveTarget';
1906 $dbw =& wfGetDB( DB_MASTER );
1908 # Is it a redirect?
1909 $id = $nt->getArticleID();
1910 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1911 array( 'page_is_redirect','old_text','old_flags' ),
1912 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1913 $fname, 'FOR UPDATE' );
1915 if ( !$obj || 0 == $obj->page_is_redirect ) {
1916 # Not a redirect
1917 return false;
1919 $text = Revision::getRevisionText( $obj );
1921 # Does the redirect point to the source?
1922 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1923 $redirTitle = Title::newFromText( $m[1] );
1924 if( !is_object( $redirTitle ) ||
1925 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1926 return false;
1928 } else {
1929 # Fail safe
1930 return false;
1933 # Does the article have a history?
1934 $row = $dbw->selectRow( array( 'page', 'revision'),
1935 array( 'rev_id' ),
1936 array( 'page_namespace' => $nt->getNamespace(),
1937 'page_title' => $nt->getDBkey(),
1938 'page_id=rev_page AND page_latest != rev_id'
1939 ), $fname, 'FOR UPDATE'
1942 # Return true if there was no history
1943 return $row === false;
1947 * Create a redirect; fails if the title already exists; does
1948 * not notify RC
1950 * @param Title $dest the destination of the redirect
1951 * @param string $comment the comment string describing the move
1952 * @return bool true on success
1953 * @access public
1955 function createRedirect( $dest, $comment ) {
1956 global $wgUser;
1957 if ( $this->getArticleID() ) {
1958 return false;
1961 $fname = 'Title::createRedirect';
1962 $dbw =& wfGetDB( DB_MASTER );
1964 $article = new Article( $this );
1965 $newid = $article->insertOn( $dbw );
1966 $revision = new Revision( array(
1967 'page' => $newid,
1968 'comment' => $comment,
1969 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1970 ) );
1971 $revisionId = $revision->insertOn( $dbw );
1972 $article->updateRevisionOn( $dbw, $revision, 0 );
1974 # Link table
1975 $dbw->insert( 'pagelinks',
1976 array(
1977 'pl_from' => $newid,
1978 'pl_namespace' => $dest->getNamespace(),
1979 'pl_title' => $dest->getDbKey()
1980 ), $fname
1983 Article::onArticleCreate( $this );
1984 return true;
1988 * Get categories to which this Title belongs and return an array of
1989 * categories' names.
1991 * @return array an array of parents in the form:
1992 * $parent => $currentarticle
1993 * @access public
1995 function getParentCategories() {
1996 global $wgContLang,$wgUser;
1998 $titlekey = $this->getArticleId();
1999 $dbr =& wfGetDB( DB_SLAVE );
2000 $categorylinks = $dbr->tableName( 'categorylinks' );
2002 # NEW SQL
2003 $sql = "SELECT * FROM $categorylinks"
2004 ." WHERE cl_from='$titlekey'"
2005 ." AND cl_from <> '0'"
2006 ." ORDER BY cl_sortkey";
2008 $res = $dbr->query ( $sql ) ;
2010 if($dbr->numRows($res) > 0) {
2011 while ( $x = $dbr->fetchObject ( $res ) )
2012 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2013 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2014 $dbr->freeResult ( $res ) ;
2015 } else {
2016 $data = '';
2018 return $data;
2022 * Get a tree of parent categories
2023 * @param array $children an array with the children in the keys, to check for circular refs
2024 * @return array
2025 * @access public
2027 function getParentCategoryTree( $children = array() ) {
2028 $parents = $this->getParentCategories();
2030 if($parents != '') {
2031 foreach($parents as $parent => $current) {
2032 if ( array_key_exists( $parent, $children ) ) {
2033 # Circular reference
2034 $stack[$parent] = array();
2035 } else {
2036 $nt = Title::newFromText($parent);
2037 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2040 return $stack;
2041 } else {
2042 return array();
2048 * Get an associative array for selecting this title from
2049 * the "page" table
2051 * @return array
2052 * @access public
2054 function pageCond() {
2055 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2059 * Get the revision ID of the previous revision
2061 * @param integer $revision Revision ID. Get the revision that was before this one.
2062 * @return interger $oldrevision|false
2064 function getPreviousRevisionID( $revision ) {
2065 $dbr =& wfGetDB( DB_SLAVE );
2066 return $dbr->selectField( 'revision', 'rev_id',
2067 'rev_page=' . intval( $this->getArticleId() ) .
2068 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2072 * Get the revision ID of the next revision
2074 * @param integer $revision Revision ID. Get the revision that was after this one.
2075 * @return interger $oldrevision|false
2077 function getNextRevisionID( $revision ) {
2078 $dbr =& wfGetDB( DB_SLAVE );
2079 return $dbr->selectField( 'revision', 'rev_id',
2080 'rev_page=' . intval( $this->getArticleId() ) .
2081 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2085 * Compare with another title.
2087 * @param Title $title
2088 * @return bool
2090 function equals( $title ) {
2091 return $this->getInterwiki() == $title->getInterwiki()
2092 && $this->getNamespace() == $title->getNamespace()
2093 && $this->getDbkey() == $title->getDbkey();
2097 * Check if page exists
2098 * @return bool
2100 function exists() {
2101 return $this->getArticleId() != 0;
2105 * Should a link should be displayed as a known link, just based on its title?
2107 * Currently, a self-link with a fragment and special pages are in
2108 * this category. Special pages never exist in the database.
2110 function isAlwaysKnown() {
2111 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2112 || NS_SPECIAL == $this->mNamespace;
2116 * Update page_touched timestamps on pages linking to this title.
2117 * In principal, this could be backgrounded and could also do squid
2118 * purging.
2120 function touchLinks() {
2121 $fname = 'Title::touchLinks';
2123 $dbw =& wfGetDB( DB_MASTER );
2125 $res = $dbw->select( 'pagelinks',
2126 array( 'pl_from' ),
2127 array(
2128 'pl_namespace' => $this->getNamespace(),
2129 'pl_title' => $this->getDbKey() ),
2130 $fname );
2132 $toucharr = array();
2133 while( $row = $dbw->fetchObject( $res ) ) {
2134 $toucharr[] = $row->pl_from;
2136 $dbw->freeResult( $res );
2138 if( $this->getNamespace() == NS_CATEGORY ) {
2139 // Categories show up in a separate set of links as well
2140 $res = $dbw->select( 'categorylinks',
2141 array( 'cl_from' ),
2142 array( 'cl_to' => $this->getDbKey() ),
2143 $fname );
2144 while( $row = $dbw->fetchObject( $res ) ) {
2145 $toucharr[] = $row->cl_from;
2147 $dbw->freeResult( $res );
2150 if (!count($toucharr))
2151 return;
2152 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2153 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2156 function trackbackURL() {
2157 global $wgTitle, $wgScriptPath, $wgServer;
2159 return "$wgServer$wgScriptPath/trackback.php?article="
2160 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2163 function trackbackRDF() {
2164 $url = htmlspecialchars($this->getFullURL());
2165 $title = htmlspecialchars($this->getText());
2166 $tburl = $this->trackbackURL();
2168 return "
2169 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2170 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2171 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2172 <rdf:Description
2173 rdf:about=\"$url\"
2174 dc:identifier=\"$url\"
2175 dc:title=\"$title\"
2176 trackback:ping=\"$tburl\" />
2177 </rdf:RDF>";