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