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