disallow embedded line breaks in ISBNs; allowing them breaks things in a most interes...
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 define ( 'GAID_FOR_UPDATE', 1 );
12
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
17 # reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
19
20 /**
21 * Title class
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
24 *
25 * @package MediaWiki
26 */
27 class Title {
28 /**
29 * Static cache variables
30 */
31 static private $titleCache=array();
32 static private $interwikiCache=array();
33
34
35 /**
36 * All member variables should be considered private
37 * Please use the accessor functions
38 */
39
40 /**#@+
41 * @private
42 */
43
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
59 /**#@-*/
60
61
62 /**
63 * Constructor
64 * @private
65 */
66 /* private */ function Title() {
67 $this->mInterwiki = $this->mUrlform =
68 $this->mTextform = $this->mDbkeyform = '';
69 $this->mArticleID = -1;
70 $this->mNamespace = NS_MAIN;
71 $this->mRestrictionsLoaded = false;
72 $this->mRestrictions = array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
74 # See bug #696
75 $this->mDefaultNamespace = NS_MAIN;
76 $this->mWatched = NULL;
77 $this->mLatestID = false;
78 }
79
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return Title the new object, or NULL on an error
86 * @static
87 * @access public
88 */
89 /* static */ function newFromDBkey( $key ) {
90 $t = new Title();
91 $t->mDbkeyform = $key;
92 if( $t->secureAndSplit() )
93 return $t;
94 else
95 return NULL;
96 }
97
98 /**
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
101 *
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
104 * are accepted
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
108 * @static
109 * @access public
110 */
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
112 if( is_object( $text ) ) {
113 throw new MWException( 'Title::newFromText given an object' );
114 }
115
116 /**
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
120 * caching them.
121 *
122 * In theory these are value objects and won't get changed...
123 */
124 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
125 return Title::$titleCache[$text];
126 }
127
128 /**
129 * Convert things like &eacute; &#257; or &#x3017; into real text...
130 */
131 $filteredText = Sanitizer::decodeCharReferences( $text );
132
133 $t = new Title();
134 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace = $defaultNamespace;
136
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN ) {
140 if( $cachedcount >= MW_TITLECACHE_MAX ) {
141 # Avoid memory leaks on mass operations...
142 Title::$titleCache = array();
143 $cachedcount=0;
144 }
145 $cachedcount++;
146 Title::$titleCache[$text] =& $t;
147 }
148 return $t;
149 } else {
150 $ret = NULL;
151 return $ret;
152 }
153 }
154
155 /**
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
160 * @static
161 * @access public
162 */
163 public static function newFromURL( $url ) {
164 global $wgLegalTitleChars;
165 $t = new Title();
166
167 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
168 # but some URLs used it as a space replacement and they still come
169 # from some external search tools.
170 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
171 $url = str_replace( '+', ' ', $url );
172 }
173
174 $t->mDbkeyform = str_replace( ' ', '_', $url );
175 if( $t->secureAndSplit() ) {
176 return $t;
177 } else {
178 return NULL;
179 }
180 }
181
182 /**
183 * Create a new Title from an article ID
184 *
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
187 *
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
190 * @access public
191 * @static
192 */
193 function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE );
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
200 } else {
201 $title = NULL;
202 }
203 return $title;
204 }
205
206 /**
207 * Make an array of titles from an array of IDs
208 */
209 function newFromIDs( $ids ) {
210 $dbr =& wfGetDB( DB_SLAVE );
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
213
214 $titles = array();
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
217 }
218 return $titles;
219 }
220
221 /**
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
227 *
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
231 * @static
232 * @access public
233 */
234 public static function &makeTitle( $ns, $title ) {
235 $t = new Title();
236 $t->mInterwiki = '';
237 $t->mFragment = '';
238 $t->mNamespace = intval( $ns );
239 $t->mDbkeyform = str_replace( ' ', '_', $title );
240 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
241 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
242 $t->mTextform = str_replace( '_', ' ', $title );
243 return $t;
244 }
245
246 /**
247 * Create a new Title from a namespace index and a DB key.
248 * The parameters will be checked for validity, which is a bit slower
249 * than makeTitle() but safer for user-provided data.
250 *
251 * @param int $ns the namespace of the article
252 * @param string $title the database key form
253 * @return Title the new object, or NULL on an error
254 * @static
255 * @access public
256 */
257 public static function makeTitleSafe( $ns, $title ) {
258 $t = new Title();
259 $t->mDbkeyform = Title::makeName( $ns, $title );
260 if( $t->secureAndSplit() ) {
261 return $t;
262 } else {
263 return NULL;
264 }
265 }
266
267 /**
268 * Create a new Title for the Main Page
269 *
270 * @static
271 * @return Title the new object
272 * @access public
273 */
274 public static function newMainPage() {
275 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
276 }
277
278 /**
279 * Create a new Title for a redirect
280 * @param string $text the redirect title text
281 * @return Title the new object, or NULL if the text is not a
282 * valid redirect
283 * @static
284 * @access public
285 */
286 public static function newFromRedirect( $text ) {
287 $mwRedir = MagicWord::get( 'redirect' );
288 $rt = NULL;
289 if ( $mwRedir->matchStart( $text ) ) {
290 $m = array();
291 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
292 # categories are escaped using : for example one can enter:
293 # #REDIRECT [[:Category:Music]]. Need to remove it.
294 if ( substr($m[1],0,1) == ':') {
295 # We don't want to keep the ':'
296 $m[1] = substr( $m[1], 1 );
297 }
298
299 $rt = Title::newFromText( $m[1] );
300 # Disallow redirects to Special:Userlogout
301 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
302 $rt = NULL;
303 }
304 }
305 }
306 return $rt;
307 }
308
309 #----------------------------------------------------------------------------
310 # Static functions
311 #----------------------------------------------------------------------------
312
313 /**
314 * Get the prefixed DB key associated with an ID
315 * @param int $id the page_id of the article
316 * @return Title an object representing the article, or NULL
317 * if no such article was found
318 * @static
319 * @access public
320 */
321 function nameOf( $id ) {
322 $fname = 'Title::nameOf';
323 $dbr =& wfGetDB( DB_SLAVE );
324
325 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
326 if ( $s === false ) { return NULL; }
327
328 $n = Title::makeName( $s->page_namespace, $s->page_title );
329 return $n;
330 }
331
332 /**
333 * Get a regex character class describing the legal characters in a link
334 * @return string the list of characters, not delimited
335 * @static
336 * @access public
337 */
338 public static function legalChars() {
339 global $wgLegalTitleChars;
340 return $wgLegalTitleChars;
341 }
342
343 /**
344 * Get a string representation of a title suitable for
345 * including in a search index
346 *
347 * @param int $ns a namespace index
348 * @param string $title text-form main part
349 * @return string a stripped-down title string ready for the
350 * search index
351 */
352 /* static */ function indexTitle( $ns, $title ) {
353 global $wgContLang;
354
355 $lc = SearchEngine::legalSearchChars() . '&#;';
356 $t = $wgContLang->stripForSearch( $title );
357 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
358 $t = $wgContLang->lc( $t );
359
360 # Handle 's, s'
361 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
362 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
363
364 $t = preg_replace( "/\\s+/", ' ', $t );
365
366 if ( $ns == NS_IMAGE ) {
367 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
368 }
369 return trim( $t );
370 }
371
372 /*
373 * Make a prefixed DB key from a DB key and a namespace index
374 * @param int $ns numerical representation of the namespace
375 * @param string $title the DB key form the title
376 * @return string the prefixed form of the title
377 */
378 public static function makeName( $ns, $title ) {
379 global $wgContLang;
380
381 $n = $wgContLang->getNsText( $ns );
382 return $n == '' ? $title : "$n:$title";
383 }
384
385 /**
386 * Returns the URL associated with an interwiki prefix
387 * @param string $key the interwiki prefix (e.g. "MeatBall")
388 * @return the associated URL, containing "$1", which should be
389 * replaced by an article title
390 * @static (arguably)
391 * @access public
392 */
393 function getInterwikiLink( $key ) {
394 global $wgMemc, $wgInterwikiExpiry;
395 global $wgInterwikiCache, $wgContLang;
396 $fname = 'Title::getInterwikiLink';
397
398 $key = $wgContLang->lc( $key );
399
400 $k = wfMemcKey( 'interwiki', $key );
401 if( array_key_exists( $k, Title::$interwikiCache ) ) {
402 return Title::$interwikiCache[$k]->iw_url;
403 }
404
405 if ($wgInterwikiCache) {
406 return Title::getInterwikiCached( $key );
407 }
408
409 $s = $wgMemc->get( $k );
410 # Ignore old keys with no iw_local
411 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
412 Title::$interwikiCache[$k] = $s;
413 return $s->iw_url;
414 }
415
416 $dbr =& wfGetDB( DB_SLAVE );
417 $res = $dbr->select( 'interwiki',
418 array( 'iw_url', 'iw_local', 'iw_trans' ),
419 array( 'iw_prefix' => $key ), $fname );
420 if( !$res ) {
421 return '';
422 }
423
424 $s = $dbr->fetchObject( $res );
425 if( !$s ) {
426 # Cache non-existence: create a blank object and save it to memcached
427 $s = (object)false;
428 $s->iw_url = '';
429 $s->iw_local = 0;
430 $s->iw_trans = 0;
431 }
432 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
433 Title::$interwikiCache[$k] = $s;
434
435 return $s->iw_url;
436 }
437
438 /**
439 * Fetch interwiki prefix data from local cache in constant database
440 *
441 * More logic is explained in DefaultSettings
442 *
443 * @return string URL of interwiki site
444 * @access public
445 */
446 function getInterwikiCached( $key ) {
447 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
448 static $db, $site;
449
450 if (!$db)
451 $db=dba_open($wgInterwikiCache,'r','cdb');
452 /* Resolve site name */
453 if ($wgInterwikiScopes>=3 and !$site) {
454 $site = dba_fetch('__sites:' . wfWikiID(), $db);
455 if ($site=="")
456 $site = $wgInterwikiFallbackSite;
457 }
458 $value = dba_fetch( wfMemcKey( $key ), $db);
459 if ($value=='' and $wgInterwikiScopes>=3) {
460 /* try site-level */
461 $value = dba_fetch("_{$site}:{$key}", $db);
462 }
463 if ($value=='' and $wgInterwikiScopes>=2) {
464 /* try globals */
465 $value = dba_fetch("__global:{$key}", $db);
466 }
467 if ($value=='undef')
468 $value='';
469 $s = (object)false;
470 $s->iw_url = '';
471 $s->iw_local = 0;
472 $s->iw_trans = 0;
473 if ($value!='') {
474 list($local,$url)=explode(' ',$value,2);
475 $s->iw_url=$url;
476 $s->iw_local=(int)$local;
477 }
478 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
479 return $s->iw_url;
480 }
481 /**
482 * Determine whether the object refers to a page within
483 * this project.
484 *
485 * @return bool TRUE if this is an in-project interwiki link
486 * or a wikilink, FALSE otherwise
487 * @access public
488 */
489 function isLocal() {
490 if ( $this->mInterwiki != '' ) {
491 # Make sure key is loaded into cache
492 $this->getInterwikiLink( $this->mInterwiki );
493 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
494 return (bool)(Title::$interwikiCache[$k]->iw_local);
495 } else {
496 return true;
497 }
498 }
499
500 /**
501 * Determine whether the object refers to a page within
502 * this project and is transcludable.
503 *
504 * @return bool TRUE if this is transcludable
505 * @access public
506 */
507 function isTrans() {
508 if ($this->mInterwiki == '')
509 return false;
510 # Make sure key is loaded into cache
511 $this->getInterwikiLink( $this->mInterwiki );
512 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
513 return (bool)(Title::$interwikiCache[$k]->iw_trans);
514 }
515
516 /**
517 * Update the page_touched field for an array of title objects
518 * @todo Inefficient unless the IDs are already loaded into the
519 * link cache
520 * @param array $titles an array of Title objects to be touched
521 * @param string $timestamp the timestamp to use instead of the
522 * default current time
523 * @static
524 * @access public
525 */
526 function touchArray( $titles, $timestamp = '' ) {
527
528 if ( count( $titles ) == 0 ) {
529 return;
530 }
531 $dbw =& wfGetDB( DB_MASTER );
532 if ( $timestamp == '' ) {
533 $timestamp = $dbw->timestamp();
534 }
535 /*
536 $page = $dbw->tableName( 'page' );
537 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
538 $first = true;
539
540 foreach ( $titles as $title ) {
541 if ( $wgUseFileCache ) {
542 $cm = new HTMLFileCache($title);
543 @unlink($cm->fileCacheName());
544 }
545
546 if ( ! $first ) {
547 $sql .= ',';
548 }
549 $first = false;
550 $sql .= $title->getArticleID();
551 }
552 $sql .= ')';
553 if ( ! $first ) {
554 $dbw->query( $sql, 'Title::touchArray' );
555 }
556 */
557 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
558 // do them in small chunks:
559 $fname = 'Title::touchArray';
560 foreach( $titles as $title ) {
561 $dbw->update( 'page',
562 array( 'page_touched' => $timestamp ),
563 array(
564 'page_namespace' => $title->getNamespace(),
565 'page_title' => $title->getDBkey() ),
566 $fname );
567 }
568 }
569
570 #----------------------------------------------------------------------------
571 # Other stuff
572 #----------------------------------------------------------------------------
573
574 /** Simple accessors */
575 /**
576 * Get the text form (spaces not underscores) of the main part
577 * @return string
578 * @access public
579 */
580 function getText() { return $this->mTextform; }
581 /**
582 * Get the URL-encoded form of the main part
583 * @return string
584 * @access public
585 */
586 function getPartialURL() { return $this->mUrlform; }
587 /**
588 * Get the main part with underscores
589 * @return string
590 * @access public
591 */
592 function getDBkey() { return $this->mDbkeyform; }
593 /**
594 * Get the namespace index, i.e. one of the NS_xxxx constants
595 * @return int
596 * @access public
597 */
598 function getNamespace() { return $this->mNamespace; }
599 /**
600 * Get the namespace text
601 * @return string
602 * @access public
603 */
604 function getNsText() {
605 global $wgContLang;
606 return $wgContLang->getNsText( $this->mNamespace );
607 }
608 /**
609 * Get the namespace text of the subject (rather than talk) page
610 * @return string
611 * @access public
612 */
613 function getSubjectNsText() {
614 global $wgContLang;
615 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
616 }
617
618 /**
619 * Get the namespace text of the talk page
620 * @return string
621 */
622 function getTalkNsText() {
623 global $wgContLang;
624 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
625 }
626
627 /**
628 * Could this title have a corresponding talk page?
629 * @return bool
630 */
631 function canTalk() {
632 return( Namespace::canTalk( $this->mNamespace ) );
633 }
634
635 /**
636 * Get the interwiki prefix (or null string)
637 * @return string
638 * @access public
639 */
640 function getInterwiki() { return $this->mInterwiki; }
641 /**
642 * Get the Title fragment (i.e. the bit after the #)
643 * @return string
644 * @access public
645 */
646 function getFragment() { return $this->mFragment; }
647 /**
648 * Get the default namespace index, for when there is no namespace
649 * @return int
650 * @access public
651 */
652 function getDefaultNamespace() { return $this->mDefaultNamespace; }
653
654 /**
655 * Get title for search index
656 * @return string a stripped-down title string ready for the
657 * search index
658 */
659 function getIndexTitle() {
660 return Title::indexTitle( $this->mNamespace, $this->mTextform );
661 }
662
663 /**
664 * Get the prefixed database key form
665 * @return string the prefixed title, with underscores and
666 * any interwiki and namespace prefixes
667 * @access public
668 */
669 function getPrefixedDBkey() {
670 $s = $this->prefix( $this->mDbkeyform );
671 $s = str_replace( ' ', '_', $s );
672 return $s;
673 }
674
675 /**
676 * Get the prefixed title with spaces.
677 * This is the form usually used for display
678 * @return string the prefixed title, with spaces
679 * @access public
680 */
681 function getPrefixedText() {
682 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
683 $s = $this->prefix( $this->mTextform );
684 $s = str_replace( '_', ' ', $s );
685 $this->mPrefixedText = $s;
686 }
687 return $this->mPrefixedText;
688 }
689
690 /**
691 * Get the prefixed title with spaces, plus any fragment
692 * (part beginning with '#')
693 * @return string the prefixed title, with spaces and
694 * the fragment, including '#'
695 * @access public
696 */
697 function getFullText() {
698 $text = $this->getPrefixedText();
699 if( '' != $this->mFragment ) {
700 $text .= '#' . $this->mFragment;
701 }
702 return $text;
703 }
704
705 /**
706 * Get the base name, i.e. the leftmost parts before the /
707 * @return string Base name
708 */
709 function getBaseText() {
710 global $wgNamespacesWithSubpages;
711 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
712 $parts = explode( '/', $this->getText() );
713 # Don't discard the real title if there's no subpage involved
714 if( count( $parts ) > 1 )
715 unset( $parts[ count( $parts ) - 1 ] );
716 return implode( '/', $parts );
717 } else {
718 return $this->getText();
719 }
720 }
721
722 /**
723 * Get the lowest-level subpage name, i.e. the rightmost part after /
724 * @return string Subpage name
725 */
726 function getSubpageText() {
727 global $wgNamespacesWithSubpages;
728 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
729 $parts = explode( '/', $this->mTextform );
730 return( $parts[ count( $parts ) - 1 ] );
731 } else {
732 return( $this->mTextform );
733 }
734 }
735
736 /**
737 * Get a URL-encoded form of the subpage text
738 * @return string URL-encoded subpage name
739 */
740 function getSubpageUrlForm() {
741 $text = $this->getSubpageText();
742 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
743 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
744 return( $text );
745 }
746
747 /**
748 * Get a URL-encoded title (not an actual URL) including interwiki
749 * @return string the URL-encoded form
750 * @access public
751 */
752 function getPrefixedURL() {
753 $s = $this->prefix( $this->mDbkeyform );
754 $s = str_replace( ' ', '_', $s );
755
756 $s = wfUrlencode ( $s ) ;
757
758 # Cleaning up URL to make it look nice -- is this safe?
759 $s = str_replace( '%28', '(', $s );
760 $s = str_replace( '%29', ')', $s );
761
762 return $s;
763 }
764
765 /**
766 * Get a real URL referring to this title, with interwiki link and
767 * fragment
768 *
769 * @param string $query an optional query string, not used
770 * for interwiki links
771 * @param string $variant language variant of url (for sr, zh..)
772 * @return string the URL
773 * @access public
774 */
775 function getFullURL( $query = '', $variant = false ) {
776 global $wgContLang, $wgServer, $wgRequest;
777
778 if ( '' == $this->mInterwiki ) {
779 $url = $this->getLocalUrl( $query, $variant );
780
781 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
782 // Correct fix would be to move the prepending elsewhere.
783 if ($wgRequest->getVal('action') != 'render') {
784 $url = $wgServer . $url;
785 }
786 } else {
787 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
788
789 $namespace = $wgContLang->getNsText( $this->mNamespace );
790 if ( '' != $namespace ) {
791 # Can this actually happen? Interwikis shouldn't be parsed.
792 $namespace .= ':';
793 }
794 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
795 if( $query != '' ) {
796 if( false === strpos( $url, '?' ) ) {
797 $url .= '?';
798 } else {
799 $url .= '&';
800 }
801 $url .= $query;
802 }
803 }
804
805 # Finally, add the fragment.
806 if ( '' != $this->mFragment ) {
807 $url .= '#' . $this->mFragment;
808 }
809
810 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
811 return $url;
812 }
813
814 /**
815 * Get a URL with no fragment or server name. If this page is generated
816 * with action=render, $wgServer is prepended.
817 * @param string $query an optional query string; if not specified,
818 * $wgArticlePath will be used.
819 * @param string $variant language variant of url (for sr, zh..)
820 * @return string the URL
821 * @access public
822 */
823 function getLocalURL( $query = '', $variant = false ) {
824 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
825 global $wgVariantArticlePath, $wgContLang, $wgUser;
826
827 // internal links should point to same variant as current page (only anonymous users)
828 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
829 $pref = $wgContLang->getPreferredVariant(false);
830 if($pref != $wgContLang->getCode())
831 $variant = $pref;
832 }
833
834 if ( $this->isExternal() ) {
835 $url = $this->getFullURL();
836 if ( $query ) {
837 // This is currently only used for edit section links in the
838 // context of interwiki transclusion. In theory we should
839 // append the query to the end of any existing query string,
840 // but interwiki transclusion is already broken in that case.
841 $url .= "?$query";
842 }
843 } else {
844 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
845 if ( $query == '' ) {
846 if($variant!=false && $wgContLang->hasVariants()){
847 if($wgVariantArticlePath==false)
848 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
849 else
850 $variantArticlePath = $wgVariantArticlePath;
851
852 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
853 $url = str_replace( '$1', $dbkey, $url );
854
855 }
856 else
857 $url = str_replace( '$1', $dbkey, $wgArticlePath );
858 } else {
859 global $wgActionPaths;
860 $url = false;
861 $matches = array();
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 ( NS_SPECIAL == $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 ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
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->isSpecial( 'Userlogin' ) ) {
1168 return true;
1169 }
1170
1171 /** some pages are explicitly allowed */
1172 $name = $this->getPrefixedText();
1173 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1174 return true;
1175 }
1176
1177 # Compatibility with old settings
1178 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1179 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1180 return true;
1181 }
1182 }
1183 }
1184 return false;
1185 }
1186
1187 /**
1188 * Is this a talk page of some sort?
1189 * @return bool
1190 * @access public
1191 */
1192 function isTalkPage() {
1193 return Namespace::isTalk( $this->getNamespace() );
1194 }
1195
1196 /**
1197 * Is this a .css or .js subpage of a user page?
1198 * @return bool
1199 * @access public
1200 */
1201 function isCssJsSubpage() {
1202 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1203 }
1204 /**
1205 * Is this a *valid* .css or .js subpage of a user page?
1206 * Check that the corresponding skin exists
1207 */
1208 function isValidCssJsSubpage() {
1209 if ( $this->isCssJsSubpage() ) {
1210 $skinNames = Skin::getSkinNames();
1211 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1212 } else {
1213 return false;
1214 }
1215 }
1216 /**
1217 * Trim down a .css or .js subpage title to get the corresponding skin name
1218 */
1219 function getSkinFromCssJsSubpage() {
1220 $subpage = explode( '/', $this->mTextform );
1221 $subpage = $subpage[ count( $subpage ) - 1 ];
1222 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1223 }
1224 /**
1225 * Is this a .css subpage of a user page?
1226 * @return bool
1227 * @access public
1228 */
1229 function isCssSubpage() {
1230 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1231 }
1232 /**
1233 * Is this a .js subpage of a user page?
1234 * @return bool
1235 * @access public
1236 */
1237 function isJsSubpage() {
1238 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1239 }
1240 /**
1241 * Protect css/js subpages of user pages: can $wgUser edit
1242 * this page?
1243 *
1244 * @return boolean
1245 * @todo XXX: this might be better using restrictions
1246 * @access public
1247 */
1248 function userCanEditCssJsSubpage() {
1249 global $wgUser;
1250 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1251 }
1252
1253 /**
1254 * Loads a string into mRestrictions array
1255 * @param string $res restrictions in string format
1256 * @access public
1257 */
1258 function loadRestrictions( $res ) {
1259 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1260 $temp = explode( '=', trim( $restrict ) );
1261 if(count($temp) == 1) {
1262 // old format should be treated as edit/move restriction
1263 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1264 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1265 } else {
1266 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1267 }
1268 }
1269 $this->mRestrictionsLoaded = true;
1270 }
1271
1272 /**
1273 * Accessor/initialisation for mRestrictions
1274 * @param string $action action that permission needs to be checked for
1275 * @return array the array of groups allowed to edit this article
1276 * @access public
1277 */
1278 function getRestrictions($action) {
1279 $id = $this->getArticleID();
1280 if ( 0 == $id ) { return array(); }
1281
1282 if ( ! $this->mRestrictionsLoaded ) {
1283 $dbr =& wfGetDB( DB_SLAVE );
1284 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1285 $this->loadRestrictions( $res );
1286 }
1287 if( isset( $this->mRestrictions[$action] ) ) {
1288 return $this->mRestrictions[$action];
1289 }
1290 return array();
1291 }
1292
1293 /**
1294 * Is there a version of this page in the deletion archive?
1295 * @return int the number of archived revisions
1296 * @access public
1297 */
1298 function isDeleted() {
1299 $fname = 'Title::isDeleted';
1300 if ( $this->getNamespace() < 0 ) {
1301 $n = 0;
1302 } else {
1303 $dbr =& wfGetDB( DB_SLAVE );
1304 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1305 'ar_title' => $this->getDBkey() ), $fname );
1306 if( $this->getNamespace() == NS_IMAGE ) {
1307 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1308 array( 'fa_name' => $this->getDBkey() ), $fname );
1309 }
1310 }
1311 return (int)$n;
1312 }
1313
1314 /**
1315 * Get the article ID for this Title from the link cache,
1316 * adding it if necessary
1317 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1318 * for update
1319 * @return int the ID
1320 * @access public
1321 */
1322 function getArticleID( $flags = 0 ) {
1323 $linkCache =& LinkCache::singleton();
1324 if ( $flags & GAID_FOR_UPDATE ) {
1325 $oldUpdate = $linkCache->forUpdate( true );
1326 $this->mArticleID = $linkCache->addLinkObj( $this );
1327 $linkCache->forUpdate( $oldUpdate );
1328 } else {
1329 if ( -1 == $this->mArticleID ) {
1330 $this->mArticleID = $linkCache->addLinkObj( $this );
1331 }
1332 }
1333 return $this->mArticleID;
1334 }
1335
1336 function getLatestRevID() {
1337 if ($this->mLatestID !== false)
1338 return $this->mLatestID;
1339
1340 $db =& wfGetDB(DB_SLAVE);
1341 return $this->mLatestID = $db->selectField( 'revision',
1342 "max(rev_id)",
1343 array('rev_page' => $this->getArticleID()),
1344 'Title::getLatestRevID' );
1345 }
1346
1347 /**
1348 * This clears some fields in this object, and clears any associated
1349 * keys in the "bad links" section of the link cache.
1350 *
1351 * - This is called from Article::insertNewArticle() to allow
1352 * loading of the new page_id. It's also called from
1353 * Article::doDeleteArticle()
1354 *
1355 * @param int $newid the new Article ID
1356 * @access public
1357 */
1358 function resetArticleID( $newid ) {
1359 $linkCache =& LinkCache::singleton();
1360 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1361
1362 if ( 0 == $newid ) { $this->mArticleID = -1; }
1363 else { $this->mArticleID = $newid; }
1364 $this->mRestrictionsLoaded = false;
1365 $this->mRestrictions = array();
1366 }
1367
1368 /**
1369 * Updates page_touched for this page; called from LinksUpdate.php
1370 * @return bool true if the update succeded
1371 * @access public
1372 */
1373 function invalidateCache() {
1374 global $wgUseFileCache;
1375
1376 if ( wfReadOnly() ) {
1377 return;
1378 }
1379
1380 $dbw =& wfGetDB( DB_MASTER );
1381 $success = $dbw->update( 'page',
1382 array( /* SET */
1383 'page_touched' => $dbw->timestamp()
1384 ), array( /* WHERE */
1385 'page_namespace' => $this->getNamespace() ,
1386 'page_title' => $this->getDBkey()
1387 ), 'Title::invalidateCache'
1388 );
1389
1390 if ($wgUseFileCache) {
1391 $cache = new HTMLFileCache($this);
1392 @unlink($cache->fileCacheName());
1393 }
1394
1395 return $success;
1396 }
1397
1398 /**
1399 * Prefix some arbitrary text with the namespace or interwiki prefix
1400 * of this object
1401 *
1402 * @param string $name the text
1403 * @return string the prefixed text
1404 * @private
1405 */
1406 /* private */ function prefix( $name ) {
1407 global $wgContLang;
1408
1409 $p = '';
1410 if ( '' != $this->mInterwiki ) {
1411 $p = $this->mInterwiki . ':';
1412 }
1413 if ( 0 != $this->mNamespace ) {
1414 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1415 }
1416 return $p . $name;
1417 }
1418
1419 /**
1420 * Secure and split - main initialisation function for this object
1421 *
1422 * Assumes that mDbkeyform has been set, and is urldecoded
1423 * and uses underscores, but not otherwise munged. This function
1424 * removes illegal characters, splits off the interwiki and
1425 * namespace prefixes, sets the other forms, and canonicalizes
1426 * everything.
1427 * @return bool true on success
1428 * @private
1429 */
1430 /* private */ function secureAndSplit() {
1431 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
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 $m = array();
1470 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1471 $p = $m[1];
1472 $lowerNs = $wgContLang->lc( $p );
1473 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1474 # Canonical namespace
1475 $t = $m[2];
1476 $this->mNamespace = $ns;
1477 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1478 # Ordinary namespace
1479 $t = $m[2];
1480 $this->mNamespace = $ns;
1481 } elseif( $this->getInterwikiLink( $p ) ) {
1482 if( !$firstPass ) {
1483 # Can't make a local interwiki link to an interwiki link.
1484 # That's just crazy!
1485 return false;
1486 }
1487
1488 # Interwiki link
1489 $t = $m[2];
1490 $this->mInterwiki = $wgContLang->lc( $p );
1491
1492 # Redundant interwiki prefix to the local wiki
1493 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1494 if( $t == '' ) {
1495 # Can't have an empty self-link
1496 return false;
1497 }
1498 $this->mInterwiki = '';
1499 $firstPass = false;
1500 # Do another namespace split...
1501 continue;
1502 }
1503
1504 # If there's an initial colon after the interwiki, that also
1505 # resets the default namespace
1506 if ( $t !== '' && $t[0] == ':' ) {
1507 $this->mNamespace = NS_MAIN;
1508 $t = substr( $t, 1 );
1509 }
1510 }
1511 # If there's no recognized interwiki or namespace,
1512 # then let the colon expression be part of the title.
1513 }
1514 break;
1515 } while( true );
1516 $r = $t;
1517
1518 # We already know that some pages won't be in the database!
1519 #
1520 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1521 $this->mArticleID = 0;
1522 }
1523 $f = strstr( $r, '#' );
1524 if ( false !== $f ) {
1525 $this->mFragment = substr( $f, 1 );
1526 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1527 # remove whitespace again: prevents "Foo_bar_#"
1528 # becoming "Foo_bar_"
1529 $r = preg_replace( '/_*$/', '', $r );
1530 }
1531
1532 # Reject illegal characters.
1533 #
1534 if( preg_match( $rxTc, $r ) ) {
1535 return false;
1536 }
1537
1538 /**
1539 * Pages with "/./" or "/../" appearing in the URLs will
1540 * often be unreachable due to the way web browsers deal
1541 * with 'relative' URLs. Forbid them explicitly.
1542 */
1543 if ( strpos( $r, '.' ) !== false &&
1544 ( $r === '.' || $r === '..' ||
1545 strpos( $r, './' ) === 0 ||
1546 strpos( $r, '../' ) === 0 ||
1547 strpos( $r, '/./' ) !== false ||
1548 strpos( $r, '/../' ) !== false ) )
1549 {
1550 return false;
1551 }
1552
1553 # We shouldn't need to query the DB for the size.
1554 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1555 if ( strlen( $r ) > 255 ) {
1556 return false;
1557 }
1558
1559 /**
1560 * Normally, all wiki links are forced to have
1561 * an initial capital letter so [[foo]] and [[Foo]]
1562 * point to the same place.
1563 *
1564 * Don't force it for interwikis, since the other
1565 * site might be case-sensitive.
1566 */
1567 if( $wgCapitalLinks && $this->mInterwiki == '') {
1568 $t = $wgContLang->ucfirst( $r );
1569 } else {
1570 $t = $r;
1571 }
1572
1573 /**
1574 * Can't make a link to a namespace alone...
1575 * "empty" local links can only be self-links
1576 * with a fragment identifier.
1577 */
1578 if( $t == '' &&
1579 $this->mInterwiki == '' &&
1580 $this->mNamespace != NS_MAIN ) {
1581 return false;
1582 }
1583
1584 // Any remaining initial :s are illegal.
1585 if ( $t !== '' && ':' == $t{0} ) {
1586 return false;
1587 }
1588
1589 # Fill fields
1590 $this->mDbkeyform = $t;
1591 $this->mUrlform = wfUrlencode( $t );
1592
1593 $this->mTextform = str_replace( '_', ' ', $t );
1594
1595 return true;
1596 }
1597
1598 /**
1599 * Get a Title object associated with the talk page of this article
1600 * @return Title the object for the talk page
1601 * @access public
1602 */
1603 function getTalkPage() {
1604 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1605 }
1606
1607 /**
1608 * Get a title object associated with the subject page of this
1609 * talk page
1610 *
1611 * @return Title the object for the subject page
1612 * @access public
1613 */
1614 function getSubjectPage() {
1615 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1616 }
1617
1618 /**
1619 * Get an array of Title objects linking to this Title
1620 * Also stores the IDs in the link cache.
1621 *
1622 * WARNING: do not use this function on arbitrary user-supplied titles!
1623 * On heavily-used templates it will max out the memory.
1624 *
1625 * @param string $options may be FOR UPDATE
1626 * @return array the Title objects linking here
1627 * @access public
1628 */
1629 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1630 $linkCache =& LinkCache::singleton();
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 $newid = $nt->getArticleID();
1902 $oldid = $this->getArticleID();
1903 $dbw =& wfGetDB( DB_MASTER );
1904 $linkCache =& LinkCache::singleton();
1905
1906 # Delete the old redirect. We don't save it to history since
1907 # by definition if we've got here it's rather uninteresting.
1908 # We have to remove it so that the next step doesn't trigger
1909 # a conflict on the unique namespace+title index...
1910 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1911
1912 # Save a null revision in the page's history notifying of the move
1913 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1914 $nullRevId = $nullRevision->insertOn( $dbw );
1915
1916 # Change the name of the target page:
1917 $dbw->update( 'page',
1918 /* SET */ array(
1919 'page_touched' => $dbw->timestamp($now),
1920 'page_namespace' => $nt->getNamespace(),
1921 'page_title' => $nt->getDBkey(),
1922 'page_latest' => $nullRevId,
1923 ),
1924 /* WHERE */ array( 'page_id' => $oldid ),
1925 $fname
1926 );
1927 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1928
1929 # Recreate the redirect, this time in the other direction.
1930 $mwRedir = MagicWord::get( 'redirect' );
1931 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1932 $redirectArticle = new Article( $this );
1933 $newid = $redirectArticle->insertOn( $dbw );
1934 $redirectRevision = new Revision( array(
1935 'page' => $newid,
1936 'comment' => $comment,
1937 'text' => $redirectText ) );
1938 $redirectRevision->insertOn( $dbw );
1939 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1940 $linkCache->clearLink( $this->getPrefixedDBkey() );
1941
1942 # Log the move
1943 $log = new LogPage( 'move' );
1944 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1945
1946 # Now, we record the link from the redirect to the new title.
1947 # It should have no other outgoing links...
1948 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1949 $dbw->insert( 'pagelinks',
1950 array(
1951 'pl_from' => $newid,
1952 'pl_namespace' => $nt->getNamespace(),
1953 'pl_title' => $nt->getDbKey() ),
1954 $fname );
1955
1956 # Purge squid
1957 if ( $wgUseSquid ) {
1958 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1959 $u = new SquidUpdate( $urls );
1960 $u->doUpdate();
1961 }
1962 }
1963
1964 /**
1965 * Move page to non-existing title.
1966 * @param Title &$nt the new Title
1967 * @private
1968 */
1969 function moveToNewTitle( &$nt, $reason = '' ) {
1970 global $wgUseSquid;
1971 $fname = 'MovePageForm::moveToNewTitle';
1972 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1973 if ( $reason ) {
1974 $comment .= ": $reason";
1975 }
1976
1977 $newid = $nt->getArticleID();
1978 $oldid = $this->getArticleID();
1979 $dbw =& wfGetDB( DB_MASTER );
1980 $now = $dbw->timestamp();
1981 $linkCache =& LinkCache::singleton();
1982
1983 # Save a null revision in the page's history notifying of the move
1984 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
1985 $nullRevId = $nullRevision->insertOn( $dbw );
1986
1987 # Rename cur entry
1988 $dbw->update( 'page',
1989 /* SET */ array(
1990 'page_touched' => $now,
1991 'page_namespace' => $nt->getNamespace(),
1992 'page_title' => $nt->getDBkey(),
1993 'page_latest' => $nullRevId,
1994 ),
1995 /* WHERE */ array( 'page_id' => $oldid ),
1996 $fname
1997 );
1998
1999 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2000
2001 # Insert redirect
2002 $mwRedir = MagicWord::get( 'redirect' );
2003 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2004 $redirectArticle = new Article( $this );
2005 $newid = $redirectArticle->insertOn( $dbw );
2006 $redirectRevision = new Revision( array(
2007 'page' => $newid,
2008 'comment' => $comment,
2009 'text' => $redirectText ) );
2010 $redirectRevision->insertOn( $dbw );
2011 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2012 $linkCache->clearLink( $this->getPrefixedDBkey() );
2013
2014 # Log the move
2015 $log = new LogPage( 'move' );
2016 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2017
2018 # Purge caches as per article creation
2019 Article::onArticleCreate( $nt );
2020
2021 # Record the just-created redirect's linking to the page
2022 $dbw->insert( 'pagelinks',
2023 array(
2024 'pl_from' => $newid,
2025 'pl_namespace' => $nt->getNamespace(),
2026 'pl_title' => $nt->getDBkey() ),
2027 $fname );
2028
2029 # Purge old title from squid
2030 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2031 $this->purgeSquid();
2032 }
2033
2034 /**
2035 * Checks if $this can be moved to a given Title
2036 * - Selects for update, so don't call it unless you mean business
2037 *
2038 * @param Title &$nt the new title to check
2039 * @access public
2040 */
2041 function isValidMoveTarget( $nt ) {
2042
2043 $fname = 'Title::isValidMoveTarget';
2044 $dbw =& wfGetDB( DB_MASTER );
2045
2046 # Is it a redirect?
2047 $id = $nt->getArticleID();
2048 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2049 array( 'page_is_redirect','old_text','old_flags' ),
2050 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2051 $fname, 'FOR UPDATE' );
2052
2053 if ( !$obj || 0 == $obj->page_is_redirect ) {
2054 # Not a redirect
2055 wfDebug( __METHOD__ . ": not a redirect\n" );
2056 return false;
2057 }
2058 $text = Revision::getRevisionText( $obj );
2059
2060 # Does the redirect point to the source?
2061 # Or is it a broken self-redirect, usually caused by namespace collisions?
2062 $m = array();
2063 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2064 $redirTitle = Title::newFromText( $m[1] );
2065 if( !is_object( $redirTitle ) ||
2066 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2067 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2068 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2069 return false;
2070 }
2071 } else {
2072 # Fail safe
2073 wfDebug( __METHOD__ . ": failsafe\n" );
2074 return false;
2075 }
2076
2077 # Does the article have a history?
2078 $row = $dbw->selectRow( array( 'page', 'revision'),
2079 array( 'rev_id' ),
2080 array( 'page_namespace' => $nt->getNamespace(),
2081 'page_title' => $nt->getDBkey(),
2082 'page_id=rev_page AND page_latest != rev_id'
2083 ), $fname, 'FOR UPDATE'
2084 );
2085
2086 # Return true if there was no history
2087 return $row === false;
2088 }
2089
2090 /**
2091 * Create a redirect; fails if the title already exists; does
2092 * not notify RC
2093 *
2094 * @param Title $dest the destination of the redirect
2095 * @param string $comment the comment string describing the move
2096 * @return bool true on success
2097 * @access public
2098 */
2099 function createRedirect( $dest, $comment ) {
2100 if ( $this->getArticleID() ) {
2101 return false;
2102 }
2103
2104 $fname = 'Title::createRedirect';
2105 $dbw =& wfGetDB( DB_MASTER );
2106
2107 $article = new Article( $this );
2108 $newid = $article->insertOn( $dbw );
2109 $revision = new Revision( array(
2110 'page' => $newid,
2111 'comment' => $comment,
2112 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2113 ) );
2114 $revision->insertOn( $dbw );
2115 $article->updateRevisionOn( $dbw, $revision, 0 );
2116
2117 # Link table
2118 $dbw->insert( 'pagelinks',
2119 array(
2120 'pl_from' => $newid,
2121 'pl_namespace' => $dest->getNamespace(),
2122 'pl_title' => $dest->getDbKey()
2123 ), $fname
2124 );
2125
2126 Article::onArticleCreate( $this );
2127 return true;
2128 }
2129
2130 /**
2131 * Get categories to which this Title belongs and return an array of
2132 * categories' names.
2133 *
2134 * @return array an array of parents in the form:
2135 * $parent => $currentarticle
2136 * @access public
2137 */
2138 function getParentCategories() {
2139 global $wgContLang;
2140
2141 $titlekey = $this->getArticleId();
2142 $dbr =& wfGetDB( DB_SLAVE );
2143 $categorylinks = $dbr->tableName( 'categorylinks' );
2144
2145 # NEW SQL
2146 $sql = "SELECT * FROM $categorylinks"
2147 ." WHERE cl_from='$titlekey'"
2148 ." AND cl_from <> '0'"
2149 ." ORDER BY cl_sortkey";
2150
2151 $res = $dbr->query ( $sql ) ;
2152
2153 if($dbr->numRows($res) > 0) {
2154 while ( $x = $dbr->fetchObject ( $res ) )
2155 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2156 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2157 $dbr->freeResult ( $res ) ;
2158 } else {
2159 $data = '';
2160 }
2161 return $data;
2162 }
2163
2164 /**
2165 * Get a tree of parent categories
2166 * @param array $children an array with the children in the keys, to check for circular refs
2167 * @return array
2168 * @access public
2169 */
2170 function getParentCategoryTree( $children = array() ) {
2171 $parents = $this->getParentCategories();
2172
2173 if($parents != '') {
2174 foreach($parents as $parent => $current) {
2175 if ( array_key_exists( $parent, $children ) ) {
2176 # Circular reference
2177 $stack[$parent] = array();
2178 } else {
2179 $nt = Title::newFromText($parent);
2180 if ( $nt ) {
2181 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2182 }
2183 }
2184 }
2185 return $stack;
2186 } else {
2187 return array();
2188 }
2189 }
2190
2191
2192 /**
2193 * Get an associative array for selecting this title from
2194 * the "page" table
2195 *
2196 * @return array
2197 * @access public
2198 */
2199 function pageCond() {
2200 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2201 }
2202
2203 /**
2204 * Get the revision ID of the previous revision
2205 *
2206 * @param integer $revision Revision ID. Get the revision that was before this one.
2207 * @return interger $oldrevision|false
2208 */
2209 function getPreviousRevisionID( $revision ) {
2210 $dbr =& wfGetDB( DB_SLAVE );
2211 return $dbr->selectField( 'revision', 'rev_id',
2212 'rev_page=' . intval( $this->getArticleId() ) .
2213 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2214 }
2215
2216 /**
2217 * Get the revision ID of the next revision
2218 *
2219 * @param integer $revision Revision ID. Get the revision that was after this one.
2220 * @return interger $oldrevision|false
2221 */
2222 function getNextRevisionID( $revision ) {
2223 $dbr =& wfGetDB( DB_SLAVE );
2224 return $dbr->selectField( 'revision', 'rev_id',
2225 'rev_page=' . intval( $this->getArticleId() ) .
2226 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2227 }
2228
2229 /**
2230 * Compare with another title.
2231 *
2232 * @param Title $title
2233 * @return bool
2234 */
2235 function equals( $title ) {
2236 // Note: === is necessary for proper matching of number-like titles.
2237 return $this->getInterwiki() === $title->getInterwiki()
2238 && $this->getNamespace() == $title->getNamespace()
2239 && $this->getDbkey() === $title->getDbkey();
2240 }
2241
2242 /**
2243 * Check if page exists
2244 * @return bool
2245 */
2246 function exists() {
2247 return $this->getArticleId() != 0;
2248 }
2249
2250 /**
2251 * Should a link should be displayed as a known link, just based on its title?
2252 *
2253 * Currently, a self-link with a fragment and special pages are in
2254 * this category. Special pages never exist in the database.
2255 */
2256 function isAlwaysKnown() {
2257 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2258 || NS_SPECIAL == $this->mNamespace;
2259 }
2260
2261 /**
2262 * Update page_touched timestamps and send squid purge messages for
2263 * pages linking to this title. May be sent to the job queue depending
2264 * on the number of links. Typically called on create and delete.
2265 */
2266 function touchLinks() {
2267 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2268 $u->doUpdate();
2269
2270 if ( $this->getNamespace() == NS_CATEGORY ) {
2271 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2272 $u->doUpdate();
2273 }
2274 }
2275
2276 /**
2277 * Get the last touched timestamp
2278 */
2279 function getTouched() {
2280 $dbr =& wfGetDB( DB_SLAVE );
2281 $touched = $dbr->selectField( 'page', 'page_touched',
2282 array(
2283 'page_namespace' => $this->getNamespace(),
2284 'page_title' => $this->getDBkey()
2285 ), __METHOD__
2286 );
2287 return $touched;
2288 }
2289
2290 /**
2291 * Get a cached value from a global cache that is invalidated when this page changes
2292 * @param string $key the key
2293 * @param callback $callback A callback function which generates the value on cache miss
2294 *
2295 * @deprecated use DependencyWrapper
2296 */
2297 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2298 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2299 $params, new TitleDependency( $this ) );
2300 }
2301
2302 function trackbackURL() {
2303 global $wgTitle, $wgScriptPath, $wgServer;
2304
2305 return "$wgServer$wgScriptPath/trackback.php?article="
2306 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2307 }
2308
2309 function trackbackRDF() {
2310 $url = htmlspecialchars($this->getFullURL());
2311 $title = htmlspecialchars($this->getText());
2312 $tburl = $this->trackbackURL();
2313
2314 return "
2315 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2316 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2317 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2318 <rdf:Description
2319 rdf:about=\"$url\"
2320 dc:identifier=\"$url\"
2321 dc:title=\"$title\"
2322 trackback:ping=\"$tburl\" />
2323 </rdf:RDF>";
2324 }
2325
2326 /**
2327 * Generate strings used for xml 'id' names in monobook tabs
2328 * @return string
2329 */
2330 function getNamespaceKey() {
2331 global $wgContLang;
2332 switch ($this->getNamespace()) {
2333 case NS_MAIN:
2334 case NS_TALK:
2335 return 'nstab-main';
2336 case NS_USER:
2337 case NS_USER_TALK:
2338 return 'nstab-user';
2339 case NS_MEDIA:
2340 return 'nstab-media';
2341 case NS_SPECIAL:
2342 return 'nstab-special';
2343 case NS_PROJECT:
2344 case NS_PROJECT_TALK:
2345 return 'nstab-project';
2346 case NS_IMAGE:
2347 case NS_IMAGE_TALK:
2348 return 'nstab-image';
2349 case NS_MEDIAWIKI:
2350 case NS_MEDIAWIKI_TALK:
2351 return 'nstab-mediawiki';
2352 case NS_TEMPLATE:
2353 case NS_TEMPLATE_TALK:
2354 return 'nstab-template';
2355 case NS_HELP:
2356 case NS_HELP_TALK:
2357 return 'nstab-help';
2358 case NS_CATEGORY:
2359 case NS_CATEGORY_TALK:
2360 return 'nstab-category';
2361 default:
2362 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2363 }
2364 }
2365
2366 /**
2367 * Returns true if this title resolves to the named special page
2368 * @param string $name The special page name
2369 * @access public
2370 */
2371 function isSpecial( $name ) {
2372 if ( $this->getNamespace() == NS_SPECIAL ) {
2373 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2374 if ( $name == $thisName ) {
2375 return true;
2376 }
2377 }
2378 return false;
2379 }
2380
2381 /**
2382 * If the Title refers to a special page alias which is not the local default,
2383 * returns a new Title which points to the local default. Otherwise, returns $this.
2384 */
2385 function fixSpecialName() {
2386 if ( $this->getNamespace() == NS_SPECIAL ) {
2387 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2388 if ( $canonicalName ) {
2389 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2390 if ( $localName != $this->mDbkeyform ) {
2391 return Title::makeTitle( NS_SPECIAL, $localName );
2392 }
2393 }
2394 }
2395 return $this;
2396 }
2397 }
2398 ?>