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