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