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