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