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