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