Some static functions. Fix strict errors when running updateSearchIndex.php
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 define ( 'GAID_FOR_UPDATE', 1 );
12
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
17 # reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
19
20 /**
21 * Title class
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
24 *
25 * @package MediaWiki
26 */
27 class Title {
28 /**
29 * Static cache variables
30 */
31 static private $titleCache=array();
32 static private $interwikiCache=array();
33
34
35 /**
36 * All member variables should be considered private
37 * Please use the accessor functions
38 */
39
40 /**#@+
41 * @private
42 */
43
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
59 /**#@-*/
60
61
62 /**
63 * Constructor
64 * @private
65 */
66 /* private */ function Title() {
67 $this->mInterwiki = $this->mUrlform =
68 $this->mTextform = $this->mDbkeyform = '';
69 $this->mArticleID = -1;
70 $this->mNamespace = NS_MAIN;
71 $this->mRestrictionsLoaded = false;
72 $this->mRestrictions = array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
74 # See bug #696
75 $this->mDefaultNamespace = NS_MAIN;
76 $this->mWatched = NULL;
77 $this->mLatestID = false;
78 }
79
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return Title the new object, or NULL on an error
86 * @static
87 * @access public
88 */
89 /* static */ function newFromDBkey( $key ) {
90 $t = new Title();
91 $t->mDbkeyform = $key;
92 if( $t->secureAndSplit() )
93 return $t;
94 else
95 return NULL;
96 }
97
98 /**
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
101 *
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
104 * are accepted
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
108 * @static
109 * @access public
110 */
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
112 if( is_object( $text ) ) {
113 throw new MWException( 'Title::newFromText given an object' );
114 }
115
116 /**
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
120 * caching them.
121 *
122 * In theory these are value objects and won't get changed...
123 */
124 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
125 return Title::$titleCache[$text];
126 }
127
128 /**
129 * Convert things like &eacute; &#257; or &#x3017; into real text...
130 */
131 $filteredText = Sanitizer::decodeCharReferences( $text );
132
133 $t = new Title();
134 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace = $defaultNamespace;
136
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN ) {
140 if( $cachedcount >= MW_TITLECACHE_MAX ) {
141 # Avoid memory leaks on mass operations...
142 Title::$titleCache = array();
143 $cachedcount=0;
144 }
145 $cachedcount++;
146 Title::$titleCache[$text] =& $t;
147 }
148 return $t;
149 } else {
150 $ret = NULL;
151 return $ret;
152 }
153 }
154
155 /**
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
160 * @static
161 * @access public
162 */
163 public static function newFromURL( $url ) {
164 global $wgLegalTitleChars;
165 $t = new Title();
166
167 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
168 # but some URLs used it as a space replacement and they still come
169 # from some external search tools.
170 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
171 $url = str_replace( '+', ' ', $url );
172 }
173
174 $t->mDbkeyform = str_replace( ' ', '_', $url );
175 if( $t->secureAndSplit() ) {
176 return $t;
177 } else {
178 return NULL;
179 }
180 }
181
182 /**
183 * Create a new Title from an article ID
184 *
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
187 *
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
190 * @access public
191 * @static
192 */
193 public static function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE );
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
200 } else {
201 $title = NULL;
202 }
203 return $title;
204 }
205
206 /**
207 * Make an array of titles from an array of IDs
208 */
209 function newFromIDs( $ids ) {
210 $dbr =& wfGetDB( DB_SLAVE );
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
213
214 $titles = array();
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
217 }
218 return $titles;
219 }
220
221 /**
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
227 *
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
231 * @static
232 * @access public
233 */
234 public static function &makeTitle( $ns, $title ) {
235 $t = new Title();
236 $t->mInterwiki = '';
237 $t->mFragment = '';
238 $t->mNamespace = intval( $ns );
239 $t->mDbkeyform = str_replace( ' ', '_', $title );
240 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
241 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
242 $t->mTextform = str_replace( '_', ' ', $title );
243 return $t;
244 }
245
246 /**
247 * Create a new Title from a namespace index and a DB key.
248 * The parameters will be checked for validity, which is a bit slower
249 * than makeTitle() but safer for user-provided data.
250 *
251 * @param int $ns the namespace of the article
252 * @param string $title the database key form
253 * @return Title the new object, or NULL on an error
254 * @static
255 * @access public
256 */
257 public static function makeTitleSafe( $ns, $title ) {
258 $t = new Title();
259 $t->mDbkeyform = Title::makeName( $ns, $title );
260 if( $t->secureAndSplit() ) {
261 return $t;
262 } else {
263 return NULL;
264 }
265 }
266
267 /**
268 * Create a new Title for the Main Page
269 *
270 * @static
271 * @return Title the new object
272 * @access public
273 */
274 public static function newMainPage() {
275 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
276 }
277
278 /**
279 * Create a new Title for a redirect
280 * @param string $text the redirect title text
281 * @return Title the new object, or NULL if the text is not a
282 * valid redirect
283 */
284 public static function newFromRedirect( $text ) {
285 $mwRedir = MagicWord::get( 'redirect' );
286 $rt = NULL;
287 if ( $mwRedir->matchStart( $text ) ) {
288 $m = array();
289 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
290 # categories are escaped using : for example one can enter:
291 # #REDIRECT [[:Category:Music]]. Need to remove it.
292 if ( substr($m[1],0,1) == ':') {
293 # We don't want to keep the ':'
294 $m[1] = substr( $m[1], 1 );
295 }
296
297 $rt = Title::newFromText( $m[1] );
298 # Disallow redirects to Special:Userlogout
299 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
300 $rt = NULL;
301 }
302 }
303 }
304 return $rt;
305 }
306
307 #----------------------------------------------------------------------------
308 # Static functions
309 #----------------------------------------------------------------------------
310
311 /**
312 * Get the prefixed DB key associated with an ID
313 * @param int $id the page_id of the article
314 * @return Title an object representing the article, or NULL
315 * if no such article was found
316 * @static
317 * @access public
318 */
319 function nameOf( $id ) {
320 $fname = 'Title::nameOf';
321 $dbr =& wfGetDB( DB_SLAVE );
322
323 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
324 if ( $s === false ) { return NULL; }
325
326 $n = Title::makeName( $s->page_namespace, $s->page_title );
327 return $n;
328 }
329
330 /**
331 * Get a regex character class describing the legal characters in a link
332 * @return string the list of characters, not delimited
333 * @static
334 * @access public
335 */
336 public static function legalChars() {
337 global $wgLegalTitleChars;
338 return $wgLegalTitleChars;
339 }
340
341 /**
342 * Get a string representation of a title suitable for
343 * including in a search index
344 *
345 * @param int $ns a namespace index
346 * @param string $title text-form main part
347 * @return string a stripped-down title string ready for the
348 * search index
349 */
350 public static function indexTitle( $ns, $title ) {
351 global $wgContLang;
352
353 $lc = SearchEngine::legalSearchChars() . '&#;';
354 $t = $wgContLang->stripForSearch( $title );
355 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
356 $t = $wgContLang->lc( $t );
357
358 # Handle 's, s'
359 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
360 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
361
362 $t = preg_replace( "/\\s+/", ' ', $t );
363
364 if ( $ns == NS_IMAGE ) {
365 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
366 }
367 return trim( $t );
368 }
369
370 /*
371 * Make a prefixed DB key from a DB key and a namespace index
372 * @param int $ns numerical representation of the namespace
373 * @param string $title the DB key form the title
374 * @return string the prefixed form of the title
375 */
376 public static function makeName( $ns, $title ) {
377 global $wgContLang;
378
379 $n = $wgContLang->getNsText( $ns );
380 return $n == '' ? $title : "$n:$title";
381 }
382
383 /**
384 * Returns the URL associated with an interwiki prefix
385 * @param string $key the interwiki prefix (e.g. "MeatBall")
386 * @return the associated URL, containing "$1", which should be
387 * replaced by an article title
388 * @static (arguably)
389 * @access public
390 */
391 function getInterwikiLink( $key ) {
392 global $wgMemc, $wgInterwikiExpiry;
393 global $wgInterwikiCache, $wgContLang;
394 $fname = 'Title::getInterwikiLink';
395
396 $key = $wgContLang->lc( $key );
397
398 $k = wfMemcKey( 'interwiki', $key );
399 if( array_key_exists( $k, Title::$interwikiCache ) ) {
400 return Title::$interwikiCache[$k]->iw_url;
401 }
402
403 if ($wgInterwikiCache) {
404 return Title::getInterwikiCached( $key );
405 }
406
407 $s = $wgMemc->get( $k );
408 # Ignore old keys with no iw_local
409 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
410 Title::$interwikiCache[$k] = $s;
411 return $s->iw_url;
412 }
413
414 $dbr =& wfGetDB( DB_SLAVE );
415 $res = $dbr->select( 'interwiki',
416 array( 'iw_url', 'iw_local', 'iw_trans' ),
417 array( 'iw_prefix' => $key ), $fname );
418 if( !$res ) {
419 return '';
420 }
421
422 $s = $dbr->fetchObject( $res );
423 if( !$s ) {
424 # Cache non-existence: create a blank object and save it to memcached
425 $s = (object)false;
426 $s->iw_url = '';
427 $s->iw_local = 0;
428 $s->iw_trans = 0;
429 }
430 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
431 Title::$interwikiCache[$k] = $s;
432
433 return $s->iw_url;
434 }
435
436 /**
437 * Fetch interwiki prefix data from local cache in constant database
438 *
439 * More logic is explained in DefaultSettings
440 *
441 * @return string URL of interwiki site
442 * @access public
443 */
444 function getInterwikiCached( $key ) {
445 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
446 static $db, $site;
447
448 if (!$db)
449 $db=dba_open($wgInterwikiCache,'r','cdb');
450 /* Resolve site name */
451 if ($wgInterwikiScopes>=3 and !$site) {
452 $site = dba_fetch('__sites:' . wfWikiID(), $db);
453 if ($site=="")
454 $site = $wgInterwikiFallbackSite;
455 }
456 $value = dba_fetch( wfMemcKey( $key ), $db);
457 if ($value=='' and $wgInterwikiScopes>=3) {
458 /* try site-level */
459 $value = dba_fetch("_{$site}:{$key}", $db);
460 }
461 if ($value=='' and $wgInterwikiScopes>=2) {
462 /* try globals */
463 $value = dba_fetch("__global:{$key}", $db);
464 }
465 if ($value=='undef')
466 $value='';
467 $s = (object)false;
468 $s->iw_url = '';
469 $s->iw_local = 0;
470 $s->iw_trans = 0;
471 if ($value!='') {
472 list($local,$url)=explode(' ',$value,2);
473 $s->iw_url=$url;
474 $s->iw_local=(int)$local;
475 }
476 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
477 return $s->iw_url;
478 }
479 /**
480 * Determine whether the object refers to a page within
481 * this project.
482 *
483 * @return bool TRUE if this is an in-project interwiki link
484 * or a wikilink, FALSE otherwise
485 * @access public
486 */
487 function isLocal() {
488 if ( $this->mInterwiki != '' ) {
489 # Make sure key is loaded into cache
490 $this->getInterwikiLink( $this->mInterwiki );
491 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
492 return (bool)(Title::$interwikiCache[$k]->iw_local);
493 } else {
494 return true;
495 }
496 }
497
498 /**
499 * Determine whether the object refers to a page within
500 * this project and is transcludable.
501 *
502 * @return bool TRUE if this is transcludable
503 * @access public
504 */
505 function isTrans() {
506 if ($this->mInterwiki == '')
507 return false;
508 # Make sure key is loaded into cache
509 $this->getInterwikiLink( $this->mInterwiki );
510 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
511 return (bool)(Title::$interwikiCache[$k]->iw_trans);
512 }
513
514 /**
515 * Determine whether a Title is a redirect
516 *
517 * @return bool
518 */
519 public function isRedirect() {
520 $article = new Article( $this );
521 return $article->isRedirect();
522 }
523
524 /**
525 * Update the page_touched field for an array of title objects
526 * @todo Inefficient unless the IDs are already loaded into the
527 * link cache
528 * @param array $titles an array of Title objects to be touched
529 * @param string $timestamp the timestamp to use instead of the
530 * default current time
531 * @static
532 * @access public
533 */
534 function touchArray( $titles, $timestamp = '' ) {
535
536 if ( count( $titles ) == 0 ) {
537 return;
538 }
539 $dbw =& wfGetDB( DB_MASTER );
540 if ( $timestamp == '' ) {
541 $timestamp = $dbw->timestamp();
542 }
543 /*
544 $page = $dbw->tableName( 'page' );
545 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
546 $first = true;
547
548 foreach ( $titles as $title ) {
549 if ( $wgUseFileCache ) {
550 $cm = new HTMLFileCache($title);
551 @unlink($cm->fileCacheName());
552 }
553
554 if ( ! $first ) {
555 $sql .= ',';
556 }
557 $first = false;
558 $sql .= $title->getArticleID();
559 }
560 $sql .= ')';
561 if ( ! $first ) {
562 $dbw->query( $sql, 'Title::touchArray' );
563 }
564 */
565 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
566 // do them in small chunks:
567 $fname = 'Title::touchArray';
568 foreach( $titles as $title ) {
569 $dbw->update( 'page',
570 array( 'page_touched' => $timestamp ),
571 array(
572 'page_namespace' => $title->getNamespace(),
573 'page_title' => $title->getDBkey() ),
574 $fname );
575 }
576 }
577
578 /**
579 * Escape a text fragment, say from a link, for a URL
580 */
581 static function escapeFragmentForURL( $fragment ) {
582 $fragment = str_replace( ' ', '_', $fragment );
583 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
584 $replaceArray = array(
585 '%3A' => ':',
586 '%' => '.'
587 );
588 return strtr( $fragment, $replaceArray );
589 }
590
591 #----------------------------------------------------------------------------
592 # Other stuff
593 #----------------------------------------------------------------------------
594
595 /** Simple accessors */
596 /**
597 * Get the text form (spaces not underscores) of the main part
598 * @return string
599 * @access public
600 */
601 function getText() { return $this->mTextform; }
602 /**
603 * Get the URL-encoded form of the main part
604 * @return string
605 * @access public
606 */
607 function getPartialURL() { return $this->mUrlform; }
608 /**
609 * Get the main part with underscores
610 * @return string
611 * @access public
612 */
613 function getDBkey() { return $this->mDbkeyform; }
614 /**
615 * Get the namespace index, i.e. one of the NS_xxxx constants
616 * @return int
617 * @access public
618 */
619 function getNamespace() { return $this->mNamespace; }
620 /**
621 * Get the namespace text
622 * @return string
623 * @access public
624 */
625 function getNsText() {
626 global $wgContLang, $wgCanonicalNamespaceNames;
627
628 if ( '' != $this->mInterwiki ) {
629 // This probably shouldn't even happen. ohh man, oh yuck.
630 // But for interwiki transclusion it sometimes does.
631 // Shit. Shit shit shit.
632 //
633 // Use the canonical namespaces if possible to try to
634 // resolve a foreign namespace.
635 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
636 return $wgCanonicalNamespaceNames[$this->mNamespace];
637 }
638 }
639 return $wgContLang->getNsText( $this->mNamespace );
640 }
641 /**
642 * Get the namespace text of the subject (rather than talk) page
643 * @return string
644 * @access public
645 */
646 function getSubjectNsText() {
647 global $wgContLang;
648 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
649 }
650
651 /**
652 * Get the namespace text of the talk page
653 * @return string
654 */
655 function getTalkNsText() {
656 global $wgContLang;
657 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
658 }
659
660 /**
661 * Could this title have a corresponding talk page?
662 * @return bool
663 */
664 function canTalk() {
665 return( Namespace::canTalk( $this->mNamespace ) );
666 }
667
668 /**
669 * Get the interwiki prefix (or null string)
670 * @return string
671 * @access public
672 */
673 function getInterwiki() { return $this->mInterwiki; }
674 /**
675 * Get the Title fragment (i.e. the bit after the #) in text form
676 * @return string
677 * @access public
678 */
679 function getFragment() { return $this->mFragment; }
680 /**
681 * Get the fragment in URL form, including the "#" character if there is one
682 *
683 * @return string
684 * @access public
685 */
686 function getFragmentForURL() {
687 if ( $this->mFragment == '' ) {
688 return '';
689 } else {
690 return '#' . Title::escapeFragmentForURL( $this->mFragment );
691 }
692 }
693 /**
694 * Get the default namespace index, for when there is no namespace
695 * @return int
696 * @access public
697 */
698 function getDefaultNamespace() { return $this->mDefaultNamespace; }
699
700 /**
701 * Get title for search index
702 * @return string a stripped-down title string ready for the
703 * search index
704 */
705 function getIndexTitle() {
706 return Title::indexTitle( $this->mNamespace, $this->mTextform );
707 }
708
709 /**
710 * Get the prefixed database key form
711 * @return string the prefixed title, with underscores and
712 * any interwiki and namespace prefixes
713 * @access public
714 */
715 function getPrefixedDBkey() {
716 $s = $this->prefix( $this->mDbkeyform );
717 $s = str_replace( ' ', '_', $s );
718 return $s;
719 }
720
721 /**
722 * Get the prefixed title with spaces.
723 * This is the form usually used for display
724 * @return string the prefixed title, with spaces
725 * @access public
726 */
727 function getPrefixedText() {
728 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
729 $s = $this->prefix( $this->mTextform );
730 $s = str_replace( '_', ' ', $s );
731 $this->mPrefixedText = $s;
732 }
733 return $this->mPrefixedText;
734 }
735
736 /**
737 * Get the prefixed title with spaces, plus any fragment
738 * (part beginning with '#')
739 * @return string the prefixed title, with spaces and
740 * the fragment, including '#'
741 * @access public
742 */
743 function getFullText() {
744 $text = $this->getPrefixedText();
745 if( '' != $this->mFragment ) {
746 $text .= '#' . $this->mFragment;
747 }
748 return $text;
749 }
750
751 /**
752 * Get the base name, i.e. the leftmost parts before the /
753 * @return string Base name
754 */
755 function getBaseText() {
756 global $wgNamespacesWithSubpages;
757 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
758 $parts = explode( '/', $this->getText() );
759 # Don't discard the real title if there's no subpage involved
760 if( count( $parts ) > 1 )
761 unset( $parts[ count( $parts ) - 1 ] );
762 return implode( '/', $parts );
763 } else {
764 return $this->getText();
765 }
766 }
767
768 /**
769 * Get the lowest-level subpage name, i.e. the rightmost part after /
770 * @return string Subpage name
771 */
772 function getSubpageText() {
773 global $wgNamespacesWithSubpages;
774 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
775 $parts = explode( '/', $this->mTextform );
776 return( $parts[ count( $parts ) - 1 ] );
777 } else {
778 return( $this->mTextform );
779 }
780 }
781
782 /**
783 * Get a URL-encoded form of the subpage text
784 * @return string URL-encoded subpage name
785 */
786 function getSubpageUrlForm() {
787 $text = $this->getSubpageText();
788 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
789 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
790 return( $text );
791 }
792
793 /**
794 * Get a URL-encoded title (not an actual URL) including interwiki
795 * @return string the URL-encoded form
796 * @access public
797 */
798 function getPrefixedURL() {
799 $s = $this->prefix( $this->mDbkeyform );
800 $s = str_replace( ' ', '_', $s );
801
802 $s = wfUrlencode ( $s ) ;
803
804 # Cleaning up URL to make it look nice -- is this safe?
805 $s = str_replace( '%28', '(', $s );
806 $s = str_replace( '%29', ')', $s );
807
808 return $s;
809 }
810
811 /**
812 * Get a real URL referring to this title, with interwiki link and
813 * fragment
814 *
815 * @param string $query an optional query string, not used
816 * for interwiki links
817 * @param string $variant language variant of url (for sr, zh..)
818 * @return string the URL
819 * @access public
820 */
821 function getFullURL( $query = '', $variant = false ) {
822 global $wgContLang, $wgServer, $wgRequest;
823
824 if ( '' == $this->mInterwiki ) {
825 $url = $this->getLocalUrl( $query, $variant );
826
827 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
828 // Correct fix would be to move the prepending elsewhere.
829 if ($wgRequest->getVal('action') != 'render') {
830 $url = $wgServer . $url;
831 }
832 } else {
833 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
834
835 $namespace = wfUrlencode( $this->getNsText() );
836 if ( '' != $namespace ) {
837 # Can this actually happen? Interwikis shouldn't be parsed.
838 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
839 $namespace .= ':';
840 }
841 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
842 if( $query != '' ) {
843 if( false === strpos( $url, '?' ) ) {
844 $url .= '?';
845 } else {
846 $url .= '&';
847 }
848 $url .= $query;
849 }
850 }
851
852 # Finally, add the fragment.
853 $url .= $this->getFragmentForURL();
854
855 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
856 return $url;
857 }
858
859 /**
860 * Get a URL with no fragment or server name. If this page is generated
861 * with action=render, $wgServer is prepended.
862 * @param string $query an optional query string; if not specified,
863 * $wgArticlePath will be used.
864 * @param string $variant language variant of url (for sr, zh..)
865 * @return string the URL
866 * @access public
867 */
868 function getLocalURL( $query = '', $variant = false ) {
869 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
870 global $wgVariantArticlePath, $wgContLang, $wgUser;
871
872 // internal links should point to same variant as current page (only anonymous users)
873 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
874 $pref = $wgContLang->getPreferredVariant(false);
875 if($pref != $wgContLang->getCode())
876 $variant = $pref;
877 }
878
879 if ( $this->isExternal() ) {
880 $url = $this->getFullURL();
881 if ( $query ) {
882 // This is currently only used for edit section links in the
883 // context of interwiki transclusion. In theory we should
884 // append the query to the end of any existing query string,
885 // but interwiki transclusion is already broken in that case.
886 $url .= "?$query";
887 }
888 } else {
889 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
890 if ( $query == '' ) {
891 if($variant!=false && $wgContLang->hasVariants()){
892 if($wgVariantArticlePath==false)
893 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
894 else
895 $variantArticlePath = $wgVariantArticlePath;
896
897 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
898 $url = str_replace( '$1', $dbkey, $url );
899
900 }
901 else
902 $url = str_replace( '$1', $dbkey, $wgArticlePath );
903 } else {
904 global $wgActionPaths;
905 $url = false;
906 $matches = array();
907 if( !empty( $wgActionPaths ) &&
908 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
909 {
910 $action = urldecode( $matches[2] );
911 if( isset( $wgActionPaths[$action] ) ) {
912 $query = $matches[1];
913 if( isset( $matches[4] ) ) $query .= $matches[4];
914 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
915 if( $query != '' ) $url .= '?' . $query;
916 }
917 }
918 if ( $url === false ) {
919 if ( $query == '-' ) {
920 $query = '';
921 }
922 $url = "{$wgScript}?title={$dbkey}&{$query}";
923 }
924 }
925
926 // FIXME: this causes breakage in various places when we
927 // actually expected a local URL and end up with dupe prefixes.
928 if ($wgRequest->getVal('action') == 'render') {
929 $url = $wgServer . $url;
930 }
931 }
932 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
933 return $url;
934 }
935
936 /**
937 * Get an HTML-escaped version of the URL form, suitable for
938 * using in a link, without a server name or fragment
939 * @param string $query an optional query string
940 * @return string the URL
941 * @access public
942 */
943 function escapeLocalURL( $query = '' ) {
944 return htmlspecialchars( $this->getLocalURL( $query ) );
945 }
946
947 /**
948 * Get an HTML-escaped version of the URL form, suitable for
949 * using in a link, including the server name and fragment
950 *
951 * @return string the URL
952 * @param string $query an optional query string
953 * @access public
954 */
955 function escapeFullURL( $query = '' ) {
956 return htmlspecialchars( $this->getFullURL( $query ) );
957 }
958
959 /**
960 * Get the URL form for an internal link.
961 * - Used in various Squid-related code, in case we have a different
962 * internal hostname for the server from the exposed one.
963 *
964 * @param string $query an optional query string
965 * @param string $variant language variant of url (for sr, zh..)
966 * @return string the URL
967 * @access public
968 */
969 function getInternalURL( $query = '', $variant = false ) {
970 global $wgInternalServer;
971 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
972 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
973 return $url;
974 }
975
976 /**
977 * Get the edit URL for this Title
978 * @return string the URL, or a null string if this is an
979 * interwiki link
980 * @access public
981 */
982 function getEditURL() {
983 if ( '' != $this->mInterwiki ) { return ''; }
984 $s = $this->getLocalURL( 'action=edit' );
985
986 return $s;
987 }
988
989 /**
990 * Get the HTML-escaped displayable text form.
991 * Used for the title field in <a> tags.
992 * @return string the text, including any prefixes
993 * @access public
994 */
995 function getEscapedText() {
996 return htmlspecialchars( $this->getPrefixedText() );
997 }
998
999 /**
1000 * Is this Title interwiki?
1001 * @return boolean
1002 * @access public
1003 */
1004 function isExternal() { return ( '' != $this->mInterwiki ); }
1005
1006 /**
1007 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1008 *
1009 * @param string Action to check (default: edit)
1010 * @return bool
1011 */
1012 function isSemiProtected( $action = 'edit' ) {
1013 if( $this->exists() ) {
1014 $restrictions = $this->getRestrictions( $action );
1015 if( count( $restrictions ) > 0 ) {
1016 foreach( $restrictions as $restriction ) {
1017 if( strtolower( $restriction ) != 'autoconfirmed' )
1018 return false;
1019 }
1020 } else {
1021 # Not protected
1022 return false;
1023 }
1024 return true;
1025 } else {
1026 # If it doesn't exist, it can't be protected
1027 return false;
1028 }
1029 }
1030
1031 /**
1032 * Does the title correspond to a protected article?
1033 * @param string $what the action the page is protected from,
1034 * by default checks move and edit
1035 * @return boolean
1036 * @access public
1037 */
1038 function isProtected( $action = '' ) {
1039 global $wgRestrictionLevels;
1040 if ( NS_SPECIAL == $this->mNamespace ) { return true; }
1041
1042 if( $action == 'edit' || $action == '' ) {
1043 $r = $this->getRestrictions( 'edit' );
1044 foreach( $wgRestrictionLevels as $level ) {
1045 if( in_array( $level, $r ) && $level != '' ) {
1046 return( true );
1047 }
1048 }
1049 }
1050
1051 if( $action == 'move' || $action == '' ) {
1052 $r = $this->getRestrictions( 'move' );
1053 foreach( $wgRestrictionLevels as $level ) {
1054 if( in_array( $level, $r ) && $level != '' ) {
1055 return( true );
1056 }
1057 }
1058 }
1059
1060 return false;
1061 }
1062
1063 /**
1064 * Is $wgUser is watching this page?
1065 * @return boolean
1066 * @access public
1067 */
1068 function userIsWatching() {
1069 global $wgUser;
1070
1071 if ( is_null( $this->mWatched ) ) {
1072 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1073 $this->mWatched = false;
1074 } else {
1075 $this->mWatched = $wgUser->isWatched( $this );
1076 }
1077 }
1078 return $this->mWatched;
1079 }
1080
1081 /**
1082 * Can $wgUser perform $action this page?
1083 * @param string $action action that permission needs to be checked for
1084 * @return boolean
1085 * @private
1086 */
1087 function userCan($action) {
1088 $fname = 'Title::userCan';
1089 wfProfileIn( $fname );
1090
1091 global $wgUser;
1092
1093 $result = null;
1094 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1095 if ( $result !== null ) {
1096 wfProfileOut( $fname );
1097 return $result;
1098 }
1099
1100 if( NS_SPECIAL == $this->mNamespace ) {
1101 wfProfileOut( $fname );
1102 return false;
1103 }
1104 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1105 // from taking effect -ævar
1106 if( NS_MEDIAWIKI == $this->mNamespace &&
1107 !$wgUser->isAllowed('editinterface') ) {
1108 wfProfileOut( $fname );
1109 return false;
1110 }
1111
1112 if( $this->mDbkeyform == '_' ) {
1113 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1114 wfProfileOut( $fname );
1115 return false;
1116 }
1117
1118 # protect css/js subpages of user pages
1119 # XXX: this might be better using restrictions
1120 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1121 if( $this->isCssJsSubpage()
1122 && !$wgUser->isAllowed('editinterface')
1123 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
1124 wfProfileOut( $fname );
1125 return false;
1126 }
1127
1128 foreach( $this->getRestrictions($action) as $right ) {
1129 // Backwards compatibility, rewrite sysop -> protect
1130 if ( $right == 'sysop' ) {
1131 $right = 'protect';
1132 }
1133 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1134 wfProfileOut( $fname );
1135 return false;
1136 }
1137 }
1138
1139 if( $action == 'move' &&
1140 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1141 wfProfileOut( $fname );
1142 return false;
1143 }
1144
1145 if( $action == 'create' ) {
1146 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1147 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1148 wfProfileOut( $fname );
1149 return false;
1150 }
1151 }
1152
1153 wfProfileOut( $fname );
1154 return true;
1155 }
1156
1157 /**
1158 * Can $wgUser edit this page?
1159 * @return boolean
1160 * @access public
1161 */
1162 function userCanEdit() {
1163 return $this->userCan('edit');
1164 }
1165
1166 /**
1167 * Can $wgUser create this page?
1168 * @return boolean
1169 * @access public
1170 */
1171 function userCanCreate() {
1172 return $this->userCan('create');
1173 }
1174
1175 /**
1176 * Can $wgUser move this page?
1177 * @return boolean
1178 * @access public
1179 */
1180 function userCanMove() {
1181 return $this->userCan('move');
1182 }
1183
1184 /**
1185 * Would anybody with sufficient privileges be able to move this page?
1186 * Some pages just aren't movable.
1187 *
1188 * @return boolean
1189 * @access public
1190 */
1191 function isMovable() {
1192 return Namespace::isMovable( $this->getNamespace() )
1193 && $this->getInterwiki() == '';
1194 }
1195
1196 /**
1197 * Can $wgUser read this page?
1198 * @return boolean
1199 * @access public
1200 */
1201 function userCanRead() {
1202 global $wgUser;
1203
1204 $result = null;
1205 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1206 if ( $result !== null ) {
1207 return $result;
1208 }
1209
1210 if( $wgUser->isAllowed('read') ) {
1211 return true;
1212 } else {
1213 global $wgWhitelistRead;
1214
1215 /**
1216 * Always grant access to the login page.
1217 * Even anons need to be able to log in.
1218 */
1219 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1220 return true;
1221 }
1222
1223 /** some pages are explicitly allowed */
1224 $name = $this->getPrefixedText();
1225 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1226 return true;
1227 }
1228
1229 # Compatibility with old settings
1230 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1231 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1232 return true;
1233 }
1234 }
1235 }
1236 return false;
1237 }
1238
1239 /**
1240 * Is this a talk page of some sort?
1241 * @return bool
1242 * @access public
1243 */
1244 function isTalkPage() {
1245 return Namespace::isTalk( $this->getNamespace() );
1246 }
1247
1248 /**
1249 * Is this a subpage?
1250 * @return bool
1251 * @access public
1252 */
1253 function isSubpage() {
1254 global $wgNamespacesWithSubpages;
1255
1256 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1257 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1258 } else {
1259 return false;
1260 }
1261 }
1262
1263 /**
1264 * Is this a .css or .js subpage of a user page?
1265 * @return bool
1266 * @access public
1267 */
1268 function isCssJsSubpage() {
1269 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform ) );
1270 }
1271 /**
1272 * Is this a *valid* .css or .js subpage of a user page?
1273 * Check that the corresponding skin exists
1274 */
1275 function isValidCssJsSubpage() {
1276 if ( $this->isCssJsSubpage() ) {
1277 $skinNames = Skin::getSkinNames();
1278 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1279 } else {
1280 return false;
1281 }
1282 }
1283 /**
1284 * Trim down a .css or .js subpage title to get the corresponding skin name
1285 */
1286 function getSkinFromCssJsSubpage() {
1287 $subpage = explode( '/', $this->mTextform );
1288 $subpage = $subpage[ count( $subpage ) - 1 ];
1289 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1290 }
1291 /**
1292 * Is this a .css subpage of a user page?
1293 * @return bool
1294 * @access public
1295 */
1296 function isCssSubpage() {
1297 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1298 }
1299 /**
1300 * Is this a .js subpage of a user page?
1301 * @return bool
1302 * @access public
1303 */
1304 function isJsSubpage() {
1305 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1306 }
1307 /**
1308 * Protect css/js subpages of user pages: can $wgUser edit
1309 * this page?
1310 *
1311 * @return boolean
1312 * @todo XXX: this might be better using restrictions
1313 * @access public
1314 */
1315 function userCanEditCssJsSubpage() {
1316 global $wgUser;
1317 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1318 }
1319
1320 /**
1321 * Loads a string into mRestrictions array
1322 * @param string $res restrictions in string format
1323 * @access public
1324 */
1325 function loadRestrictions( $res ) {
1326 $this->mRestrictions['edit'] = array();
1327 $this->mRestrictions['move'] = array();
1328
1329 if( !$res ) {
1330 # No restrictions (page_restrictions blank)
1331 $this->mRestrictionsLoaded = true;
1332 return;
1333 }
1334
1335 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1336 $temp = explode( '=', trim( $restrict ) );
1337 if(count($temp) == 1) {
1338 // old format should be treated as edit/move restriction
1339 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1340 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1341 } else {
1342 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1343 }
1344 }
1345 $this->mRestrictionsLoaded = true;
1346 }
1347
1348 /**
1349 * Accessor/initialisation for mRestrictions
1350 *
1351 * @access public
1352 * @param string $action action that permission needs to be checked for
1353 * @return array the array of groups allowed to edit this article
1354 */
1355 function getRestrictions( $action ) {
1356 if( $this->exists() ) {
1357 if( !$this->mRestrictionsLoaded ) {
1358 $dbr =& wfGetDB( DB_SLAVE );
1359 $res = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ) );
1360 $this->loadRestrictions( $res );
1361 }
1362 return isset( $this->mRestrictions[$action] )
1363 ? $this->mRestrictions[$action]
1364 : array();
1365 } else {
1366 return array();
1367 }
1368 }
1369
1370 /**
1371 * Is there a version of this page in the deletion archive?
1372 * @return int the number of archived revisions
1373 * @access public
1374 */
1375 function isDeleted() {
1376 $fname = 'Title::isDeleted';
1377 if ( $this->getNamespace() < 0 ) {
1378 $n = 0;
1379 } else {
1380 $dbr =& wfGetDB( DB_SLAVE );
1381 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1382 'ar_title' => $this->getDBkey() ), $fname );
1383 if( $this->getNamespace() == NS_IMAGE ) {
1384 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1385 array( 'fa_name' => $this->getDBkey() ), $fname );
1386 }
1387 }
1388 return (int)$n;
1389 }
1390
1391 /**
1392 * Get the article ID for this Title from the link cache,
1393 * adding it if necessary
1394 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1395 * for update
1396 * @return int the ID
1397 */
1398 public function getArticleID( $flags = 0 ) {
1399 $linkCache =& LinkCache::singleton();
1400 if ( $flags & GAID_FOR_UPDATE ) {
1401 $oldUpdate = $linkCache->forUpdate( true );
1402 $this->mArticleID = $linkCache->addLinkObj( $this );
1403 $linkCache->forUpdate( $oldUpdate );
1404 } else {
1405 if ( -1 == $this->mArticleID ) {
1406 $this->mArticleID = $linkCache->addLinkObj( $this );
1407 }
1408 }
1409 return $this->mArticleID;
1410 }
1411
1412 /**
1413 * Return the associated Article object.
1414 *
1415 * @return Article
1416 */
1417 public function getArticle() {
1418 return new Article( $this );
1419 }
1420
1421 function getLatestRevID() {
1422 if ($this->mLatestID !== false)
1423 return $this->mLatestID;
1424
1425 $db =& wfGetDB(DB_SLAVE);
1426 return $this->mLatestID = $db->selectField( 'revision',
1427 "max(rev_id)",
1428 array('rev_page' => $this->getArticleID()),
1429 'Title::getLatestRevID' );
1430 }
1431
1432 /**
1433 * This clears some fields in this object, and clears any associated
1434 * keys in the "bad links" section of the link cache.
1435 *
1436 * - This is called from Article::insertNewArticle() to allow
1437 * loading of the new page_id. It's also called from
1438 * Article::doDeleteArticle()
1439 *
1440 * @param int $newid the new Article ID
1441 * @access public
1442 */
1443 function resetArticleID( $newid ) {
1444 $linkCache =& LinkCache::singleton();
1445 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1446
1447 if ( 0 == $newid ) { $this->mArticleID = -1; }
1448 else { $this->mArticleID = $newid; }
1449 $this->mRestrictionsLoaded = false;
1450 $this->mRestrictions = array();
1451 }
1452
1453 /**
1454 * Updates page_touched for this page; called from LinksUpdate.php
1455 * @return bool true if the update succeded
1456 * @access public
1457 */
1458 function invalidateCache() {
1459 global $wgUseFileCache;
1460
1461 if ( wfReadOnly() ) {
1462 return;
1463 }
1464
1465 $dbw =& wfGetDB( DB_MASTER );
1466 $success = $dbw->update( 'page',
1467 array( /* SET */
1468 'page_touched' => $dbw->timestamp()
1469 ), array( /* WHERE */
1470 'page_namespace' => $this->getNamespace() ,
1471 'page_title' => $this->getDBkey()
1472 ), 'Title::invalidateCache'
1473 );
1474
1475 if ($wgUseFileCache) {
1476 $cache = new HTMLFileCache($this);
1477 @unlink($cache->fileCacheName());
1478 }
1479
1480 return $success;
1481 }
1482
1483 /**
1484 * Prefix some arbitrary text with the namespace or interwiki prefix
1485 * of this object
1486 *
1487 * @param string $name the text
1488 * @return string the prefixed text
1489 * @private
1490 */
1491 /* private */ function prefix( $name ) {
1492 $p = '';
1493 if ( '' != $this->mInterwiki ) {
1494 $p = $this->mInterwiki . ':';
1495 }
1496 if ( 0 != $this->mNamespace ) {
1497 $p .= $this->getNsText() . ':';
1498 }
1499 return $p . $name;
1500 }
1501
1502 /**
1503 * Secure and split - main initialisation function for this object
1504 *
1505 * Assumes that mDbkeyform has been set, and is urldecoded
1506 * and uses underscores, but not otherwise munged. This function
1507 * removes illegal characters, splits off the interwiki and
1508 * namespace prefixes, sets the other forms, and canonicalizes
1509 * everything.
1510 * @return bool true on success
1511 * @private
1512 */
1513 /* private */ function secureAndSplit() {
1514 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1515
1516 # Initialisation
1517 static $rxTc = false;
1518 if( !$rxTc ) {
1519 # % is needed as well
1520 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1521 }
1522
1523 $this->mInterwiki = $this->mFragment = '';
1524 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1525
1526 $dbkey = $this->mDbkeyform;
1527
1528 # Strip Unicode bidi override characters.
1529 # Sometimes they slip into cut-n-pasted page titles, where the
1530 # override chars get included in list displays.
1531 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1532 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1533
1534 # Clean up whitespace
1535 #
1536 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1537 $dbkey = trim( $dbkey, '_' );
1538
1539 if ( '' == $dbkey ) {
1540 return false;
1541 }
1542
1543 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1544 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1545 return false;
1546 }
1547
1548 $this->mDbkeyform = $dbkey;
1549
1550 # Initial colon indicates main namespace rather than specified default
1551 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1552 if ( ':' == $dbkey{0} ) {
1553 $this->mNamespace = NS_MAIN;
1554 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1555 }
1556
1557 # Namespace or interwiki prefix
1558 $firstPass = true;
1559 do {
1560 $m = array();
1561 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1562 $p = $m[1];
1563 $lowerNs = $wgContLang->lc( $p );
1564 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1565 # Canonical namespace
1566 $dbkey = $m[2];
1567 $this->mNamespace = $ns;
1568 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1569 # Ordinary namespace
1570 $dbkey = $m[2];
1571 $this->mNamespace = $ns;
1572 } elseif( $this->getInterwikiLink( $p ) ) {
1573 if( !$firstPass ) {
1574 # Can't make a local interwiki link to an interwiki link.
1575 # That's just crazy!
1576 return false;
1577 }
1578
1579 # Interwiki link
1580 $dbkey = $m[2];
1581 $this->mInterwiki = $wgContLang->lc( $p );
1582
1583 # Redundant interwiki prefix to the local wiki
1584 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1585 if( $dbkey == '' ) {
1586 # Can't have an empty self-link
1587 return false;
1588 }
1589 $this->mInterwiki = '';
1590 $firstPass = false;
1591 # Do another namespace split...
1592 continue;
1593 }
1594
1595 # If there's an initial colon after the interwiki, that also
1596 # resets the default namespace
1597 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1598 $this->mNamespace = NS_MAIN;
1599 $dbkey = substr( $dbkey, 1 );
1600 }
1601 }
1602 # If there's no recognized interwiki or namespace,
1603 # then let the colon expression be part of the title.
1604 }
1605 break;
1606 } while( true );
1607
1608 # We already know that some pages won't be in the database!
1609 #
1610 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1611 $this->mArticleID = 0;
1612 }
1613 $fragment = strstr( $dbkey, '#' );
1614 if ( false !== $fragment ) {
1615 $this->setFragment( $fragment );
1616 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1617 # remove whitespace again: prevents "Foo_bar_#"
1618 # becoming "Foo_bar_"
1619 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1620 }
1621
1622 # Reject illegal characters.
1623 #
1624 if( preg_match( $rxTc, $dbkey ) ) {
1625 return false;
1626 }
1627
1628 /**
1629 * Pages with "/./" or "/../" appearing in the URLs will
1630 * often be unreachable due to the way web browsers deal
1631 * with 'relative' URLs. Forbid them explicitly.
1632 */
1633 if ( strpos( $dbkey, '.' ) !== false &&
1634 ( $dbkey === '.' || $dbkey === '..' ||
1635 strpos( $dbkey, './' ) === 0 ||
1636 strpos( $dbkey, '../' ) === 0 ||
1637 strpos( $dbkey, '/./' ) !== false ||
1638 strpos( $dbkey, '/../' ) !== false ) )
1639 {
1640 return false;
1641 }
1642
1643 /**
1644 * Limit the size of titles to 255 bytes.
1645 * This is typically the size of the underlying database field.
1646 * We make an exception for special pages, which don't need to be stored
1647 * in the database, and may edge over 255 bytes due to subpage syntax
1648 * for long titles, e.g. [[Special:Block/Long name]]
1649 */
1650 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1651 strlen( $dbkey ) > 512 )
1652 {
1653 return false;
1654 }
1655
1656 /**
1657 * Normally, all wiki links are forced to have
1658 * an initial capital letter so [[foo]] and [[Foo]]
1659 * point to the same place.
1660 *
1661 * Don't force it for interwikis, since the other
1662 * site might be case-sensitive.
1663 */
1664 if( $wgCapitalLinks && $this->mInterwiki == '') {
1665 $dbkey = $wgContLang->ucfirst( $dbkey );
1666 }
1667
1668 /**
1669 * Can't make a link to a namespace alone...
1670 * "empty" local links can only be self-links
1671 * with a fragment identifier.
1672 */
1673 if( $dbkey == '' &&
1674 $this->mInterwiki == '' &&
1675 $this->mNamespace != NS_MAIN ) {
1676 return false;
1677 }
1678
1679 // Any remaining initial :s are illegal.
1680 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1681 return false;
1682 }
1683
1684 # Fill fields
1685 $this->mDbkeyform = $dbkey;
1686 $this->mUrlform = wfUrlencode( $dbkey );
1687
1688 $this->mTextform = str_replace( '_', ' ', $dbkey );
1689
1690 return true;
1691 }
1692
1693 /**
1694 * Set the fragment for this title
1695 * This is kind of bad, since except for this rarely-used function, Title objects
1696 * are immutable. The reason this is here is because it's better than setting the
1697 * members directly, which is what Linker::formatComment was doing previously.
1698 *
1699 * @param string $fragment text
1700 * @access kind of public
1701 */
1702 function setFragment( $fragment ) {
1703 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1704 }
1705
1706 /**
1707 * Get a Title object associated with the talk page of this article
1708 * @return Title the object for the talk page
1709 * @access public
1710 */
1711 function getTalkPage() {
1712 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1713 }
1714
1715 /**
1716 * Get a title object associated with the subject page of this
1717 * talk page
1718 *
1719 * @return Title the object for the subject page
1720 * @access public
1721 */
1722 function getSubjectPage() {
1723 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1724 }
1725
1726 /**
1727 * Get an array of Title objects linking to this Title
1728 * Also stores the IDs in the link cache.
1729 *
1730 * WARNING: do not use this function on arbitrary user-supplied titles!
1731 * On heavily-used templates it will max out the memory.
1732 *
1733 * @param string $options may be FOR UPDATE
1734 * @return array the Title objects linking here
1735 * @access public
1736 */
1737 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1738 $linkCache =& LinkCache::singleton();
1739
1740 if ( $options ) {
1741 $db =& wfGetDB( DB_MASTER );
1742 } else {
1743 $db =& wfGetDB( DB_SLAVE );
1744 }
1745
1746 $res = $db->select( array( 'page', $table ),
1747 array( 'page_namespace', 'page_title', 'page_id' ),
1748 array(
1749 "{$prefix}_from=page_id",
1750 "{$prefix}_namespace" => $this->getNamespace(),
1751 "{$prefix}_title" => $this->getDbKey() ),
1752 'Title::getLinksTo',
1753 $options );
1754
1755 $retVal = array();
1756 if ( $db->numRows( $res ) ) {
1757 while ( $row = $db->fetchObject( $res ) ) {
1758 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1759 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1760 $retVal[] = $titleObj;
1761 }
1762 }
1763 }
1764 $db->freeResult( $res );
1765 return $retVal;
1766 }
1767
1768 /**
1769 * Get an array of Title objects using this Title as a template
1770 * Also stores the IDs in the link cache.
1771 *
1772 * WARNING: do not use this function on arbitrary user-supplied titles!
1773 * On heavily-used templates it will max out the memory.
1774 *
1775 * @param string $options may be FOR UPDATE
1776 * @return array the Title objects linking here
1777 * @access public
1778 */
1779 function getTemplateLinksTo( $options = '' ) {
1780 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1781 }
1782
1783 /**
1784 * Get an array of Title objects referring to non-existent articles linked from this page
1785 *
1786 * @param string $options may be FOR UPDATE
1787 * @return array the Title objects
1788 * @access public
1789 */
1790 function getBrokenLinksFrom( $options = '' ) {
1791 if ( $options ) {
1792 $db =& wfGetDB( DB_MASTER );
1793 } else {
1794 $db =& wfGetDB( DB_SLAVE );
1795 }
1796
1797 $res = $db->safeQuery(
1798 "SELECT pl_namespace, pl_title
1799 FROM !
1800 LEFT JOIN !
1801 ON pl_namespace=page_namespace
1802 AND pl_title=page_title
1803 WHERE pl_from=?
1804 AND page_namespace IS NULL
1805 !",
1806 $db->tableName( 'pagelinks' ),
1807 $db->tableName( 'page' ),
1808 $this->getArticleId(),
1809 $options );
1810
1811 $retVal = array();
1812 if ( $db->numRows( $res ) ) {
1813 while ( $row = $db->fetchObject( $res ) ) {
1814 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1815 }
1816 }
1817 $db->freeResult( $res );
1818 return $retVal;
1819 }
1820
1821
1822 /**
1823 * Get a list of URLs to purge from the Squid cache when this
1824 * page changes
1825 *
1826 * @return array the URLs
1827 * @access public
1828 */
1829 function getSquidURLs() {
1830 global $wgContLang;
1831
1832 $urls = array(
1833 $this->getInternalURL(),
1834 $this->getInternalURL( 'action=history' )
1835 );
1836
1837 // purge variant urls as well
1838 if($wgContLang->hasVariants()){
1839 $variants = $wgContLang->getVariants();
1840 foreach($variants as $vCode){
1841 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1842 $urls[] = $this->getInternalURL('',$vCode);
1843 }
1844 }
1845
1846 return $urls;
1847 }
1848
1849 function purgeSquid() {
1850 global $wgUseSquid;
1851 if ( $wgUseSquid ) {
1852 $urls = $this->getSquidURLs();
1853 $u = new SquidUpdate( $urls );
1854 $u->doUpdate();
1855 }
1856 }
1857
1858 /**
1859 * Move this page without authentication
1860 * @param Title &$nt the new page Title
1861 * @access public
1862 */
1863 function moveNoAuth( &$nt ) {
1864 return $this->moveTo( $nt, false );
1865 }
1866
1867 /**
1868 * Check whether a given move operation would be valid.
1869 * Returns true if ok, or a message key string for an error message
1870 * if invalid. (Scarrrrry ugly interface this.)
1871 * @param Title &$nt the new title
1872 * @param bool $auth indicates whether $wgUser's permissions
1873 * should be checked
1874 * @return mixed true on success, message name on failure
1875 * @access public
1876 */
1877 function isValidMoveOperation( &$nt, $auth = true ) {
1878 if( !$this or !$nt ) {
1879 return 'badtitletext';
1880 }
1881 if( $this->equals( $nt ) ) {
1882 return 'selfmove';
1883 }
1884 if( !$this->isMovable() || !$nt->isMovable() ) {
1885 return 'immobile_namespace';
1886 }
1887
1888 $oldid = $this->getArticleID();
1889 $newid = $nt->getArticleID();
1890
1891 if ( strlen( $nt->getDBkey() ) < 1 ) {
1892 return 'articleexists';
1893 }
1894 if ( ( '' == $this->getDBkey() ) ||
1895 ( !$oldid ) ||
1896 ( '' == $nt->getDBkey() ) ) {
1897 return 'badarticleerror';
1898 }
1899
1900 if ( $auth && (
1901 !$this->userCanEdit() || !$nt->userCanEdit() ||
1902 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1903 return 'protectedpage';
1904 }
1905
1906 # The move is allowed only if (1) the target doesn't exist, or
1907 # (2) the target is a redirect to the source, and has no history
1908 # (so we can undo bad moves right after they're done).
1909
1910 if ( 0 != $newid ) { # Target exists; check for validity
1911 if ( ! $this->isValidMoveTarget( $nt ) ) {
1912 return 'articleexists';
1913 }
1914 }
1915 return true;
1916 }
1917
1918 /**
1919 * Move a title to a new location
1920 * @param Title &$nt the new title
1921 * @param bool $auth indicates whether $wgUser's permissions
1922 * should be checked
1923 * @return mixed true on success, message name on failure
1924 * @access public
1925 */
1926 function moveTo( &$nt, $auth = true, $reason = '' ) {
1927 $err = $this->isValidMoveOperation( $nt, $auth );
1928 if( is_string( $err ) ) {
1929 return $err;
1930 }
1931
1932 $pageid = $this->getArticleID();
1933 if( $nt->exists() ) {
1934 $this->moveOverExistingRedirect( $nt, $reason );
1935 $pageCountChange = 0;
1936 } else { # Target didn't exist, do normal move.
1937 $this->moveToNewTitle( $nt, $reason );
1938 $pageCountChange = 1;
1939 }
1940 $redirid = $this->getArticleID();
1941
1942 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1943 $dbw =& wfGetDB( DB_MASTER );
1944 $categorylinks = $dbw->tableName( 'categorylinks' );
1945 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1946 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1947 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1948 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1949
1950 # Update watchlists
1951
1952 $oldnamespace = $this->getNamespace() & ~1;
1953 $newnamespace = $nt->getNamespace() & ~1;
1954 $oldtitle = $this->getDBkey();
1955 $newtitle = $nt->getDBkey();
1956
1957 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1958 WatchedItem::duplicateEntries( $this, $nt );
1959 }
1960
1961 # Update search engine
1962 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1963 $u->doUpdate();
1964 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1965 $u->doUpdate();
1966
1967 # Update site_stats
1968 if( $this->isContentPage() && !$nt->isContentPage() ) {
1969 # No longer a content page
1970 # Not viewed, edited, removing
1971 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
1972 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
1973 # Now a content page
1974 # Not viewed, edited, adding
1975 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1976 } elseif( $pageCountChange ) {
1977 # Redirect added
1978 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1979 } else {
1980 # Nothing special
1981 $u = false;
1982 }
1983 if( $u )
1984 $u->doUpdate();
1985
1986 global $wgUser;
1987 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1988 return true;
1989 }
1990
1991 /**
1992 * Move page to a title which is at present a redirect to the
1993 * source page
1994 *
1995 * @param Title &$nt the page to move to, which should currently
1996 * be a redirect
1997 * @private
1998 */
1999 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2000 global $wgUseSquid;
2001 $fname = 'Title::moveOverExistingRedirect';
2002 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2003
2004 if ( $reason ) {
2005 $comment .= ": $reason";
2006 }
2007
2008 $now = wfTimestampNow();
2009 $newid = $nt->getArticleID();
2010 $oldid = $this->getArticleID();
2011 $dbw =& wfGetDB( DB_MASTER );
2012 $linkCache =& LinkCache::singleton();
2013
2014 # Delete the old redirect. We don't save it to history since
2015 # by definition if we've got here it's rather uninteresting.
2016 # We have to remove it so that the next step doesn't trigger
2017 # a conflict on the unique namespace+title index...
2018 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2019
2020 # Save a null revision in the page's history notifying of the move
2021 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2022 $nullRevId = $nullRevision->insertOn( $dbw );
2023
2024 # Change the name of the target page:
2025 $dbw->update( 'page',
2026 /* SET */ array(
2027 'page_touched' => $dbw->timestamp($now),
2028 'page_namespace' => $nt->getNamespace(),
2029 'page_title' => $nt->getDBkey(),
2030 'page_latest' => $nullRevId,
2031 ),
2032 /* WHERE */ array( 'page_id' => $oldid ),
2033 $fname
2034 );
2035 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2036
2037 # Recreate the redirect, this time in the other direction.
2038 $mwRedir = MagicWord::get( 'redirect' );
2039 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2040 $redirectArticle = new Article( $this );
2041 $newid = $redirectArticle->insertOn( $dbw );
2042 $redirectRevision = new Revision( array(
2043 'page' => $newid,
2044 'comment' => $comment,
2045 'text' => $redirectText ) );
2046 $redirectRevision->insertOn( $dbw );
2047 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2048 $linkCache->clearLink( $this->getPrefixedDBkey() );
2049
2050 # Log the move
2051 $log = new LogPage( 'move' );
2052 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2053
2054 # Now, we record the link from the redirect to the new title.
2055 # It should have no other outgoing links...
2056 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2057 $dbw->insert( 'pagelinks',
2058 array(
2059 'pl_from' => $newid,
2060 'pl_namespace' => $nt->getNamespace(),
2061 'pl_title' => $nt->getDbKey() ),
2062 $fname );
2063
2064 # Purge squid
2065 if ( $wgUseSquid ) {
2066 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2067 $u = new SquidUpdate( $urls );
2068 $u->doUpdate();
2069 }
2070 }
2071
2072 /**
2073 * Move page to non-existing title.
2074 * @param Title &$nt the new Title
2075 * @private
2076 */
2077 function moveToNewTitle( &$nt, $reason = '' ) {
2078 global $wgUseSquid;
2079 $fname = 'MovePageForm::moveToNewTitle';
2080 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2081 if ( $reason ) {
2082 $comment .= ": $reason";
2083 }
2084
2085 $newid = $nt->getArticleID();
2086 $oldid = $this->getArticleID();
2087 $dbw =& wfGetDB( DB_MASTER );
2088 $now = $dbw->timestamp();
2089 $linkCache =& LinkCache::singleton();
2090
2091 # Save a null revision in the page's history notifying of the move
2092 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2093 $nullRevId = $nullRevision->insertOn( $dbw );
2094
2095 # Rename cur entry
2096 $dbw->update( 'page',
2097 /* SET */ array(
2098 'page_touched' => $now,
2099 'page_namespace' => $nt->getNamespace(),
2100 'page_title' => $nt->getDBkey(),
2101 'page_latest' => $nullRevId,
2102 ),
2103 /* WHERE */ array( 'page_id' => $oldid ),
2104 $fname
2105 );
2106
2107 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2108
2109 # Insert redirect
2110 $mwRedir = MagicWord::get( 'redirect' );
2111 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2112 $redirectArticle = new Article( $this );
2113 $newid = $redirectArticle->insertOn( $dbw );
2114 $redirectRevision = new Revision( array(
2115 'page' => $newid,
2116 'comment' => $comment,
2117 'text' => $redirectText ) );
2118 $redirectRevision->insertOn( $dbw );
2119 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2120 $linkCache->clearLink( $this->getPrefixedDBkey() );
2121
2122 # Log the move
2123 $log = new LogPage( 'move' );
2124 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2125
2126 # Purge caches as per article creation
2127 Article::onArticleCreate( $nt );
2128
2129 # Record the just-created redirect's linking to the page
2130 $dbw->insert( 'pagelinks',
2131 array(
2132 'pl_from' => $newid,
2133 'pl_namespace' => $nt->getNamespace(),
2134 'pl_title' => $nt->getDBkey() ),
2135 $fname );
2136
2137 # Purge old title from squid
2138 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2139 $this->purgeSquid();
2140 }
2141
2142 /**
2143 * Checks if $this can be moved to a given Title
2144 * - Selects for update, so don't call it unless you mean business
2145 *
2146 * @param Title &$nt the new title to check
2147 * @access public
2148 */
2149 function isValidMoveTarget( $nt ) {
2150
2151 $fname = 'Title::isValidMoveTarget';
2152 $dbw =& wfGetDB( DB_MASTER );
2153
2154 # Is it a redirect?
2155 $id = $nt->getArticleID();
2156 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2157 array( 'page_is_redirect','old_text','old_flags' ),
2158 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2159 $fname, 'FOR UPDATE' );
2160
2161 if ( !$obj || 0 == $obj->page_is_redirect ) {
2162 # Not a redirect
2163 wfDebug( __METHOD__ . ": not a redirect\n" );
2164 return false;
2165 }
2166 $text = Revision::getRevisionText( $obj );
2167
2168 # Does the redirect point to the source?
2169 # Or is it a broken self-redirect, usually caused by namespace collisions?
2170 $m = array();
2171 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2172 $redirTitle = Title::newFromText( $m[1] );
2173 if( !is_object( $redirTitle ) ||
2174 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2175 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2176 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2177 return false;
2178 }
2179 } else {
2180 # Fail safe
2181 wfDebug( __METHOD__ . ": failsafe\n" );
2182 return false;
2183 }
2184
2185 # Does the article have a history?
2186 $row = $dbw->selectRow( array( 'page', 'revision'),
2187 array( 'rev_id' ),
2188 array( 'page_namespace' => $nt->getNamespace(),
2189 'page_title' => $nt->getDBkey(),
2190 'page_id=rev_page AND page_latest != rev_id'
2191 ), $fname, 'FOR UPDATE'
2192 );
2193
2194 # Return true if there was no history
2195 return $row === false;
2196 }
2197
2198 /**
2199 * Create a redirect; fails if the title already exists; does
2200 * not notify RC
2201 *
2202 * @param Title $dest the destination of the redirect
2203 * @param string $comment the comment string describing the move
2204 * @return bool true on success
2205 * @access public
2206 */
2207 function createRedirect( $dest, $comment ) {
2208 if ( $this->getArticleID() ) {
2209 return false;
2210 }
2211
2212 $fname = 'Title::createRedirect';
2213 $dbw =& wfGetDB( DB_MASTER );
2214
2215 $article = new Article( $this );
2216 $newid = $article->insertOn( $dbw );
2217 $revision = new Revision( array(
2218 'page' => $newid,
2219 'comment' => $comment,
2220 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2221 ) );
2222 $revision->insertOn( $dbw );
2223 $article->updateRevisionOn( $dbw, $revision, 0 );
2224
2225 # Link table
2226 $dbw->insert( 'pagelinks',
2227 array(
2228 'pl_from' => $newid,
2229 'pl_namespace' => $dest->getNamespace(),
2230 'pl_title' => $dest->getDbKey()
2231 ), $fname
2232 );
2233
2234 Article::onArticleCreate( $this );
2235 return true;
2236 }
2237
2238 /**
2239 * Get categories to which this Title belongs and return an array of
2240 * categories' names.
2241 *
2242 * @return array an array of parents in the form:
2243 * $parent => $currentarticle
2244 * @access public
2245 */
2246 function getParentCategories() {
2247 global $wgContLang;
2248
2249 $titlekey = $this->getArticleId();
2250 $dbr =& wfGetDB( DB_SLAVE );
2251 $categorylinks = $dbr->tableName( 'categorylinks' );
2252
2253 # NEW SQL
2254 $sql = "SELECT * FROM $categorylinks"
2255 ." WHERE cl_from='$titlekey'"
2256 ." AND cl_from <> '0'"
2257 ." ORDER BY cl_sortkey";
2258
2259 $res = $dbr->query ( $sql ) ;
2260
2261 if($dbr->numRows($res) > 0) {
2262 while ( $x = $dbr->fetchObject ( $res ) )
2263 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2264 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2265 $dbr->freeResult ( $res ) ;
2266 } else {
2267 $data = '';
2268 }
2269 return $data;
2270 }
2271
2272 /**
2273 * Get a tree of parent categories
2274 * @param array $children an array with the children in the keys, to check for circular refs
2275 * @return array
2276 * @access public
2277 */
2278 function getParentCategoryTree( $children = array() ) {
2279 $parents = $this->getParentCategories();
2280
2281 if($parents != '') {
2282 foreach($parents as $parent => $current) {
2283 if ( array_key_exists( $parent, $children ) ) {
2284 # Circular reference
2285 $stack[$parent] = array();
2286 } else {
2287 $nt = Title::newFromText($parent);
2288 if ( $nt ) {
2289 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2290 }
2291 }
2292 }
2293 return $stack;
2294 } else {
2295 return array();
2296 }
2297 }
2298
2299
2300 /**
2301 * Get an associative array for selecting this title from
2302 * the "page" table
2303 *
2304 * @return array
2305 * @access public
2306 */
2307 function pageCond() {
2308 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2309 }
2310
2311 /**
2312 * Get the revision ID of the previous revision
2313 *
2314 * @param integer $revision Revision ID. Get the revision that was before this one.
2315 * @return integer $oldrevision|false
2316 */
2317 function getPreviousRevisionID( $revision ) {
2318 $dbr =& wfGetDB( DB_SLAVE );
2319 return $dbr->selectField( 'revision', 'rev_id',
2320 'rev_page=' . intval( $this->getArticleId() ) .
2321 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2322 }
2323
2324 /**
2325 * Get the revision ID of the next revision
2326 *
2327 * @param integer $revision Revision ID. Get the revision that was after this one.
2328 * @return integer $oldrevision|false
2329 */
2330 function getNextRevisionID( $revision ) {
2331 $dbr =& wfGetDB( DB_SLAVE );
2332 return $dbr->selectField( 'revision', 'rev_id',
2333 'rev_page=' . intval( $this->getArticleId() ) .
2334 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2335 }
2336
2337 /**
2338 * Get the number of revisions between the given revision IDs.
2339 *
2340 * @param integer $old Revision ID.
2341 * @param integer $new Revision ID.
2342 * @return integer Number of revisions between these IDs.
2343 */
2344 function countRevisionsBetween( $old, $new ) {
2345 $dbr =& wfGetDB( DB_SLAVE );
2346 return $dbr->selectField( 'revision', 'count(*)',
2347 'rev_page = ' . intval( $this->getArticleId() ) .
2348 ' AND rev_id > ' . intval( $old ) .
2349 ' AND rev_id < ' . intval( $new ) );
2350 }
2351
2352 /**
2353 * Compare with another title.
2354 *
2355 * @param Title $title
2356 * @return bool
2357 */
2358 function equals( $title ) {
2359 // Note: === is necessary for proper matching of number-like titles.
2360 return $this->getInterwiki() === $title->getInterwiki()
2361 && $this->getNamespace() == $title->getNamespace()
2362 && $this->getDbkey() === $title->getDbkey();
2363 }
2364
2365 /**
2366 * Check if page exists
2367 * @return bool
2368 */
2369 function exists() {
2370 return $this->getArticleId() != 0;
2371 }
2372
2373 /**
2374 * Should a link should be displayed as a known link, just based on its title?
2375 *
2376 * Currently, a self-link with a fragment and special pages are in
2377 * this category. Special pages never exist in the database.
2378 */
2379 function isAlwaysKnown() {
2380 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2381 || NS_SPECIAL == $this->mNamespace;
2382 }
2383
2384 /**
2385 * Update page_touched timestamps and send squid purge messages for
2386 * pages linking to this title. May be sent to the job queue depending
2387 * on the number of links. Typically called on create and delete.
2388 */
2389 function touchLinks() {
2390 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2391 $u->doUpdate();
2392
2393 if ( $this->getNamespace() == NS_CATEGORY ) {
2394 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2395 $u->doUpdate();
2396 }
2397 }
2398
2399 /**
2400 * Get the last touched timestamp
2401 */
2402 function getTouched() {
2403 $dbr =& wfGetDB( DB_SLAVE );
2404 $touched = $dbr->selectField( 'page', 'page_touched',
2405 array(
2406 'page_namespace' => $this->getNamespace(),
2407 'page_title' => $this->getDBkey()
2408 ), __METHOD__
2409 );
2410 return $touched;
2411 }
2412
2413 /**
2414 * Get a cached value from a global cache that is invalidated when this page changes
2415 * @param string $key the key
2416 * @param callback $callback A callback function which generates the value on cache miss
2417 *
2418 * @deprecated use DependencyWrapper
2419 */
2420 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2421 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2422 $params, new TitleDependency( $this ) );
2423 }
2424
2425 function trackbackURL() {
2426 global $wgTitle, $wgScriptPath, $wgServer;
2427
2428 return "$wgServer$wgScriptPath/trackback.php?article="
2429 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2430 }
2431
2432 function trackbackRDF() {
2433 $url = htmlspecialchars($this->getFullURL());
2434 $title = htmlspecialchars($this->getText());
2435 $tburl = $this->trackbackURL();
2436
2437 return "
2438 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2439 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2440 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2441 <rdf:Description
2442 rdf:about=\"$url\"
2443 dc:identifier=\"$url\"
2444 dc:title=\"$title\"
2445 trackback:ping=\"$tburl\" />
2446 </rdf:RDF>";
2447 }
2448
2449 /**
2450 * Generate strings used for xml 'id' names in monobook tabs
2451 * @return string
2452 */
2453 function getNamespaceKey() {
2454 global $wgContLang;
2455 switch ($this->getNamespace()) {
2456 case NS_MAIN:
2457 case NS_TALK:
2458 return 'nstab-main';
2459 case NS_USER:
2460 case NS_USER_TALK:
2461 return 'nstab-user';
2462 case NS_MEDIA:
2463 return 'nstab-media';
2464 case NS_SPECIAL:
2465 return 'nstab-special';
2466 case NS_PROJECT:
2467 case NS_PROJECT_TALK:
2468 return 'nstab-project';
2469 case NS_IMAGE:
2470 case NS_IMAGE_TALK:
2471 return 'nstab-image';
2472 case NS_MEDIAWIKI:
2473 case NS_MEDIAWIKI_TALK:
2474 return 'nstab-mediawiki';
2475 case NS_TEMPLATE:
2476 case NS_TEMPLATE_TALK:
2477 return 'nstab-template';
2478 case NS_HELP:
2479 case NS_HELP_TALK:
2480 return 'nstab-help';
2481 case NS_CATEGORY:
2482 case NS_CATEGORY_TALK:
2483 return 'nstab-category';
2484 default:
2485 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2486 }
2487 }
2488
2489 /**
2490 * Returns true if this title resolves to the named special page
2491 * @param string $name The special page name
2492 * @access public
2493 */
2494 function isSpecial( $name ) {
2495 if ( $this->getNamespace() == NS_SPECIAL ) {
2496 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2497 if ( $name == $thisName ) {
2498 return true;
2499 }
2500 }
2501 return false;
2502 }
2503
2504 /**
2505 * If the Title refers to a special page alias which is not the local default,
2506 * returns a new Title which points to the local default. Otherwise, returns $this.
2507 */
2508 function fixSpecialName() {
2509 if ( $this->getNamespace() == NS_SPECIAL ) {
2510 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2511 if ( $canonicalName ) {
2512 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2513 if ( $localName != $this->mDbkeyform ) {
2514 return Title::makeTitle( NS_SPECIAL, $localName );
2515 }
2516 }
2517 }
2518 return $this;
2519 }
2520
2521 /**
2522 * Is this Title in a namespace which contains content?
2523 * In other words, is this a content page, for the purposes of calculating
2524 * statistics, etc?
2525 *
2526 * @return bool
2527 */
2528 public function isContentPage() {
2529 return Namespace::isContent( $this->getNamespace() );
2530 }
2531
2532 }
2533
2534 ?>