Allow customizing the minimum per-namespace protection level via $wgNamespaceProtection.
[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 # Constants for pr_cascade bitfield
21 define( 'CASCADE', 1 );
22
23 /**
24 * Title class
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
27 *
28 * @package MediaWiki
29 */
30 class Title {
31 /**
32 * Static cache variables
33 */
34 static private $titleCache=array();
35 static private $interwikiCache=array();
36
37
38 /**
39 * All member variables should be considered private
40 * Please use the accessor functions
41 */
42
43 /**#@+
44 * @private
45 */
46
47 var $mTextform; # Text form (spaces not underscores) of the main part
48 var $mUrlform; # URL-encoded form of the main part
49 var $mDbkeyform; # Main part with underscores
50 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
51 var $mInterwiki; # Interwiki prefix (or null string)
52 var $mFragment; # Title fragment (i.e. the bit after the #)
53 var $mArticleID; # Article ID, fetched from the link cache on demand
54 var $mLatestID; # ID of most recent revision
55 var $mRestrictions; # Array of groups allowed to edit this article
56 var $mCascadeRestriction;
57 var $mRestrictionsLoaded; # Boolean for initialisation on demand
58 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
59 var $mDefaultNamespace; # Namespace index when there is no namespace
60 # Zero except in {{transclusion}} tags
61 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
62 /**#@-*/
63
64
65 /**
66 * Constructor
67 * @private
68 */
69 /* private */ function Title() {
70 $this->mInterwiki = $this->mUrlform =
71 $this->mTextform = $this->mDbkeyform = '';
72 $this->mArticleID = -1;
73 $this->mNamespace = NS_MAIN;
74 $this->mRestrictionsLoaded = false;
75 $this->mRestrictions = array();
76 # Dont change the following, NS_MAIN is hardcoded in several place
77 # See bug #696
78 $this->mDefaultNamespace = NS_MAIN;
79 $this->mWatched = NULL;
80 $this->mLatestID = false;
81 }
82
83 /**
84 * Create a new Title from a prefixed DB key
85 * @param string $key The database key, which has underscores
86 * instead of spaces, possibly including namespace and
87 * interwiki prefixes
88 * @return Title the new object, or NULL on an error
89 * @static
90 * @access public
91 */
92 /* static */ function newFromDBkey( $key ) {
93 $t = new Title();
94 $t->mDbkeyform = $key;
95 if( $t->secureAndSplit() )
96 return $t;
97 else
98 return NULL;
99 }
100
101 /**
102 * Create a new Title from text, such as what one would
103 * find in a link. Decodes any HTML entities in the text.
104 *
105 * @param string $text the link text; spaces, prefixes,
106 * and an initial ':' indicating the main namespace
107 * are accepted
108 * @param int $defaultNamespace the namespace to use if
109 * none is specified by a prefix
110 * @return Title the new object, or NULL on an error
111 * @static
112 * @access public
113 */
114 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
115 if( is_object( $text ) ) {
116 throw new MWException( 'Title::newFromText given an object' );
117 }
118
119 /**
120 * Wiki pages often contain multiple links to the same page.
121 * Title normalization and parsing can become expensive on
122 * pages with many links, so we can save a little time by
123 * caching them.
124 *
125 * In theory these are value objects and won't get changed...
126 */
127 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
128 return Title::$titleCache[$text];
129 }
130
131 /**
132 * Convert things like &eacute; &#257; or &#x3017; into real text...
133 */
134 $filteredText = Sanitizer::decodeCharReferences( $text );
135
136 $t = new Title();
137 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
138 $t->mDefaultNamespace = $defaultNamespace;
139
140 static $cachedcount = 0 ;
141 if( $t->secureAndSplit() ) {
142 if( $defaultNamespace == NS_MAIN ) {
143 if( $cachedcount >= MW_TITLECACHE_MAX ) {
144 # Avoid memory leaks on mass operations...
145 Title::$titleCache = array();
146 $cachedcount=0;
147 }
148 $cachedcount++;
149 Title::$titleCache[$text] =& $t;
150 }
151 return $t;
152 } else {
153 $ret = NULL;
154 return $ret;
155 }
156 }
157
158 /**
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
163 * @static
164 * @access public
165 */
166 public static function newFromURL( $url ) {
167 global $wgLegalTitleChars;
168 $t = new Title();
169
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
175 }
176
177 $t->mDbkeyform = str_replace( ' ', '_', $url );
178 if( $t->secureAndSplit() ) {
179 return $t;
180 } else {
181 return NULL;
182 }
183 }
184
185 /**
186 * Create a new Title from an article ID
187 *
188 * @todo This is inefficiently implemented, the page row is requested
189 * but not used for anything else
190 *
191 * @param int $id the page_id corresponding to the Title to create
192 * @return Title the new object, or NULL on an error
193 * @access public
194 * @static
195 */
196 public static function newFromID( $id ) {
197 $fname = 'Title::newFromID';
198 $dbr =& wfGetDB( DB_SLAVE );
199 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
200 array( 'page_id' => $id ), $fname );
201 if ( $row !== false ) {
202 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
203 } else {
204 $title = NULL;
205 }
206 return $title;
207 }
208
209 /**
210 * Make an array of titles from an array of IDs
211 */
212 function newFromIDs( $ids ) {
213 $dbr =& wfGetDB( DB_SLAVE );
214 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
215 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
216
217 $titles = array();
218 while ( $row = $dbr->fetchObject( $res ) ) {
219 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
220 }
221 return $titles;
222 }
223
224 /**
225 * Create a new Title from a namespace index and a DB key.
226 * It's assumed that $ns and $title are *valid*, for instance when
227 * they came directly from the database or a special page name.
228 * For convenience, spaces are converted to underscores so that
229 * eg user_text fields can be used directly.
230 *
231 * @param int $ns the namespace of the article
232 * @param string $title the unprefixed database key form
233 * @return Title the new object
234 * @static
235 * @access public
236 */
237 public static function &makeTitle( $ns, $title ) {
238 $t = new Title();
239 $t->mInterwiki = '';
240 $t->mFragment = '';
241 $t->mNamespace = intval( $ns );
242 $t->mDbkeyform = str_replace( ' ', '_', $title );
243 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
244 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
245 $t->mTextform = str_replace( '_', ' ', $title );
246 return $t;
247 }
248
249 /**
250 * Create a new Title from a namespace index and a DB key.
251 * The parameters will be checked for validity, which is a bit slower
252 * than makeTitle() but safer for user-provided data.
253 *
254 * @param int $ns the namespace of the article
255 * @param string $title the database key form
256 * @return Title the new object, or NULL on an error
257 * @static
258 * @access public
259 */
260 public static function makeTitleSafe( $ns, $title ) {
261 $t = new Title();
262 $t->mDbkeyform = Title::makeName( $ns, $title );
263 if( $t->secureAndSplit() ) {
264 return $t;
265 } else {
266 return NULL;
267 }
268 }
269
270 /**
271 * Create a new Title for the Main Page
272 *
273 * @static
274 * @return Title the new object
275 * @access public
276 */
277 public static function newMainPage() {
278 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
279 }
280
281 /**
282 * Create a new Title for a redirect
283 * @param string $text the redirect title text
284 * @return Title the new object, or NULL if the text is not a
285 * valid redirect
286 */
287 public static function newFromRedirect( $text ) {
288 $mwRedir = MagicWord::get( 'redirect' );
289 $rt = NULL;
290 if ( $mwRedir->matchStart( $text ) ) {
291 $m = array();
292 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
293 # categories are escaped using : for example one can enter:
294 # #REDIRECT [[:Category:Music]]. Need to remove it.
295 if ( substr($m[1],0,1) == ':') {
296 # We don't want to keep the ':'
297 $m[1] = substr( $m[1], 1 );
298 }
299
300 $rt = Title::newFromText( $m[1] );
301 # Disallow redirects to Special:Userlogout
302 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
303 $rt = NULL;
304 }
305 }
306 }
307 return $rt;
308 }
309
310 #----------------------------------------------------------------------------
311 # Static functions
312 #----------------------------------------------------------------------------
313
314 /**
315 * Get the prefixed DB key associated with an ID
316 * @param int $id the page_id of the article
317 * @return Title an object representing the article, or NULL
318 * if no such article was found
319 * @static
320 * @access public
321 */
322 function nameOf( $id ) {
323 $fname = 'Title::nameOf';
324 $dbr =& wfGetDB( DB_SLAVE );
325
326 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
327 if ( $s === false ) { return NULL; }
328
329 $n = Title::makeName( $s->page_namespace, $s->page_title );
330 return $n;
331 }
332
333 /**
334 * Get a regex character class describing the legal characters in a link
335 * @return string the list of characters, not delimited
336 * @static
337 * @access public
338 */
339 public static function legalChars() {
340 global $wgLegalTitleChars;
341 return $wgLegalTitleChars;
342 }
343
344 /**
345 * Get a string representation of a title suitable for
346 * including in a search index
347 *
348 * @param int $ns a namespace index
349 * @param string $title text-form main part
350 * @return string a stripped-down title string ready for the
351 * search index
352 */
353 public static function indexTitle( $ns, $title ) {
354 global $wgContLang;
355
356 $lc = SearchEngine::legalSearchChars() . '&#;';
357 $t = $wgContLang->stripForSearch( $title );
358 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
359 $t = $wgContLang->lc( $t );
360
361 # Handle 's, s'
362 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
363 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
364
365 $t = preg_replace( "/\\s+/", ' ', $t );
366
367 if ( $ns == NS_IMAGE ) {
368 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
369 }
370 return trim( $t );
371 }
372
373 /*
374 * Make a prefixed DB key from a DB key and a namespace index
375 * @param int $ns numerical representation of the namespace
376 * @param string $title the DB key form the title
377 * @return string the prefixed form of the title
378 */
379 public static function makeName( $ns, $title ) {
380 global $wgContLang;
381
382 $n = $wgContLang->getNsText( $ns );
383 return $n == '' ? $title : "$n:$title";
384 }
385
386 /**
387 * Returns the URL associated with an interwiki prefix
388 * @param string $key the interwiki prefix (e.g. "MeatBall")
389 * @return the associated URL, containing "$1", which should be
390 * replaced by an article title
391 * @static (arguably)
392 * @access public
393 */
394 function getInterwikiLink( $key ) {
395 global $wgMemc, $wgInterwikiExpiry;
396 global $wgInterwikiCache, $wgContLang;
397 $fname = 'Title::getInterwikiLink';
398
399 $key = $wgContLang->lc( $key );
400
401 $k = wfMemcKey( 'interwiki', $key );
402 if( array_key_exists( $k, Title::$interwikiCache ) ) {
403 return Title::$interwikiCache[$k]->iw_url;
404 }
405
406 if ($wgInterwikiCache) {
407 return Title::getInterwikiCached( $key );
408 }
409
410 $s = $wgMemc->get( $k );
411 # Ignore old keys with no iw_local
412 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
413 Title::$interwikiCache[$k] = $s;
414 return $s->iw_url;
415 }
416
417 $dbr =& wfGetDB( DB_SLAVE );
418 $res = $dbr->select( 'interwiki',
419 array( 'iw_url', 'iw_local', 'iw_trans' ),
420 array( 'iw_prefix' => $key ), $fname );
421 if( !$res ) {
422 return '';
423 }
424
425 $s = $dbr->fetchObject( $res );
426 if( !$s ) {
427 # Cache non-existence: create a blank object and save it to memcached
428 $s = (object)false;
429 $s->iw_url = '';
430 $s->iw_local = 0;
431 $s->iw_trans = 0;
432 }
433 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
434 Title::$interwikiCache[$k] = $s;
435
436 return $s->iw_url;
437 }
438
439 /**
440 * Fetch interwiki prefix data from local cache in constant database
441 *
442 * More logic is explained in DefaultSettings
443 *
444 * @return string URL of interwiki site
445 * @access public
446 */
447 function getInterwikiCached( $key ) {
448 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
449 static $db, $site;
450
451 if (!$db)
452 $db=dba_open($wgInterwikiCache,'r','cdb');
453 /* Resolve site name */
454 if ($wgInterwikiScopes>=3 and !$site) {
455 $site = dba_fetch('__sites:' . wfWikiID(), $db);
456 if ($site=="")
457 $site = $wgInterwikiFallbackSite;
458 }
459 $value = dba_fetch( wfMemcKey( $key ), $db);
460 if ($value=='' and $wgInterwikiScopes>=3) {
461 /* try site-level */
462 $value = dba_fetch("_{$site}:{$key}", $db);
463 }
464 if ($value=='' and $wgInterwikiScopes>=2) {
465 /* try globals */
466 $value = dba_fetch("__global:{$key}", $db);
467 }
468 if ($value=='undef')
469 $value='';
470 $s = (object)false;
471 $s->iw_url = '';
472 $s->iw_local = 0;
473 $s->iw_trans = 0;
474 if ($value!='') {
475 list($local,$url)=explode(' ',$value,2);
476 $s->iw_url=$url;
477 $s->iw_local=(int)$local;
478 }
479 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
480 return $s->iw_url;
481 }
482 /**
483 * Determine whether the object refers to a page within
484 * this project.
485 *
486 * @return bool TRUE if this is an in-project interwiki link
487 * or a wikilink, FALSE otherwise
488 * @access public
489 */
490 function isLocal() {
491 if ( $this->mInterwiki != '' ) {
492 # Make sure key is loaded into cache
493 $this->getInterwikiLink( $this->mInterwiki );
494 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
495 return (bool)(Title::$interwikiCache[$k]->iw_local);
496 } else {
497 return true;
498 }
499 }
500
501 /**
502 * Determine whether the object refers to a page within
503 * this project and is transcludable.
504 *
505 * @return bool TRUE if this is transcludable
506 * @access public
507 */
508 function isTrans() {
509 if ($this->mInterwiki == '')
510 return false;
511 # Make sure key is loaded into cache
512 $this->getInterwikiLink( $this->mInterwiki );
513 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
514 return (bool)(Title::$interwikiCache[$k]->iw_trans);
515 }
516
517 /**
518 * Update the page_touched field for an array of title objects
519 * @todo Inefficient unless the IDs are already loaded into the
520 * link cache
521 * @param array $titles an array of Title objects to be touched
522 * @param string $timestamp the timestamp to use instead of the
523 * default current time
524 * @static
525 * @access public
526 */
527 function touchArray( $titles, $timestamp = '' ) {
528
529 if ( count( $titles ) == 0 ) {
530 return;
531 }
532 $dbw =& wfGetDB( DB_MASTER );
533 if ( $timestamp == '' ) {
534 $timestamp = $dbw->timestamp();
535 }
536 /*
537 $page = $dbw->tableName( 'page' );
538 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
539 $first = true;
540
541 foreach ( $titles as $title ) {
542 if ( $wgUseFileCache ) {
543 $cm = new HTMLFileCache($title);
544 @unlink($cm->fileCacheName());
545 }
546
547 if ( ! $first ) {
548 $sql .= ',';
549 }
550 $first = false;
551 $sql .= $title->getArticleID();
552 }
553 $sql .= ')';
554 if ( ! $first ) {
555 $dbw->query( $sql, 'Title::touchArray' );
556 }
557 */
558 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
559 // do them in small chunks:
560 $fname = 'Title::touchArray';
561 foreach( $titles as $title ) {
562 $dbw->update( 'page',
563 array( 'page_touched' => $timestamp ),
564 array(
565 'page_namespace' => $title->getNamespace(),
566 'page_title' => $title->getDBkey() ),
567 $fname );
568 }
569 }
570
571 /**
572 * Escape a text fragment, say from a link, for a URL
573 */
574 static function escapeFragmentForURL( $fragment ) {
575 $fragment = str_replace( ' ', '_', $fragment );
576 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
577 $replaceArray = array(
578 '%3A' => ':',
579 '%' => '.'
580 );
581 return strtr( $fragment, $replaceArray );
582 }
583
584 #----------------------------------------------------------------------------
585 # Other stuff
586 #----------------------------------------------------------------------------
587
588 /** Simple accessors */
589 /**
590 * Get the text form (spaces not underscores) of the main part
591 * @return string
592 * @access public
593 */
594 function getText() { return $this->mTextform; }
595 /**
596 * Get the URL-encoded form of the main part
597 * @return string
598 * @access public
599 */
600 function getPartialURL() { return $this->mUrlform; }
601 /**
602 * Get the main part with underscores
603 * @return string
604 * @access public
605 */
606 function getDBkey() { return $this->mDbkeyform; }
607 /**
608 * Get the namespace index, i.e. one of the NS_xxxx constants
609 * @return int
610 * @access public
611 */
612 function getNamespace() { return $this->mNamespace; }
613 /**
614 * Get the namespace text
615 * @return string
616 * @access public
617 */
618 function getNsText() {
619 global $wgContLang, $wgCanonicalNamespaceNames;
620
621 if ( '' != $this->mInterwiki ) {
622 // This probably shouldn't even happen. ohh man, oh yuck.
623 // But for interwiki transclusion it sometimes does.
624 // Shit. Shit shit shit.
625 //
626 // Use the canonical namespaces if possible to try to
627 // resolve a foreign namespace.
628 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
629 return $wgCanonicalNamespaceNames[$this->mNamespace];
630 }
631 }
632 return $wgContLang->getNsText( $this->mNamespace );
633 }
634 /**
635 * Get the namespace text of the subject (rather than talk) page
636 * @return string
637 * @access public
638 */
639 function getSubjectNsText() {
640 global $wgContLang;
641 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
642 }
643
644 /**
645 * Get the namespace text of the talk page
646 * @return string
647 */
648 function getTalkNsText() {
649 global $wgContLang;
650 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
651 }
652
653 /**
654 * Could this title have a corresponding talk page?
655 * @return bool
656 */
657 function canTalk() {
658 return( Namespace::canTalk( $this->mNamespace ) );
659 }
660
661 /**
662 * Get the interwiki prefix (or null string)
663 * @return string
664 * @access public
665 */
666 function getInterwiki() { return $this->mInterwiki; }
667 /**
668 * Get the Title fragment (i.e. the bit after the #) in text form
669 * @return string
670 * @access public
671 */
672 function getFragment() { return $this->mFragment; }
673 /**
674 * Get the fragment in URL form, including the "#" character if there is one
675 *
676 * @return string
677 * @access public
678 */
679 function getFragmentForURL() {
680 if ( $this->mFragment == '' ) {
681 return '';
682 } else {
683 return '#' . Title::escapeFragmentForURL( $this->mFragment );
684 }
685 }
686 /**
687 * Get the default namespace index, for when there is no namespace
688 * @return int
689 * @access public
690 */
691 function getDefaultNamespace() { return $this->mDefaultNamespace; }
692
693 /**
694 * Get title for search index
695 * @return string a stripped-down title string ready for the
696 * search index
697 */
698 function getIndexTitle() {
699 return Title::indexTitle( $this->mNamespace, $this->mTextform );
700 }
701
702 /**
703 * Get the prefixed database key form
704 * @return string the prefixed title, with underscores and
705 * any interwiki and namespace prefixes
706 * @access public
707 */
708 function getPrefixedDBkey() {
709 $s = $this->prefix( $this->mDbkeyform );
710 $s = str_replace( ' ', '_', $s );
711 return $s;
712 }
713
714 /**
715 * Get the prefixed title with spaces.
716 * This is the form usually used for display
717 * @return string the prefixed title, with spaces
718 * @access public
719 */
720 function getPrefixedText() {
721 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
722 $s = $this->prefix( $this->mTextform );
723 $s = str_replace( '_', ' ', $s );
724 $this->mPrefixedText = $s;
725 }
726 return $this->mPrefixedText;
727 }
728
729 /**
730 * Get the prefixed title with spaces, plus any fragment
731 * (part beginning with '#')
732 * @return string the prefixed title, with spaces and
733 * the fragment, including '#'
734 * @access public
735 */
736 function getFullText() {
737 $text = $this->getPrefixedText();
738 if( '' != $this->mFragment ) {
739 $text .= '#' . $this->mFragment;
740 }
741 return $text;
742 }
743
744 /**
745 * Get the base name, i.e. the leftmost parts before the /
746 * @return string Base name
747 */
748 function getBaseText() {
749 global $wgNamespacesWithSubpages;
750 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
751 $parts = explode( '/', $this->getText() );
752 # Don't discard the real title if there's no subpage involved
753 if( count( $parts ) > 1 )
754 unset( $parts[ count( $parts ) - 1 ] );
755 return implode( '/', $parts );
756 } else {
757 return $this->getText();
758 }
759 }
760
761 /**
762 * Get the lowest-level subpage name, i.e. the rightmost part after /
763 * @return string Subpage name
764 */
765 function getSubpageText() {
766 global $wgNamespacesWithSubpages;
767 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
768 $parts = explode( '/', $this->mTextform );
769 return( $parts[ count( $parts ) - 1 ] );
770 } else {
771 return( $this->mTextform );
772 }
773 }
774
775 /**
776 * Get a URL-encoded form of the subpage text
777 * @return string URL-encoded subpage name
778 */
779 function getSubpageUrlForm() {
780 $text = $this->getSubpageText();
781 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
782 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
783 return( $text );
784 }
785
786 /**
787 * Get a URL-encoded title (not an actual URL) including interwiki
788 * @return string the URL-encoded form
789 * @access public
790 */
791 function getPrefixedURL() {
792 $s = $this->prefix( $this->mDbkeyform );
793 $s = str_replace( ' ', '_', $s );
794
795 $s = wfUrlencode ( $s ) ;
796
797 # Cleaning up URL to make it look nice -- is this safe?
798 $s = str_replace( '%28', '(', $s );
799 $s = str_replace( '%29', ')', $s );
800
801 return $s;
802 }
803
804 /**
805 * Get a real URL referring to this title, with interwiki link and
806 * fragment
807 *
808 * @param string $query an optional query string, not used
809 * for interwiki links
810 * @param string $variant language variant of url (for sr, zh..)
811 * @return string the URL
812 * @access public
813 */
814 function getFullURL( $query = '', $variant = false ) {
815 global $wgContLang, $wgServer, $wgRequest;
816
817 if ( '' == $this->mInterwiki ) {
818 $url = $this->getLocalUrl( $query, $variant );
819
820 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
821 // Correct fix would be to move the prepending elsewhere.
822 if ($wgRequest->getVal('action') != 'render') {
823 $url = $wgServer . $url;
824 }
825 } else {
826 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
827
828 $namespace = wfUrlencode( $this->getNsText() );
829 if ( '' != $namespace ) {
830 # Can this actually happen? Interwikis shouldn't be parsed.
831 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
832 $namespace .= ':';
833 }
834 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
835 if( $query != '' ) {
836 if( false === strpos( $url, '?' ) ) {
837 $url .= '?';
838 } else {
839 $url .= '&';
840 }
841 $url .= $query;
842 }
843 }
844
845 # Finally, add the fragment.
846 $url .= $this->getFragmentForURL();
847
848 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
849 return $url;
850 }
851
852 /**
853 * Get a URL with no fragment or server name. If this page is generated
854 * with action=render, $wgServer is prepended.
855 * @param string $query an optional query string; if not specified,
856 * $wgArticlePath will be used.
857 * @param string $variant language variant of url (for sr, zh..)
858 * @return string the URL
859 * @access public
860 */
861 function getLocalURL( $query = '', $variant = false ) {
862 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
863 global $wgVariantArticlePath, $wgContLang, $wgUser;
864
865 // internal links should point to same variant as current page (only anonymous users)
866 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
867 $pref = $wgContLang->getPreferredVariant(false);
868 if($pref != $wgContLang->getCode())
869 $variant = $pref;
870 }
871
872 if ( $this->isExternal() ) {
873 $url = $this->getFullURL();
874 if ( $query ) {
875 // This is currently only used for edit section links in the
876 // context of interwiki transclusion. In theory we should
877 // append the query to the end of any existing query string,
878 // but interwiki transclusion is already broken in that case.
879 $url .= "?$query";
880 }
881 } else {
882 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
883 if ( $query == '' ) {
884 if($variant!=false && $wgContLang->hasVariants()){
885 if($wgVariantArticlePath==false)
886 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
887 else
888 $variantArticlePath = $wgVariantArticlePath;
889
890 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
891 $url = str_replace( '$1', $dbkey, $url );
892
893 }
894 else
895 $url = str_replace( '$1', $dbkey, $wgArticlePath );
896 } else {
897 global $wgActionPaths;
898 $url = false;
899 $matches = array();
900 if( !empty( $wgActionPaths ) &&
901 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
902 {
903 $action = urldecode( $matches[2] );
904 if( isset( $wgActionPaths[$action] ) ) {
905 $query = $matches[1];
906 if( isset( $matches[4] ) ) $query .= $matches[4];
907 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
908 if( $query != '' ) $url .= '?' . $query;
909 }
910 }
911 if ( $url === false ) {
912 if ( $query == '-' ) {
913 $query = '';
914 }
915 $url = "{$wgScript}?title={$dbkey}&{$query}";
916 }
917 }
918
919 // FIXME: this causes breakage in various places when we
920 // actually expected a local URL and end up with dupe prefixes.
921 if ($wgRequest->getVal('action') == 'render') {
922 $url = $wgServer . $url;
923 }
924 }
925 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
926 return $url;
927 }
928
929 /**
930 * Get an HTML-escaped version of the URL form, suitable for
931 * using in a link, without a server name or fragment
932 * @param string $query an optional query string
933 * @return string the URL
934 * @access public
935 */
936 function escapeLocalURL( $query = '' ) {
937 return htmlspecialchars( $this->getLocalURL( $query ) );
938 }
939
940 /**
941 * Get an HTML-escaped version of the URL form, suitable for
942 * using in a link, including the server name and fragment
943 *
944 * @return string the URL
945 * @param string $query an optional query string
946 * @access public
947 */
948 function escapeFullURL( $query = '' ) {
949 return htmlspecialchars( $this->getFullURL( $query ) );
950 }
951
952 /**
953 * Get the URL form for an internal link.
954 * - Used in various Squid-related code, in case we have a different
955 * internal hostname for the server from the exposed one.
956 *
957 * @param string $query an optional query string
958 * @param string $variant language variant of url (for sr, zh..)
959 * @return string the URL
960 * @access public
961 */
962 function getInternalURL( $query = '', $variant = false ) {
963 global $wgInternalServer;
964 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
965 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
966 return $url;
967 }
968
969 /**
970 * Get the edit URL for this Title
971 * @return string the URL, or a null string if this is an
972 * interwiki link
973 * @access public
974 */
975 function getEditURL() {
976 if ( '' != $this->mInterwiki ) { return ''; }
977 $s = $this->getLocalURL( 'action=edit' );
978
979 return $s;
980 }
981
982 /**
983 * Get the HTML-escaped displayable text form.
984 * Used for the title field in <a> tags.
985 * @return string the text, including any prefixes
986 * @access public
987 */
988 function getEscapedText() {
989 return htmlspecialchars( $this->getPrefixedText() );
990 }
991
992 /**
993 * Is this Title interwiki?
994 * @return boolean
995 * @access public
996 */
997 function isExternal() { return ( '' != $this->mInterwiki ); }
998
999 /**
1000 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1001 *
1002 * @param string Action to check (default: edit)
1003 * @return bool
1004 */
1005 function isSemiProtected( $action = 'edit' ) {
1006 if( $this->exists() ) {
1007 $restrictions = $this->getRestrictions( $action );
1008 if( count( $restrictions ) > 0 ) {
1009 foreach( $restrictions as $restriction ) {
1010 if( strtolower( $restriction ) != 'autoconfirmed' )
1011 return false;
1012 }
1013 } else {
1014 # Not protected
1015 return false;
1016 }
1017 return true;
1018 } else {
1019 # If it doesn't exist, it can't be protected
1020 return false;
1021 }
1022 }
1023
1024 /**
1025 * Does the title correspond to a protected article?
1026 * @param string $what the action the page is protected from,
1027 * by default checks move and edit
1028 * @return boolean
1029 * @access public
1030 */
1031 function isProtected( $action = '' ) {
1032 global $wgRestrictionLevels;
1033 if ( NS_SPECIAL == $this->mNamespace ) { return true; }
1034
1035 if( $action == 'edit' || $action == '' ) {
1036 $r = $this->getRestrictions( 'edit' );
1037 foreach( $wgRestrictionLevels as $level ) {
1038 if( in_array( $level, $r ) && $level != '' ) {
1039 return( true );
1040 }
1041 }
1042 }
1043
1044 if( $action == 'move' || $action == '' ) {
1045 $r = $this->getRestrictions( 'move' );
1046 foreach( $wgRestrictionLevels as $level ) {
1047 if( in_array( $level, $r ) && $level != '' ) {
1048 return( true );
1049 }
1050 }
1051 }
1052
1053 return false;
1054 }
1055
1056 /**
1057 * Is $wgUser is watching this page?
1058 * @return boolean
1059 * @access public
1060 */
1061 function userIsWatching() {
1062 global $wgUser;
1063
1064 if ( is_null( $this->mWatched ) ) {
1065 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1066 $this->mWatched = false;
1067 } else {
1068 $this->mWatched = $wgUser->isWatched( $this );
1069 }
1070 }
1071 return $this->mWatched;
1072 }
1073
1074 /**
1075 * Can $wgUser perform $action this page?
1076 * @param string $action action that permission needs to be checked for
1077 * @return boolean
1078 * @private
1079 */
1080 function userCan($action) {
1081 $fname = 'Title::userCan';
1082 wfProfileIn( $fname );
1083
1084 global $wgUser, $wgNamespaceProtection;
1085
1086 $result = null;
1087 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1088 if ( $result !== null ) {
1089 wfProfileOut( $fname );
1090 return $result;
1091 }
1092
1093 if( NS_SPECIAL == $this->mNamespace ) {
1094 wfProfileOut( $fname );
1095 return false;
1096 }
1097 if ( array_key_exists( $this->mNamespace, $wgNamespaceProtection ) ) {
1098 $nsProt = $wgNamespaceProtection[ $this->mNamespace ];
1099 if ( !is_array($nsProt) ) $nsProt = array($nsProt);
1100 foreach( $nsProt as $right ) {
1101 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1102 wfProfileOut( $fname );
1103 return false;
1104 }
1105 }
1106 }
1107
1108 if( $this->mDbkeyform == '_' ) {
1109 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1110 wfProfileOut( $fname );
1111 return false;
1112 }
1113
1114 # protect css/js subpages of user pages
1115 # XXX: this might be better using restrictions
1116 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1117 if( $this->isCssJsSubpage()
1118 && !$wgUser->isAllowed('editinterface')
1119 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
1120 wfProfileOut( $fname );
1121 return false;
1122 }
1123
1124 if ( ( $this->isCascadeProtectedPage() ) ||
1125 ($this->getNamespace() == NS_IMAGE && $this->isCascadeProtectedImage() ) ) {
1126 # We /could/ use the protection level on the source page, but it's fairly ugly
1127 # as we have to establish a precedence hierarchy for pages included by multiple
1128 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1129 # as they could remove the protection anyway.
1130 if ( !$wgUser->isAllowed('protect') ) {
1131 wfProfileOut( $fname );
1132 return false;
1133 }
1134 }
1135
1136 foreach( $this->getRestrictions($action) as $right ) {
1137 // Backwards compatibility, rewrite sysop -> protect
1138 if ( $right == 'sysop' ) {
1139 $right = 'protect';
1140 }
1141 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1142 wfProfileOut( $fname );
1143 return false;
1144 }
1145 }
1146
1147 if( $action == 'move' &&
1148 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1149 wfProfileOut( $fname );
1150 return false;
1151 }
1152
1153 if( $action == 'create' ) {
1154 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1155 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1156 wfProfileOut( $fname );
1157 return false;
1158 }
1159 }
1160
1161 wfProfileOut( $fname );
1162 return true;
1163 }
1164
1165 /**
1166 * Can $wgUser edit this page?
1167 * @return boolean
1168 * @access public
1169 */
1170 function userCanEdit() {
1171 return $this->userCan('edit');
1172 }
1173
1174 /**
1175 * Can $wgUser create this page?
1176 * @return boolean
1177 * @access public
1178 */
1179 function userCanCreate() {
1180 return $this->userCan('create');
1181 }
1182
1183 /**
1184 * Can $wgUser move this page?
1185 * @return boolean
1186 * @access public
1187 */
1188 function userCanMove() {
1189 return $this->userCan('move');
1190 }
1191
1192 /**
1193 * Would anybody with sufficient privileges be able to move this page?
1194 * Some pages just aren't movable.
1195 *
1196 * @return boolean
1197 * @access public
1198 */
1199 function isMovable() {
1200 return Namespace::isMovable( $this->getNamespace() )
1201 && $this->getInterwiki() == '';
1202 }
1203
1204 /**
1205 * Can $wgUser read this page?
1206 * @return boolean
1207 * @access public
1208 */
1209 function userCanRead() {
1210 global $wgUser;
1211
1212 $result = null;
1213 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1214 if ( $result !== null ) {
1215 return $result;
1216 }
1217
1218 if( $wgUser->isAllowed('read') ) {
1219 return true;
1220 } else {
1221 global $wgWhitelistRead;
1222
1223 /**
1224 * Always grant access to the login page.
1225 * Even anons need to be able to log in.
1226 */
1227 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1228 return true;
1229 }
1230
1231 /** some pages are explicitly allowed */
1232 $name = $this->getPrefixedText();
1233 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1234 return true;
1235 }
1236
1237 # Compatibility with old settings
1238 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1239 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1240 return true;
1241 }
1242 }
1243 }
1244 return false;
1245 }
1246
1247 /**
1248 * Is this a talk page of some sort?
1249 * @return bool
1250 * @access public
1251 */
1252 function isTalkPage() {
1253 return Namespace::isTalk( $this->getNamespace() );
1254 }
1255
1256 /**
1257 * Is this a subpage?
1258 * @return bool
1259 * @access public
1260 */
1261 function isSubpage() {
1262 global $wgNamespacesWithSubpages;
1263
1264 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1265 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1266 } else {
1267 return false;
1268 }
1269 }
1270
1271 /**
1272 * Is this a .css or .js subpage of a user page?
1273 * @return bool
1274 * @access public
1275 */
1276 function isCssJsSubpage() {
1277 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform ) );
1278 }
1279 /**
1280 * Is this a *valid* .css or .js subpage of a user page?
1281 * Check that the corresponding skin exists
1282 */
1283 function isValidCssJsSubpage() {
1284 if ( $this->isCssJsSubpage() ) {
1285 $skinNames = Skin::getSkinNames();
1286 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1287 } else {
1288 return false;
1289 }
1290 }
1291 /**
1292 * Trim down a .css or .js subpage title to get the corresponding skin name
1293 */
1294 function getSkinFromCssJsSubpage() {
1295 $subpage = explode( '/', $this->mTextform );
1296 $subpage = $subpage[ count( $subpage ) - 1 ];
1297 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1298 }
1299 /**
1300 * Is this a .css subpage of a user page?
1301 * @return bool
1302 * @access public
1303 */
1304 function isCssSubpage() {
1305 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1306 }
1307 /**
1308 * Is this a .js subpage of a user page?
1309 * @return bool
1310 * @access public
1311 */
1312 function isJsSubpage() {
1313 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1314 }
1315 /**
1316 * Protect css/js subpages of user pages: can $wgUser edit
1317 * this page?
1318 *
1319 * @return boolean
1320 * @todo XXX: this might be better using restrictions
1321 * @access public
1322 */
1323 function userCanEditCssJsSubpage() {
1324 global $wgUser;
1325 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1326 }
1327
1328 /**
1329 * Cascading protects: Check if the current image is protected due to a cascading restriction
1330 *
1331 * @return bool If the current page is protected due to a cascading restriction.
1332 * @access public
1333 */
1334 function isCascadeProtectedImage() {
1335 global $wgEnableCascadingProtection;
1336 if (!$wgEnableCascadingProtection)
1337 return false;
1338
1339 wfProfileIn(__METHOD__);
1340
1341 $dbr =& wfGetDb( DB_SLAVE );
1342
1343 $cols = array( 'il_to' );
1344 $tables = array ('imagelinks', 'page_restrictions');
1345 $where_clauses = array( 'il_to' => $this->getDBkey(), 'il_from=pr_page', 'pr_cascade' => 1 );
1346
1347 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__);
1348
1349 if ($dbr->numRows($res)) {
1350 wfProfileOut(__METHOD__);
1351 return true;
1352 } else {
1353 wfProfileOut(__METHOD__);
1354 return false;
1355 }
1356 }
1357
1358 /**
1359 * Cascading protects: Check if the current page is protected due to a cascading restriction.
1360 *
1361 * @return bool if the current page is protected due to a cascading restriction
1362 * @access public
1363 */
1364 function isCascadeProtectedPage() {
1365 global $wgEnableCascadingProtection;
1366 if (!$wgEnableCascadingProtection)
1367 return false;
1368
1369 wfProfileIn(__METHOD__);
1370
1371 $dbr =& wfGetDb( DB_SLAVE );
1372
1373 $cols = array( 'tl_namespace', 'tl_title'/*, 'pr_level', 'pr_type'*/ );
1374 $tables = array ('templatelinks', 'page_restrictions');
1375 $where_clauses = array( 'tl_namespace' => $this->getNamespace(), 'tl_title' => $this->getDBkey(), 'tl_from=pr_page', 'pr_cascade' => 1 );
1376
1377 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__);
1378
1379 if ($dbr->numRows($res)) {
1380 wfProfileOut(__METHOD__);
1381 return true;
1382 } else {
1383 wfProfileOut(__METHOD__);
1384 return false;
1385 }
1386 }
1387
1388 function areRestrictionsCascading() {
1389 if (!$this->mRestrictionsLoaded) {
1390 $this->loadRestrictions();
1391 }
1392
1393 return $this->mCascadeRestriction;
1394 }
1395
1396 /**
1397 * Loads a string into mRestrictions array
1398 * @param resource $res restrictions as an SQL result.
1399 * @access public
1400 */
1401 function loadRestrictionsFromRow( $res ) {
1402 $dbr =& wfGetDb( DB_SLAVE );
1403
1404 if (!$dbr->numRows( $res ) ) {
1405 # No restrictions
1406 $this->mRestrictionsLoaded = true;
1407 return;
1408 }
1409
1410 $this->mRestrictions['edit'] = array();
1411 $this->mRestrictions['move'] = array();
1412
1413 while ($row = $dbr->fetchObject( $res ) ) {
1414 # Cycle through all the restrictions.
1415
1416 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1417
1418 $this->mCascadeRestriction |= $row->pr_cascade;
1419 }
1420
1421 $this->mRestrictionsLoaded = true;
1422 }
1423
1424 function loadRestrictions() {
1425 if( !$this->mRestrictionsLoaded ) {
1426 $dbr =& wfGetDB( DB_SLAVE );
1427
1428 $res = $dbr->select( 'page_restrictions', '*',
1429 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1430 $this->loadRestrictionsFromRow( $res );
1431 }
1432 }
1433
1434 /**
1435 * Accessor/initialisation for mRestrictions
1436 *
1437 * @access public
1438 * @param string $action action that permission needs to be checked for
1439 * @return array the array of groups allowed to edit this article
1440 */
1441 function getRestrictions( $action ) {
1442 if( $this->exists() ) {
1443 if( !$this->mRestrictionsLoaded ) {
1444 $this->loadRestrictions();
1445 }
1446 return isset( $this->mRestrictions[$action] )
1447 ? $this->mRestrictions[$action]
1448 : array();
1449 } else {
1450 return array();
1451 }
1452 }
1453
1454 /**
1455 * Is there a version of this page in the deletion archive?
1456 * @return int the number of archived revisions
1457 * @access public
1458 */
1459 function isDeleted() {
1460 $fname = 'Title::isDeleted';
1461 if ( $this->getNamespace() < 0 ) {
1462 $n = 0;
1463 } else {
1464 $dbr =& wfGetDB( DB_SLAVE );
1465 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1466 'ar_title' => $this->getDBkey() ), $fname );
1467 if( $this->getNamespace() == NS_IMAGE ) {
1468 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1469 array( 'fa_name' => $this->getDBkey() ), $fname );
1470 }
1471 }
1472 return (int)$n;
1473 }
1474
1475 /**
1476 * Get the article ID for this Title from the link cache,
1477 * adding it if necessary
1478 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1479 * for update
1480 * @return int the ID
1481 */
1482 public function getArticleID( $flags = 0 ) {
1483 $linkCache =& LinkCache::singleton();
1484 if ( $flags & GAID_FOR_UPDATE ) {
1485 $oldUpdate = $linkCache->forUpdate( true );
1486 $this->mArticleID = $linkCache->addLinkObj( $this );
1487 $linkCache->forUpdate( $oldUpdate );
1488 } else {
1489 if ( -1 == $this->mArticleID ) {
1490 $this->mArticleID = $linkCache->addLinkObj( $this );
1491 }
1492 }
1493 return $this->mArticleID;
1494 }
1495
1496 function getLatestRevID() {
1497 if ($this->mLatestID !== false)
1498 return $this->mLatestID;
1499
1500 $db =& wfGetDB(DB_SLAVE);
1501 return $this->mLatestID = $db->selectField( 'revision',
1502 "max(rev_id)",
1503 array('rev_page' => $this->getArticleID()),
1504 'Title::getLatestRevID' );
1505 }
1506
1507 /**
1508 * This clears some fields in this object, and clears any associated
1509 * keys in the "bad links" section of the link cache.
1510 *
1511 * - This is called from Article::insertNewArticle() to allow
1512 * loading of the new page_id. It's also called from
1513 * Article::doDeleteArticle()
1514 *
1515 * @param int $newid the new Article ID
1516 * @access public
1517 */
1518 function resetArticleID( $newid ) {
1519 $linkCache =& LinkCache::singleton();
1520 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1521
1522 if ( 0 == $newid ) { $this->mArticleID = -1; }
1523 else { $this->mArticleID = $newid; }
1524 $this->mRestrictionsLoaded = false;
1525 $this->mRestrictions = array();
1526 }
1527
1528 /**
1529 * Updates page_touched for this page; called from LinksUpdate.php
1530 * @return bool true if the update succeded
1531 * @access public
1532 */
1533 function invalidateCache() {
1534 global $wgUseFileCache;
1535
1536 if ( wfReadOnly() ) {
1537 return;
1538 }
1539
1540 $dbw =& wfGetDB( DB_MASTER );
1541 $success = $dbw->update( 'page',
1542 array( /* SET */
1543 'page_touched' => $dbw->timestamp()
1544 ), array( /* WHERE */
1545 'page_namespace' => $this->getNamespace() ,
1546 'page_title' => $this->getDBkey()
1547 ), 'Title::invalidateCache'
1548 );
1549
1550 if ($wgUseFileCache) {
1551 $cache = new HTMLFileCache($this);
1552 @unlink($cache->fileCacheName());
1553 }
1554
1555 return $success;
1556 }
1557
1558 /**
1559 * Prefix some arbitrary text with the namespace or interwiki prefix
1560 * of this object
1561 *
1562 * @param string $name the text
1563 * @return string the prefixed text
1564 * @private
1565 */
1566 /* private */ function prefix( $name ) {
1567 $p = '';
1568 if ( '' != $this->mInterwiki ) {
1569 $p = $this->mInterwiki . ':';
1570 }
1571 if ( 0 != $this->mNamespace ) {
1572 $p .= $this->getNsText() . ':';
1573 }
1574 return $p . $name;
1575 }
1576
1577 /**
1578 * Secure and split - main initialisation function for this object
1579 *
1580 * Assumes that mDbkeyform has been set, and is urldecoded
1581 * and uses underscores, but not otherwise munged. This function
1582 * removes illegal characters, splits off the interwiki and
1583 * namespace prefixes, sets the other forms, and canonicalizes
1584 * everything.
1585 * @return bool true on success
1586 * @private
1587 */
1588 /* private */ function secureAndSplit() {
1589 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1590
1591 # Initialisation
1592 static $rxTc = false;
1593 if( !$rxTc ) {
1594 # % is needed as well
1595 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1596 }
1597
1598 $this->mInterwiki = $this->mFragment = '';
1599 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1600
1601 $dbkey = $this->mDbkeyform;
1602
1603 # Strip Unicode bidi override characters.
1604 # Sometimes they slip into cut-n-pasted page titles, where the
1605 # override chars get included in list displays.
1606 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1607 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1608
1609 # Clean up whitespace
1610 #
1611 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1612 $dbkey = trim( $dbkey, '_' );
1613
1614 if ( '' == $dbkey ) {
1615 return false;
1616 }
1617
1618 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1619 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1620 return false;
1621 }
1622
1623 $this->mDbkeyform = $dbkey;
1624
1625 # Initial colon indicates main namespace rather than specified default
1626 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1627 if ( ':' == $dbkey{0} ) {
1628 $this->mNamespace = NS_MAIN;
1629 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1630 }
1631
1632 # Namespace or interwiki prefix
1633 $firstPass = true;
1634 do {
1635 $m = array();
1636 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1637 $p = $m[1];
1638 $lowerNs = $wgContLang->lc( $p );
1639 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1640 # Canonical namespace
1641 $dbkey = $m[2];
1642 $this->mNamespace = $ns;
1643 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1644 # Ordinary namespace
1645 $dbkey = $m[2];
1646 $this->mNamespace = $ns;
1647 } elseif( $this->getInterwikiLink( $p ) ) {
1648 if( !$firstPass ) {
1649 # Can't make a local interwiki link to an interwiki link.
1650 # That's just crazy!
1651 return false;
1652 }
1653
1654 # Interwiki link
1655 $dbkey = $m[2];
1656 $this->mInterwiki = $wgContLang->lc( $p );
1657
1658 # Redundant interwiki prefix to the local wiki
1659 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1660 if( $dbkey == '' ) {
1661 # Can't have an empty self-link
1662 return false;
1663 }
1664 $this->mInterwiki = '';
1665 $firstPass = false;
1666 # Do another namespace split...
1667 continue;
1668 }
1669
1670 # If there's an initial colon after the interwiki, that also
1671 # resets the default namespace
1672 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1673 $this->mNamespace = NS_MAIN;
1674 $dbkey = substr( $dbkey, 1 );
1675 }
1676 }
1677 # If there's no recognized interwiki or namespace,
1678 # then let the colon expression be part of the title.
1679 }
1680 break;
1681 } while( true );
1682
1683 # We already know that some pages won't be in the database!
1684 #
1685 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1686 $this->mArticleID = 0;
1687 }
1688 $fragment = strstr( $dbkey, '#' );
1689 if ( false !== $fragment ) {
1690 $this->setFragment( $fragment );
1691 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1692 # remove whitespace again: prevents "Foo_bar_#"
1693 # becoming "Foo_bar_"
1694 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1695 }
1696
1697 # Reject illegal characters.
1698 #
1699 if( preg_match( $rxTc, $dbkey ) ) {
1700 return false;
1701 }
1702
1703 /**
1704 * Pages with "/./" or "/../" appearing in the URLs will
1705 * often be unreachable due to the way web browsers deal
1706 * with 'relative' URLs. Forbid them explicitly.
1707 */
1708 if ( strpos( $dbkey, '.' ) !== false &&
1709 ( $dbkey === '.' || $dbkey === '..' ||
1710 strpos( $dbkey, './' ) === 0 ||
1711 strpos( $dbkey, '../' ) === 0 ||
1712 strpos( $dbkey, '/./' ) !== false ||
1713 strpos( $dbkey, '/../' ) !== false ) )
1714 {
1715 return false;
1716 }
1717
1718 /**
1719 * Limit the size of titles to 255 bytes.
1720 * This is typically the size of the underlying database field.
1721 * We make an exception for special pages, which don't need to be stored
1722 * in the database, and may edge over 255 bytes due to subpage syntax
1723 * for long titles, e.g. [[Special:Block/Long name]]
1724 */
1725 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1726 strlen( $dbkey ) > 512 )
1727 {
1728 return false;
1729 }
1730
1731 /**
1732 * Normally, all wiki links are forced to have
1733 * an initial capital letter so [[foo]] and [[Foo]]
1734 * point to the same place.
1735 *
1736 * Don't force it for interwikis, since the other
1737 * site might be case-sensitive.
1738 */
1739 if( $wgCapitalLinks && $this->mInterwiki == '') {
1740 $dbkey = $wgContLang->ucfirst( $dbkey );
1741 }
1742
1743 /**
1744 * Can't make a link to a namespace alone...
1745 * "empty" local links can only be self-links
1746 * with a fragment identifier.
1747 */
1748 if( $dbkey == '' &&
1749 $this->mInterwiki == '' &&
1750 $this->mNamespace != NS_MAIN ) {
1751 return false;
1752 }
1753
1754 // Any remaining initial :s are illegal.
1755 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1756 return false;
1757 }
1758
1759 # Fill fields
1760 $this->mDbkeyform = $dbkey;
1761 $this->mUrlform = wfUrlencode( $dbkey );
1762
1763 $this->mTextform = str_replace( '_', ' ', $dbkey );
1764
1765 return true;
1766 }
1767
1768 /**
1769 * Set the fragment for this title
1770 * This is kind of bad, since except for this rarely-used function, Title objects
1771 * are immutable. The reason this is here is because it's better than setting the
1772 * members directly, which is what Linker::formatComment was doing previously.
1773 *
1774 * @param string $fragment text
1775 * @access kind of public
1776 */
1777 function setFragment( $fragment ) {
1778 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1779 }
1780
1781 /**
1782 * Get a Title object associated with the talk page of this article
1783 * @return Title the object for the talk page
1784 * @access public
1785 */
1786 function getTalkPage() {
1787 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1788 }
1789
1790 /**
1791 * Get a title object associated with the subject page of this
1792 * talk page
1793 *
1794 * @return Title the object for the subject page
1795 * @access public
1796 */
1797 function getSubjectPage() {
1798 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1799 }
1800
1801 /**
1802 * Get an array of Title objects linking to this Title
1803 * Also stores the IDs in the link cache.
1804 *
1805 * WARNING: do not use this function on arbitrary user-supplied titles!
1806 * On heavily-used templates it will max out the memory.
1807 *
1808 * @param string $options may be FOR UPDATE
1809 * @return array the Title objects linking here
1810 * @access public
1811 */
1812 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1813 $linkCache =& LinkCache::singleton();
1814
1815 if ( $options ) {
1816 $db =& wfGetDB( DB_MASTER );
1817 } else {
1818 $db =& wfGetDB( DB_SLAVE );
1819 }
1820
1821 $res = $db->select( array( 'page', $table ),
1822 array( 'page_namespace', 'page_title', 'page_id' ),
1823 array(
1824 "{$prefix}_from=page_id",
1825 "{$prefix}_namespace" => $this->getNamespace(),
1826 "{$prefix}_title" => $this->getDbKey() ),
1827 'Title::getLinksTo',
1828 $options );
1829
1830 $retVal = array();
1831 if ( $db->numRows( $res ) ) {
1832 while ( $row = $db->fetchObject( $res ) ) {
1833 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1834 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1835 $retVal[] = $titleObj;
1836 }
1837 }
1838 }
1839 $db->freeResult( $res );
1840 return $retVal;
1841 }
1842
1843 /**
1844 * Get an array of Title objects using this Title as a template
1845 * Also stores the IDs in the link cache.
1846 *
1847 * WARNING: do not use this function on arbitrary user-supplied titles!
1848 * On heavily-used templates it will max out the memory.
1849 *
1850 * @param string $options may be FOR UPDATE
1851 * @return array the Title objects linking here
1852 * @access public
1853 */
1854 function getTemplateLinksTo( $options = '' ) {
1855 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1856 }
1857
1858 /**
1859 * Get an array of Title objects referring to non-existent articles linked from this page
1860 *
1861 * @param string $options may be FOR UPDATE
1862 * @return array the Title objects
1863 * @access public
1864 */
1865 function getBrokenLinksFrom( $options = '' ) {
1866 if ( $options ) {
1867 $db =& wfGetDB( DB_MASTER );
1868 } else {
1869 $db =& wfGetDB( DB_SLAVE );
1870 }
1871
1872 $res = $db->safeQuery(
1873 "SELECT pl_namespace, pl_title
1874 FROM !
1875 LEFT JOIN !
1876 ON pl_namespace=page_namespace
1877 AND pl_title=page_title
1878 WHERE pl_from=?
1879 AND page_namespace IS NULL
1880 !",
1881 $db->tableName( 'pagelinks' ),
1882 $db->tableName( 'page' ),
1883 $this->getArticleId(),
1884 $options );
1885
1886 $retVal = array();
1887 if ( $db->numRows( $res ) ) {
1888 while ( $row = $db->fetchObject( $res ) ) {
1889 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1890 }
1891 }
1892 $db->freeResult( $res );
1893 return $retVal;
1894 }
1895
1896
1897 /**
1898 * Get a list of URLs to purge from the Squid cache when this
1899 * page changes
1900 *
1901 * @return array the URLs
1902 * @access public
1903 */
1904 function getSquidURLs() {
1905 global $wgContLang;
1906
1907 $urls = array(
1908 $this->getInternalURL(),
1909 $this->getInternalURL( 'action=history' )
1910 );
1911
1912 // purge variant urls as well
1913 if($wgContLang->hasVariants()){
1914 $variants = $wgContLang->getVariants();
1915 foreach($variants as $vCode){
1916 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1917 $urls[] = $this->getInternalURL('',$vCode);
1918 }
1919 }
1920
1921 return $urls;
1922 }
1923
1924 function purgeSquid() {
1925 global $wgUseSquid;
1926 if ( $wgUseSquid ) {
1927 $urls = $this->getSquidURLs();
1928 $u = new SquidUpdate( $urls );
1929 $u->doUpdate();
1930 }
1931 }
1932
1933 /**
1934 * Move this page without authentication
1935 * @param Title &$nt the new page Title
1936 * @access public
1937 */
1938 function moveNoAuth( &$nt ) {
1939 return $this->moveTo( $nt, false );
1940 }
1941
1942 /**
1943 * Check whether a given move operation would be valid.
1944 * Returns true if ok, or a message key string for an error message
1945 * if invalid. (Scarrrrry ugly interface this.)
1946 * @param Title &$nt the new title
1947 * @param bool $auth indicates whether $wgUser's permissions
1948 * should be checked
1949 * @return mixed true on success, message name on failure
1950 * @access public
1951 */
1952 function isValidMoveOperation( &$nt, $auth = true ) {
1953 if( !$this or !$nt ) {
1954 return 'badtitletext';
1955 }
1956 if( $this->equals( $nt ) ) {
1957 return 'selfmove';
1958 }
1959 if( !$this->isMovable() || !$nt->isMovable() ) {
1960 return 'immobile_namespace';
1961 }
1962
1963 $oldid = $this->getArticleID();
1964 $newid = $nt->getArticleID();
1965
1966 if ( strlen( $nt->getDBkey() ) < 1 ) {
1967 return 'articleexists';
1968 }
1969 if ( ( '' == $this->getDBkey() ) ||
1970 ( !$oldid ) ||
1971 ( '' == $nt->getDBkey() ) ) {
1972 return 'badarticleerror';
1973 }
1974
1975 if ( $auth && (
1976 !$this->userCanEdit() || !$nt->userCanEdit() ||
1977 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1978 return 'protectedpage';
1979 }
1980
1981 # The move is allowed only if (1) the target doesn't exist, or
1982 # (2) the target is a redirect to the source, and has no history
1983 # (so we can undo bad moves right after they're done).
1984
1985 if ( 0 != $newid ) { # Target exists; check for validity
1986 if ( ! $this->isValidMoveTarget( $nt ) ) {
1987 return 'articleexists';
1988 }
1989 }
1990 return true;
1991 }
1992
1993 /**
1994 * Move a title to a new location
1995 * @param Title &$nt the new title
1996 * @param bool $auth indicates whether $wgUser's permissions
1997 * should be checked
1998 * @return mixed true on success, message name on failure
1999 * @access public
2000 */
2001 function moveTo( &$nt, $auth = true, $reason = '' ) {
2002 $err = $this->isValidMoveOperation( $nt, $auth );
2003 if( is_string( $err ) ) {
2004 return $err;
2005 }
2006
2007 $pageid = $this->getArticleID();
2008 if( $nt->exists() ) {
2009 $this->moveOverExistingRedirect( $nt, $reason );
2010 $pageCountChange = 0;
2011 } else { # Target didn't exist, do normal move.
2012 $this->moveToNewTitle( $nt, $reason );
2013 $pageCountChange = 1;
2014 }
2015 $redirid = $this->getArticleID();
2016
2017 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2018 $dbw =& wfGetDB( DB_MASTER );
2019 $categorylinks = $dbw->tableName( 'categorylinks' );
2020 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2021 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2022 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2023 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2024
2025 # Update watchlists
2026
2027 $oldnamespace = $this->getNamespace() & ~1;
2028 $newnamespace = $nt->getNamespace() & ~1;
2029 $oldtitle = $this->getDBkey();
2030 $newtitle = $nt->getDBkey();
2031
2032 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2033 WatchedItem::duplicateEntries( $this, $nt );
2034 }
2035
2036 # Update search engine
2037 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2038 $u->doUpdate();
2039 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2040 $u->doUpdate();
2041
2042 # Update site_stats
2043 if( $this->isContentPage() && !$nt->isContentPage() ) {
2044 # No longer a content page
2045 # Not viewed, edited, removing
2046 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2047 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2048 # Now a content page
2049 # Not viewed, edited, adding
2050 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2051 } elseif( $pageCountChange ) {
2052 # Redirect added
2053 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2054 } else {
2055 # Nothing special
2056 $u = false;
2057 }
2058 if( $u )
2059 $u->doUpdate();
2060
2061 global $wgUser;
2062 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2063 return true;
2064 }
2065
2066 /**
2067 * Move page to a title which is at present a redirect to the
2068 * source page
2069 *
2070 * @param Title &$nt the page to move to, which should currently
2071 * be a redirect
2072 * @private
2073 */
2074 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2075 global $wgUseSquid;
2076 $fname = 'Title::moveOverExistingRedirect';
2077 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2078
2079 if ( $reason ) {
2080 $comment .= ": $reason";
2081 }
2082
2083 $now = wfTimestampNow();
2084 $newid = $nt->getArticleID();
2085 $oldid = $this->getArticleID();
2086 $dbw =& wfGetDB( DB_MASTER );
2087 $linkCache =& LinkCache::singleton();
2088
2089 # Delete the old redirect. We don't save it to history since
2090 # by definition if we've got here it's rather uninteresting.
2091 # We have to remove it so that the next step doesn't trigger
2092 # a conflict on the unique namespace+title index...
2093 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2094
2095 # Save a null revision in the page's history notifying of the move
2096 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2097 $nullRevId = $nullRevision->insertOn( $dbw );
2098
2099 # Change the name of the target page:
2100 $dbw->update( 'page',
2101 /* SET */ array(
2102 'page_touched' => $dbw->timestamp($now),
2103 'page_namespace' => $nt->getNamespace(),
2104 'page_title' => $nt->getDBkey(),
2105 'page_latest' => $nullRevId,
2106 ),
2107 /* WHERE */ array( 'page_id' => $oldid ),
2108 $fname
2109 );
2110 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2111
2112 # Recreate the redirect, this time in the other direction.
2113 $mwRedir = MagicWord::get( 'redirect' );
2114 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2115 $redirectArticle = new Article( $this );
2116 $newid = $redirectArticle->insertOn( $dbw );
2117 $redirectRevision = new Revision( array(
2118 'page' => $newid,
2119 'comment' => $comment,
2120 'text' => $redirectText ) );
2121 $redirectRevision->insertOn( $dbw );
2122 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2123 $linkCache->clearLink( $this->getPrefixedDBkey() );
2124
2125 # Log the move
2126 $log = new LogPage( 'move' );
2127 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2128
2129 # Now, we record the link from the redirect to the new title.
2130 # It should have no other outgoing links...
2131 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2132 $dbw->insert( 'pagelinks',
2133 array(
2134 'pl_from' => $newid,
2135 'pl_namespace' => $nt->getNamespace(),
2136 'pl_title' => $nt->getDbKey() ),
2137 $fname );
2138
2139 # Purge squid
2140 if ( $wgUseSquid ) {
2141 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2142 $u = new SquidUpdate( $urls );
2143 $u->doUpdate();
2144 }
2145 }
2146
2147 /**
2148 * Move page to non-existing title.
2149 * @param Title &$nt the new Title
2150 * @private
2151 */
2152 function moveToNewTitle( &$nt, $reason = '' ) {
2153 global $wgUseSquid;
2154 $fname = 'MovePageForm::moveToNewTitle';
2155 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2156 if ( $reason ) {
2157 $comment .= ": $reason";
2158 }
2159
2160 $newid = $nt->getArticleID();
2161 $oldid = $this->getArticleID();
2162 $dbw =& wfGetDB( DB_MASTER );
2163 $now = $dbw->timestamp();
2164 $linkCache =& LinkCache::singleton();
2165
2166 # Save a null revision in the page's history notifying of the move
2167 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2168 $nullRevId = $nullRevision->insertOn( $dbw );
2169
2170 # Rename cur entry
2171 $dbw->update( 'page',
2172 /* SET */ array(
2173 'page_touched' => $now,
2174 'page_namespace' => $nt->getNamespace(),
2175 'page_title' => $nt->getDBkey(),
2176 'page_latest' => $nullRevId,
2177 ),
2178 /* WHERE */ array( 'page_id' => $oldid ),
2179 $fname
2180 );
2181
2182 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2183
2184 # Insert redirect
2185 $mwRedir = MagicWord::get( 'redirect' );
2186 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2187 $redirectArticle = new Article( $this );
2188 $newid = $redirectArticle->insertOn( $dbw );
2189 $redirectRevision = new Revision( array(
2190 'page' => $newid,
2191 'comment' => $comment,
2192 'text' => $redirectText ) );
2193 $redirectRevision->insertOn( $dbw );
2194 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2195 $linkCache->clearLink( $this->getPrefixedDBkey() );
2196
2197 # Log the move
2198 $log = new LogPage( 'move' );
2199 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2200
2201 # Purge caches as per article creation
2202 Article::onArticleCreate( $nt );
2203
2204 # Record the just-created redirect's linking to the page
2205 $dbw->insert( 'pagelinks',
2206 array(
2207 'pl_from' => $newid,
2208 'pl_namespace' => $nt->getNamespace(),
2209 'pl_title' => $nt->getDBkey() ),
2210 $fname );
2211
2212 # Purge old title from squid
2213 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2214 $this->purgeSquid();
2215 }
2216
2217 /**
2218 * Checks if $this can be moved to a given Title
2219 * - Selects for update, so don't call it unless you mean business
2220 *
2221 * @param Title &$nt the new title to check
2222 * @access public
2223 */
2224 function isValidMoveTarget( $nt ) {
2225
2226 $fname = 'Title::isValidMoveTarget';
2227 $dbw =& wfGetDB( DB_MASTER );
2228
2229 # Is it a redirect?
2230 $id = $nt->getArticleID();
2231 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2232 array( 'page_is_redirect','old_text','old_flags' ),
2233 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2234 $fname, 'FOR UPDATE' );
2235
2236 if ( !$obj || 0 == $obj->page_is_redirect ) {
2237 # Not a redirect
2238 wfDebug( __METHOD__ . ": not a redirect\n" );
2239 return false;
2240 }
2241 $text = Revision::getRevisionText( $obj );
2242
2243 # Does the redirect point to the source?
2244 # Or is it a broken self-redirect, usually caused by namespace collisions?
2245 $m = array();
2246 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2247 $redirTitle = Title::newFromText( $m[1] );
2248 if( !is_object( $redirTitle ) ||
2249 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2250 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2251 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2252 return false;
2253 }
2254 } else {
2255 # Fail safe
2256 wfDebug( __METHOD__ . ": failsafe\n" );
2257 return false;
2258 }
2259
2260 # Does the article have a history?
2261 $row = $dbw->selectRow( array( 'page', 'revision'),
2262 array( 'rev_id' ),
2263 array( 'page_namespace' => $nt->getNamespace(),
2264 'page_title' => $nt->getDBkey(),
2265 'page_id=rev_page AND page_latest != rev_id'
2266 ), $fname, 'FOR UPDATE'
2267 );
2268
2269 # Return true if there was no history
2270 return $row === false;
2271 }
2272
2273 /**
2274 * Create a redirect; fails if the title already exists; does
2275 * not notify RC
2276 *
2277 * @param Title $dest the destination of the redirect
2278 * @param string $comment the comment string describing the move
2279 * @return bool true on success
2280 * @access public
2281 */
2282 function createRedirect( $dest, $comment ) {
2283 if ( $this->getArticleID() ) {
2284 return false;
2285 }
2286
2287 $fname = 'Title::createRedirect';
2288 $dbw =& wfGetDB( DB_MASTER );
2289
2290 $article = new Article( $this );
2291 $newid = $article->insertOn( $dbw );
2292 $revision = new Revision( array(
2293 'page' => $newid,
2294 'comment' => $comment,
2295 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2296 ) );
2297 $revision->insertOn( $dbw );
2298 $article->updateRevisionOn( $dbw, $revision, 0 );
2299
2300 # Link table
2301 $dbw->insert( 'pagelinks',
2302 array(
2303 'pl_from' => $newid,
2304 'pl_namespace' => $dest->getNamespace(),
2305 'pl_title' => $dest->getDbKey()
2306 ), $fname
2307 );
2308
2309 Article::onArticleCreate( $this );
2310 return true;
2311 }
2312
2313 /**
2314 * Get categories to which this Title belongs and return an array of
2315 * categories' names.
2316 *
2317 * @return array an array of parents in the form:
2318 * $parent => $currentarticle
2319 * @access public
2320 */
2321 function getParentCategories() {
2322 global $wgContLang;
2323
2324 $titlekey = $this->getArticleId();
2325 $dbr =& wfGetDB( DB_SLAVE );
2326 $categorylinks = $dbr->tableName( 'categorylinks' );
2327
2328 # NEW SQL
2329 $sql = "SELECT * FROM $categorylinks"
2330 ." WHERE cl_from='$titlekey'"
2331 ." AND cl_from <> '0'"
2332 ." ORDER BY cl_sortkey";
2333
2334 $res = $dbr->query ( $sql ) ;
2335
2336 if($dbr->numRows($res) > 0) {
2337 while ( $x = $dbr->fetchObject ( $res ) )
2338 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2339 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2340 $dbr->freeResult ( $res ) ;
2341 } else {
2342 $data = '';
2343 }
2344 return $data;
2345 }
2346
2347 /**
2348 * Get a tree of parent categories
2349 * @param array $children an array with the children in the keys, to check for circular refs
2350 * @return array
2351 * @access public
2352 */
2353 function getParentCategoryTree( $children = array() ) {
2354 $parents = $this->getParentCategories();
2355
2356 if($parents != '') {
2357 foreach($parents as $parent => $current) {
2358 if ( array_key_exists( $parent, $children ) ) {
2359 # Circular reference
2360 $stack[$parent] = array();
2361 } else {
2362 $nt = Title::newFromText($parent);
2363 if ( $nt ) {
2364 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2365 }
2366 }
2367 }
2368 return $stack;
2369 } else {
2370 return array();
2371 }
2372 }
2373
2374
2375 /**
2376 * Get an associative array for selecting this title from
2377 * the "page" table
2378 *
2379 * @return array
2380 * @access public
2381 */
2382 function pageCond() {
2383 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2384 }
2385
2386 /**
2387 * Get the revision ID of the previous revision
2388 *
2389 * @param integer $revision Revision ID. Get the revision that was before this one.
2390 * @return integer $oldrevision|false
2391 */
2392 function getPreviousRevisionID( $revision ) {
2393 $dbr =& wfGetDB( DB_SLAVE );
2394 return $dbr->selectField( 'revision', 'rev_id',
2395 'rev_page=' . intval( $this->getArticleId() ) .
2396 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2397 }
2398
2399 /**
2400 * Get the revision ID of the next revision
2401 *
2402 * @param integer $revision Revision ID. Get the revision that was after this one.
2403 * @return integer $oldrevision|false
2404 */
2405 function getNextRevisionID( $revision ) {
2406 $dbr =& wfGetDB( DB_SLAVE );
2407 return $dbr->selectField( 'revision', 'rev_id',
2408 'rev_page=' . intval( $this->getArticleId() ) .
2409 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2410 }
2411
2412 /**
2413 * Get the number of revisions between the given revision IDs.
2414 *
2415 * @param integer $old Revision ID.
2416 * @param integer $new Revision ID.
2417 * @return integer Number of revisions between these IDs.
2418 */
2419 function countRevisionsBetween( $old, $new ) {
2420 $dbr =& wfGetDB( DB_SLAVE );
2421 return $dbr->selectField( 'revision', 'count(*)',
2422 'rev_page = ' . intval( $this->getArticleId() ) .
2423 ' AND rev_id > ' . intval( $old ) .
2424 ' AND rev_id < ' . intval( $new ) );
2425 }
2426
2427 /**
2428 * Compare with another title.
2429 *
2430 * @param Title $title
2431 * @return bool
2432 */
2433 function equals( $title ) {
2434 // Note: === is necessary for proper matching of number-like titles.
2435 return $this->getInterwiki() === $title->getInterwiki()
2436 && $this->getNamespace() == $title->getNamespace()
2437 && $this->getDbkey() === $title->getDbkey();
2438 }
2439
2440 /**
2441 * Check if page exists
2442 * @return bool
2443 */
2444 function exists() {
2445 return $this->getArticleId() != 0;
2446 }
2447
2448 /**
2449 * Should a link should be displayed as a known link, just based on its title?
2450 *
2451 * Currently, a self-link with a fragment and special pages are in
2452 * this category. Special pages never exist in the database.
2453 */
2454 function isAlwaysKnown() {
2455 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2456 || NS_SPECIAL == $this->mNamespace;
2457 }
2458
2459 /**
2460 * Update page_touched timestamps and send squid purge messages for
2461 * pages linking to this title. May be sent to the job queue depending
2462 * on the number of links. Typically called on create and delete.
2463 */
2464 function touchLinks() {
2465 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2466 $u->doUpdate();
2467
2468 if ( $this->getNamespace() == NS_CATEGORY ) {
2469 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2470 $u->doUpdate();
2471 }
2472 }
2473
2474 /**
2475 * Get the last touched timestamp
2476 */
2477 function getTouched() {
2478 $dbr =& wfGetDB( DB_SLAVE );
2479 $touched = $dbr->selectField( 'page', 'page_touched',
2480 array(
2481 'page_namespace' => $this->getNamespace(),
2482 'page_title' => $this->getDBkey()
2483 ), __METHOD__
2484 );
2485 return $touched;
2486 }
2487
2488 /**
2489 * Get a cached value from a global cache that is invalidated when this page changes
2490 * @param string $key the key
2491 * @param callback $callback A callback function which generates the value on cache miss
2492 *
2493 * @deprecated use DependencyWrapper
2494 */
2495 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2496 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2497 $params, new TitleDependency( $this ) );
2498 }
2499
2500 function trackbackURL() {
2501 global $wgTitle, $wgScriptPath, $wgServer;
2502
2503 return "$wgServer$wgScriptPath/trackback.php?article="
2504 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2505 }
2506
2507 function trackbackRDF() {
2508 $url = htmlspecialchars($this->getFullURL());
2509 $title = htmlspecialchars($this->getText());
2510 $tburl = $this->trackbackURL();
2511
2512 return "
2513 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2514 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2515 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2516 <rdf:Description
2517 rdf:about=\"$url\"
2518 dc:identifier=\"$url\"
2519 dc:title=\"$title\"
2520 trackback:ping=\"$tburl\" />
2521 </rdf:RDF>";
2522 }
2523
2524 /**
2525 * Generate strings used for xml 'id' names in monobook tabs
2526 * @return string
2527 */
2528 function getNamespaceKey() {
2529 global $wgContLang;
2530 switch ($this->getNamespace()) {
2531 case NS_MAIN:
2532 case NS_TALK:
2533 return 'nstab-main';
2534 case NS_USER:
2535 case NS_USER_TALK:
2536 return 'nstab-user';
2537 case NS_MEDIA:
2538 return 'nstab-media';
2539 case NS_SPECIAL:
2540 return 'nstab-special';
2541 case NS_PROJECT:
2542 case NS_PROJECT_TALK:
2543 return 'nstab-project';
2544 case NS_IMAGE:
2545 case NS_IMAGE_TALK:
2546 return 'nstab-image';
2547 case NS_MEDIAWIKI:
2548 case NS_MEDIAWIKI_TALK:
2549 return 'nstab-mediawiki';
2550 case NS_TEMPLATE:
2551 case NS_TEMPLATE_TALK:
2552 return 'nstab-template';
2553 case NS_HELP:
2554 case NS_HELP_TALK:
2555 return 'nstab-help';
2556 case NS_CATEGORY:
2557 case NS_CATEGORY_TALK:
2558 return 'nstab-category';
2559 default:
2560 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2561 }
2562 }
2563
2564 /**
2565 * Returns true if this title resolves to the named special page
2566 * @param string $name The special page name
2567 * @access public
2568 */
2569 function isSpecial( $name ) {
2570 if ( $this->getNamespace() == NS_SPECIAL ) {
2571 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2572 if ( $name == $thisName ) {
2573 return true;
2574 }
2575 }
2576 return false;
2577 }
2578
2579 /**
2580 * If the Title refers to a special page alias which is not the local default,
2581 * returns a new Title which points to the local default. Otherwise, returns $this.
2582 */
2583 function fixSpecialName() {
2584 if ( $this->getNamespace() == NS_SPECIAL ) {
2585 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2586 if ( $canonicalName ) {
2587 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2588 if ( $localName != $this->mDbkeyform ) {
2589 return Title::makeTitle( NS_SPECIAL, $localName );
2590 }
2591 }
2592 }
2593 return $this;
2594 }
2595
2596 /**
2597 * Is this Title in a namespace which contains content?
2598 * In other words, is this a content page, for the purposes of calculating
2599 * statistics, etc?
2600 *
2601 * @return bool
2602 */
2603 public function isContentPage() {
2604 return Namespace::isContent( $this->getNamespace() );
2605 }
2606
2607 }
2608
2609 ?>