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