API: Adding cascade flag to prop=info&inprop=protection
[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 *
1030 * FIXME: This *does not* check throttles (User::pingLimiter()).
1031 *
1032 * @param string $action action that permission needs to be checked for
1033 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1034 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1035 */
1036 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
1037 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1038
1039 global $wgContLang;
1040 global $wgLang;
1041 global $wgEmailConfirmToEdit, $wgUser;
1042
1043 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1044 $errors[] = array( 'confirmedittext' );
1045 }
1046
1047 if ( $user->isBlockedFrom( $this ) ) {
1048 $block = $user->mBlock;
1049
1050 // This is from OutputPage::blockedPage
1051 // Copied at r23888 by werdna
1052
1053 $id = $user->blockedBy();
1054 $reason = $user->blockedFor();
1055 if( $reason == '' ) {
1056 $reason = wfMsg( 'blockednoreason' );
1057 }
1058 $ip = wfGetIP();
1059
1060 if ( is_numeric( $id ) ) {
1061 $name = User::whoIs( $id );
1062 } else {
1063 $name = $id;
1064 }
1065
1066 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1067 $blockid = $block->mId;
1068 $blockExpiry = $user->mBlock->mExpiry;
1069 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1070
1071 if ( $blockExpiry == 'infinity' ) {
1072 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1073 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1074
1075 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1076 if ( strpos( $option, ':' ) == false )
1077 continue;
1078
1079 list ($show, $value) = explode( ":", $option );
1080
1081 if ( $value == 'infinite' || $value == 'indefinite' ) {
1082 $blockExpiry = $show;
1083 break;
1084 }
1085 }
1086 } else {
1087 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1088 }
1089
1090 $intended = $user->mBlock->mAddress;
1091
1092 $errors[] = array ( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
1093 }
1094
1095 return $errors;
1096 }
1097
1098 /**
1099 * Can $user perform $action on this page? This is an internal function,
1100 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1101 * checks on wfReadOnly() and blocks)
1102 *
1103 * @param string $action action that permission needs to be checked for
1104 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1105 * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
1106 */
1107 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1108 wfProfileIn( __METHOD__ );
1109
1110 $errors = array();
1111
1112 // Use getUserPermissionsErrors instead
1113 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1114 return $result ? array() : array( array( 'badaccess-group0' ) );
1115 }
1116
1117 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1118 if ($result != array() && is_array($result) && !is_array($result[0]))
1119 $errors[] = $result; # A single array representing an error
1120 else if (is_array($result) && is_array($result[0]))
1121 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1122 else if ($result != '' && $result != null && $result !== true && $result !== false)
1123 $errors[] = array($result); # A string representing a message-id
1124 else if ($result === false )
1125 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1126 }
1127 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1128 if ($result != array() && is_array($result) && !is_array($result[0]))
1129 $errors[] = $result; # A single array representing an error
1130 else if (is_array($result) && is_array($result[0]))
1131 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1132 else if ($result != '' && $result != null && $result !== true && $result !== false)
1133 $errors[] = array($result); # A string representing a message-id
1134 else if ($result === false )
1135 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1136 }
1137
1138 if( NS_SPECIAL == $this->mNamespace ) {
1139 $errors[] = array('ns-specialprotected');
1140 }
1141
1142 if ( $this->isNamespaceProtected() ) {
1143 $ns = $this->getNamespace() == NS_MAIN
1144 ? wfMsg( 'nstab-main' )
1145 : $this->getNsText();
1146 $errors[] = (NS_MEDIAWIKI == $this->mNamespace
1147 ? array('protectedinterface')
1148 : array( 'namespaceprotected', $ns ) );
1149 }
1150
1151 if( $this->mDbkeyform == '_' ) {
1152 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1153 $errors[] = array('badaccess-group0');
1154 }
1155
1156 # protect css/js subpages of user pages
1157 # XXX: this might be better using restrictions
1158 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1159 if( $this->isCssJsSubpage()
1160 && !$user->isAllowed('editusercssjs')
1161 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1162 $errors[] = array('customcssjsprotected');
1163 }
1164
1165 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1166 # We /could/ use the protection level on the source page, but it's fairly ugly
1167 # as we have to establish a precedence hierarchy for pages included by multiple
1168 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1169 # as they could remove the protection anyway.
1170 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1171 # Cascading protection depends on more than this page...
1172 # Several cascading protected pages may include this page...
1173 # Check each cascading level
1174 # This is only for protection restrictions, not for all actions
1175 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1176 foreach( $restrictions[$action] as $right ) {
1177 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1178 if( '' != $right && !$user->isAllowed( $right ) ) {
1179 $pages = '';
1180 foreach( $cascadingSources as $page )
1181 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1182 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1183 }
1184 }
1185 }
1186 }
1187
1188 foreach( $this->getRestrictions($action) as $right ) {
1189 // Backwards compatibility, rewrite sysop -> protect
1190 if ( $right == 'sysop' ) {
1191 $right = 'protect';
1192 }
1193 if( '' != $right && !$user->isAllowed( $right ) ) {
1194 $errors[] = array( 'protectedpagetext', $right );
1195 }
1196 }
1197
1198 if ($action == 'protect') {
1199 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1200 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1201 }
1202 }
1203
1204 if ($action == 'create') {
1205 $title_protection = $this->getTitleProtection();
1206
1207 if (is_array($title_protection)) {
1208 extract($title_protection);
1209
1210 if ($pt_create_perm == 'sysop')
1211 $pt_create_perm = 'protect';
1212
1213 if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
1214 $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
1215 }
1216 }
1217
1218 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1219 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1220 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1221 }
1222 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1223 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1224 } elseif ( !$user->isAllowed( $action ) ) {
1225 $return = null;
1226 $groups = array();
1227 global $wgGroupPermissions;
1228 foreach( $wgGroupPermissions as $key => $value ) {
1229 if( isset( $value[$action] ) && $value[$action] == true ) {
1230 $groupName = User::getGroupName( $key );
1231 $groupPage = User::getGroupPage( $key );
1232 if( $groupPage ) {
1233 $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
1234 } else {
1235 $groups[] = $groupName;
1236 }
1237 }
1238 }
1239 $n = count( $groups );
1240 $groups = implode( ', ', $groups );
1241 switch( $n ) {
1242 case 0:
1243 case 1:
1244 case 2:
1245 $return = array( "badaccess-group$n", $groups );
1246 break;
1247 default:
1248 $return = array( 'badaccess-groups', $groups );
1249 }
1250 $errors[] = $return;
1251 }
1252
1253 wfProfileOut( __METHOD__ );
1254 return $errors;
1255 }
1256
1257 /**
1258 * Is this title subject to title protection?
1259 * @return mixed An associative array representing any existent title
1260 * protection, or false if there's none.
1261 */
1262 private function getTitleProtection() {
1263 // Can't protect pages in special namespaces
1264 if ( $this->getNamespace() < 0 ) {
1265 return false;
1266 }
1267
1268 $dbr = wfGetDB( DB_SLAVE );
1269 $res = $dbr->select( 'protected_titles', '*',
1270 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1271
1272 if ($row = $dbr->fetchRow( $res )) {
1273 return $row;
1274 } else {
1275 return false;
1276 }
1277 }
1278
1279 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1280 global $wgGroupPermissions,$wgUser,$wgContLang;
1281
1282 if ($create_perm == implode(',',$this->getRestrictions('create'))
1283 && $expiry == $this->mRestrictionsExpiry) {
1284 // No change
1285 return true;
1286 }
1287
1288 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1289
1290 $dbw = wfGetDB( DB_MASTER );
1291
1292 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1293
1294 $expiry_description = '';
1295 if ( $encodedExpiry != 'infinity' ) {
1296 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1297 }
1298
1299 # Update protection table
1300 if ($create_perm != '' ) {
1301 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1302 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1303 , 'pt_create_perm' => $create_perm
1304 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1305 , 'pt_expiry' => $encodedExpiry
1306 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1307 } else {
1308 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1309 'pt_title' => $title ), __METHOD__ );
1310 }
1311 # Update the protection log
1312 $log = new LogPage( 'protect' );
1313
1314 if( $create_perm ) {
1315 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1316 } else {
1317 $log->addEntry( 'unprotect', $this, $reason );
1318 }
1319
1320 return true;
1321 }
1322
1323 /**
1324 * Remove any title protection (due to page existing
1325 */
1326 public function deleteTitleProtection() {
1327 $dbw = wfGetDB( DB_MASTER );
1328
1329 $dbw->delete( 'protected_titles',
1330 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1331 }
1332
1333 /**
1334 * Can $wgUser edit this page?
1335 * @return boolean
1336 * @deprecated use userCan('edit')
1337 */
1338 public function userCanEdit( $doExpensiveQueries = true ) {
1339 return $this->userCan( 'edit', $doExpensiveQueries );
1340 }
1341
1342 /**
1343 * Can $wgUser create this page?
1344 * @return boolean
1345 * @deprecated use userCan('create')
1346 */
1347 public function userCanCreate( $doExpensiveQueries = true ) {
1348 return $this->userCan( 'create', $doExpensiveQueries );
1349 }
1350
1351 /**
1352 * Can $wgUser move this page?
1353 * @return boolean
1354 * @deprecated use userCan('move')
1355 */
1356 public function userCanMove( $doExpensiveQueries = true ) {
1357 return $this->userCan( 'move', $doExpensiveQueries );
1358 }
1359
1360 /**
1361 * Would anybody with sufficient privileges be able to move this page?
1362 * Some pages just aren't movable.
1363 *
1364 * @return boolean
1365 */
1366 public function isMovable() {
1367 return Namespace::isMovable( $this->getNamespace() )
1368 && $this->getInterwiki() == '';
1369 }
1370
1371 /**
1372 * Can $wgUser read this page?
1373 * @return boolean
1374 * @todo fold these checks into userCan()
1375 */
1376 public function userCanRead() {
1377 global $wgUser, $wgGroupPermissions;
1378
1379 # Shortcut for public wikis, allows skipping quite a bit of code path
1380 if ($wgGroupPermissions['*']['read'])
1381 return true;
1382
1383 $result = null;
1384 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1385 if ( $result !== null ) {
1386 return $result;
1387 }
1388
1389 if( $wgUser->isAllowed( 'read' ) ) {
1390 return true;
1391 } else {
1392 global $wgWhitelistRead;
1393
1394 /**
1395 * Always grant access to the login page.
1396 * Even anons need to be able to log in.
1397 */
1398 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1399 return true;
1400 }
1401
1402 /**
1403 * Bail out if there isn't whitelist
1404 */
1405 if( !is_array($wgWhitelistRead) ) {
1406 return false;
1407 }
1408
1409 /**
1410 * Check for explicit whitelisting
1411 */
1412 $name = $this->getPrefixedText();
1413 if( in_array( $name, $wgWhitelistRead, true ) )
1414 return true;
1415
1416 /**
1417 * Old settings might have the title prefixed with
1418 * a colon for main-namespace pages
1419 */
1420 if( $this->getNamespace() == NS_MAIN ) {
1421 if( in_array( ':' . $name, $wgWhitelistRead ) )
1422 return true;
1423 }
1424
1425 /**
1426 * If it's a special page, ditch the subpage bit
1427 * and check again
1428 */
1429 if( $this->getNamespace() == NS_SPECIAL ) {
1430 $name = $this->getDBkey();
1431 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1432 if ( $name === false ) {
1433 # Invalid special page, but we show standard login required message
1434 return false;
1435 }
1436
1437 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1438 if( in_array( $pure, $wgWhitelistRead, true ) )
1439 return true;
1440 }
1441
1442 }
1443 return false;
1444 }
1445
1446 /**
1447 * Is this a talk page of some sort?
1448 * @return bool
1449 */
1450 public function isTalkPage() {
1451 return Namespace::isTalk( $this->getNamespace() );
1452 }
1453
1454 /**
1455 * Is this a subpage?
1456 * @return bool
1457 */
1458 public function isSubpage() {
1459 global $wgNamespacesWithSubpages;
1460
1461 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1462 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1463 } else {
1464 return false;
1465 }
1466 }
1467
1468 /**
1469 * Could this page contain custom CSS or JavaScript, based
1470 * on the title?
1471 *
1472 * @return bool
1473 */
1474 public function isCssOrJsPage() {
1475 return $this->mNamespace == NS_MEDIAWIKI
1476 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1477 }
1478
1479 /**
1480 * Is this a .css or .js subpage of a user page?
1481 * @return bool
1482 */
1483 public function isCssJsSubpage() {
1484 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1485 }
1486 /**
1487 * Is this a *valid* .css or .js subpage of a user page?
1488 * Check that the corresponding skin exists
1489 */
1490 public function isValidCssJsSubpage() {
1491 if ( $this->isCssJsSubpage() ) {
1492 $skinNames = Skin::getSkinNames();
1493 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1494 } else {
1495 return false;
1496 }
1497 }
1498 /**
1499 * Trim down a .css or .js subpage title to get the corresponding skin name
1500 */
1501 public function getSkinFromCssJsSubpage() {
1502 $subpage = explode( '/', $this->mTextform );
1503 $subpage = $subpage[ count( $subpage ) - 1 ];
1504 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1505 }
1506 /**
1507 * Is this a .css subpage of a user page?
1508 * @return bool
1509 */
1510 public function isCssSubpage() {
1511 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1512 }
1513 /**
1514 * Is this a .js subpage of a user page?
1515 * @return bool
1516 */
1517 public function isJsSubpage() {
1518 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1519 }
1520 /**
1521 * Protect css/js subpages of user pages: can $wgUser edit
1522 * this page?
1523 *
1524 * @return boolean
1525 * @todo XXX: this might be better using restrictions
1526 */
1527 public function userCanEditCssJsSubpage() {
1528 global $wgUser;
1529 return ( $wgUser->isAllowed('editusercssjs') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1530 }
1531
1532 /**
1533 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1534 *
1535 * @return bool If the page is subject to cascading restrictions.
1536 */
1537 public function isCascadeProtected() {
1538 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1539 return ( $sources > 0 );
1540 }
1541
1542 /**
1543 * Cascading protection: Get the source of any cascading restrictions on this page.
1544 *
1545 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1546 * @return array( mixed title array, restriction array)
1547 * 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.
1548 * The restriction array is an array of each type, each of which contains an array of unique groups
1549 */
1550 public function getCascadeProtectionSources( $get_pages = true ) {
1551 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1552
1553 # Define our dimension of restrictions types
1554 $pagerestrictions = array();
1555 foreach( $wgRestrictionTypes as $action )
1556 $pagerestrictions[$action] = array();
1557
1558 if (!$wgEnableCascadingProtection)
1559 return array( false, $pagerestrictions );
1560
1561 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1562 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1563 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1564 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1565 }
1566
1567 wfProfileIn( __METHOD__ );
1568
1569 $dbr = wfGetDb( DB_SLAVE );
1570
1571 if ( $this->getNamespace() == NS_IMAGE ) {
1572 $tables = array ('imagelinks', 'page_restrictions');
1573 $where_clauses = array(
1574 'il_to' => $this->getDBkey(),
1575 'il_from=pr_page',
1576 'pr_cascade' => 1 );
1577 } else {
1578 $tables = array ('templatelinks', 'page_restrictions');
1579 $where_clauses = array(
1580 'tl_namespace' => $this->getNamespace(),
1581 'tl_title' => $this->getDBkey(),
1582 'tl_from=pr_page',
1583 'pr_cascade' => 1 );
1584 }
1585
1586 if ( $get_pages ) {
1587 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1588 $where_clauses[] = 'page_id=pr_page';
1589 $tables[] = 'page';
1590 } else {
1591 $cols = array( 'pr_expiry' );
1592 }
1593
1594 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1595
1596 $sources = $get_pages ? array() : false;
1597 $now = wfTimestampNow();
1598 $purgeExpired = false;
1599
1600 while( $row = $dbr->fetchObject( $res ) ) {
1601 $expiry = Block::decodeExpiry( $row->pr_expiry );
1602 if( $expiry > $now ) {
1603 if ($get_pages) {
1604 $page_id = $row->pr_page;
1605 $page_ns = $row->page_namespace;
1606 $page_title = $row->page_title;
1607 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1608 # Add groups needed for each restriction type if its not already there
1609 # Make sure this restriction type still exists
1610 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1611 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1612 }
1613 } else {
1614 $sources = true;
1615 }
1616 } else {
1617 // Trigger lazy purge of expired restrictions from the db
1618 $purgeExpired = true;
1619 }
1620 }
1621 if( $purgeExpired ) {
1622 Title::purgeExpiredRestrictions();
1623 }
1624
1625 wfProfileOut( __METHOD__ );
1626
1627 if ( $get_pages ) {
1628 $this->mCascadeSources = $sources;
1629 $this->mCascadingRestrictions = $pagerestrictions;
1630 } else {
1631 $this->mHasCascadingRestrictions = $sources;
1632 }
1633
1634 return array( $sources, $pagerestrictions );
1635 }
1636
1637 function areRestrictionsCascading() {
1638 if (!$this->mRestrictionsLoaded) {
1639 $this->loadRestrictions();
1640 }
1641
1642 return $this->mCascadeRestriction;
1643 }
1644
1645 /**
1646 * Loads a string into mRestrictions array
1647 * @param resource $res restrictions as an SQL result.
1648 */
1649 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1650 $dbr = wfGetDb( DB_SLAVE );
1651
1652 $this->mRestrictions['edit'] = array();
1653 $this->mRestrictions['move'] = array();
1654
1655 # Backwards-compatibility: also load the restrictions from the page record (old format).
1656
1657 if ( $oldFashionedRestrictions == NULL ) {
1658 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1659 }
1660
1661 if ($oldFashionedRestrictions != '') {
1662
1663 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1664 $temp = explode( '=', trim( $restrict ) );
1665 if(count($temp) == 1) {
1666 // old old format should be treated as edit/move restriction
1667 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1668 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1669 } else {
1670 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1671 }
1672 }
1673
1674 $this->mOldRestrictions = true;
1675 $this->mCascadeRestriction = false;
1676 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1677
1678 }
1679
1680 if( $dbr->numRows( $res ) ) {
1681 # Current system - load second to make them override.
1682 $now = wfTimestampNow();
1683 $purgeExpired = false;
1684
1685 while ($row = $dbr->fetchObject( $res ) ) {
1686 # Cycle through all the restrictions.
1687
1688 // This code should be refactored, now that it's being used more generally,
1689 // But I don't really see any harm in leaving it in Block for now -werdna
1690 $expiry = Block::decodeExpiry( $row->pr_expiry );
1691
1692 // Only apply the restrictions if they haven't expired!
1693 if ( !$expiry || $expiry > $now ) {
1694 $this->mRestrictionsExpiry = $expiry;
1695 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1696
1697 $this->mCascadeRestriction |= $row->pr_cascade;
1698 } else {
1699 // Trigger a lazy purge of expired restrictions
1700 $purgeExpired = true;
1701 }
1702 }
1703
1704 if( $purgeExpired ) {
1705 Title::purgeExpiredRestrictions();
1706 }
1707 }
1708
1709 $this->mRestrictionsLoaded = true;
1710 }
1711
1712 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1713 if( !$this->mRestrictionsLoaded ) {
1714 if ($this->exists()) {
1715 $dbr = wfGetDB( DB_SLAVE );
1716
1717 $res = $dbr->select( 'page_restrictions', '*',
1718 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1719
1720 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1721 } else {
1722 $title_protection = $this->getTitleProtection();
1723
1724 if (is_array($title_protection)) {
1725 extract($title_protection);
1726
1727 $now = wfTimestampNow();
1728 $expiry = Block::decodeExpiry($pt_expiry);
1729
1730 if (!$expiry || $expiry > $now) {
1731 // Apply the restrictions
1732 $this->mRestrictionsExpiry = $expiry;
1733 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1734 } else { // Get rid of the old restrictions
1735 Title::purgeExpiredRestrictions();
1736 }
1737 }
1738 $this->mRestrictionsLoaded = true;
1739 }
1740 }
1741 }
1742
1743 /**
1744 * Purge expired restrictions from the page_restrictions table
1745 */
1746 static function purgeExpiredRestrictions() {
1747 $dbw = wfGetDB( DB_MASTER );
1748 $dbw->delete( 'page_restrictions',
1749 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1750 __METHOD__ );
1751
1752 $dbw->delete( 'protected_titles',
1753 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1754 __METHOD__ );
1755 }
1756
1757 /**
1758 * Accessor/initialisation for mRestrictions
1759 *
1760 * @param string $action action that permission needs to be checked for
1761 * @return array the array of groups allowed to edit this article
1762 */
1763 public function getRestrictions( $action ) {
1764 if( !$this->mRestrictionsLoaded ) {
1765 $this->loadRestrictions();
1766 }
1767 return isset( $this->mRestrictions[$action] )
1768 ? $this->mRestrictions[$action]
1769 : array();
1770 }
1771
1772 /**
1773 * Is there a version of this page in the deletion archive?
1774 * @return int the number of archived revisions
1775 */
1776 public function isDeleted() {
1777 $fname = 'Title::isDeleted';
1778 if ( $this->getNamespace() < 0 ) {
1779 $n = 0;
1780 } else {
1781 $dbr = wfGetDB( DB_SLAVE );
1782 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1783 'ar_title' => $this->getDBkey() ), $fname );
1784 if( $this->getNamespace() == NS_IMAGE ) {
1785 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1786 array( 'fa_name' => $this->getDBkey() ), $fname );
1787 }
1788 }
1789 return (int)$n;
1790 }
1791
1792 /**
1793 * Get the article ID for this Title from the link cache,
1794 * adding it if necessary
1795 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1796 * for update
1797 * @return int the ID
1798 */
1799 public function getArticleID( $flags = 0 ) {
1800 $linkCache =& LinkCache::singleton();
1801 if ( $flags & GAID_FOR_UPDATE ) {
1802 $oldUpdate = $linkCache->forUpdate( true );
1803 $this->mArticleID = $linkCache->addLinkObj( $this );
1804 $linkCache->forUpdate( $oldUpdate );
1805 } else {
1806 if ( -1 == $this->mArticleID ) {
1807 $this->mArticleID = $linkCache->addLinkObj( $this );
1808 }
1809 }
1810 return $this->mArticleID;
1811 }
1812
1813 public function getLatestRevID() {
1814 if ($this->mLatestID !== false)
1815 return $this->mLatestID;
1816
1817 $db = wfGetDB(DB_SLAVE);
1818 return $this->mLatestID = $db->selectField( 'revision',
1819 "max(rev_id)",
1820 array('rev_page' => $this->getArticleID()),
1821 'Title::getLatestRevID' );
1822 }
1823
1824 /**
1825 * This clears some fields in this object, and clears any associated
1826 * keys in the "bad links" section of the link cache.
1827 *
1828 * - This is called from Article::insertNewArticle() to allow
1829 * loading of the new page_id. It's also called from
1830 * Article::doDeleteArticle()
1831 *
1832 * @param int $newid the new Article ID
1833 */
1834 public function resetArticleID( $newid ) {
1835 $linkCache =& LinkCache::singleton();
1836 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1837
1838 if ( 0 == $newid ) { $this->mArticleID = -1; }
1839 else { $this->mArticleID = $newid; }
1840 $this->mRestrictionsLoaded = false;
1841 $this->mRestrictions = array();
1842 }
1843
1844 /**
1845 * Updates page_touched for this page; called from LinksUpdate.php
1846 * @return bool true if the update succeded
1847 */
1848 public function invalidateCache() {
1849 global $wgUseFileCache;
1850
1851 if ( wfReadOnly() ) {
1852 return;
1853 }
1854
1855 $dbw = wfGetDB( DB_MASTER );
1856 $success = $dbw->update( 'page',
1857 array( /* SET */
1858 'page_touched' => $dbw->timestamp()
1859 ), array( /* WHERE */
1860 'page_namespace' => $this->getNamespace() ,
1861 'page_title' => $this->getDBkey()
1862 ), 'Title::invalidateCache'
1863 );
1864
1865 if ($wgUseFileCache) {
1866 $cache = new HTMLFileCache($this);
1867 @unlink($cache->fileCacheName());
1868 }
1869
1870 return $success;
1871 }
1872
1873 /**
1874 * Prefix some arbitrary text with the namespace or interwiki prefix
1875 * of this object
1876 *
1877 * @param string $name the text
1878 * @return string the prefixed text
1879 * @private
1880 */
1881 /* private */ function prefix( $name ) {
1882 $p = '';
1883 if ( '' != $this->mInterwiki ) {
1884 $p = $this->mInterwiki . ':';
1885 }
1886 if ( 0 != $this->mNamespace ) {
1887 $p .= $this->getNsText() . ':';
1888 }
1889 return $p . $name;
1890 }
1891
1892 /**
1893 * Secure and split - main initialisation function for this object
1894 *
1895 * Assumes that mDbkeyform has been set, and is urldecoded
1896 * and uses underscores, but not otherwise munged. This function
1897 * removes illegal characters, splits off the interwiki and
1898 * namespace prefixes, sets the other forms, and canonicalizes
1899 * everything.
1900 * @return bool true on success
1901 */
1902 private function secureAndSplit() {
1903 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1904
1905 # Initialisation
1906 static $rxTc = false;
1907 if( !$rxTc ) {
1908 # Matching titles will be held as illegal.
1909 $rxTc = '/' .
1910 # Any character not allowed is forbidden...
1911 '[^' . Title::legalChars() . ']' .
1912 # URL percent encoding sequences interfere with the ability
1913 # to round-trip titles -- you can't link to them consistently.
1914 '|%[0-9A-Fa-f]{2}' .
1915 # XML/HTML character references produce similar issues.
1916 '|&[A-Za-z0-9\x80-\xff]+;' .
1917 '|&#[0-9]+;' .
1918 '|&#x[0-9A-Fa-f]+;' .
1919 '/S';
1920 }
1921
1922 $this->mInterwiki = $this->mFragment = '';
1923 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1924
1925 $dbkey = $this->mDbkeyform;
1926
1927 # Strip Unicode bidi override characters.
1928 # Sometimes they slip into cut-n-pasted page titles, where the
1929 # override chars get included in list displays.
1930 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1931 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1932
1933 # Clean up whitespace
1934 #
1935 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1936 $dbkey = trim( $dbkey, '_' );
1937
1938 if ( '' == $dbkey ) {
1939 return false;
1940 }
1941
1942 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1943 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1944 return false;
1945 }
1946
1947 $this->mDbkeyform = $dbkey;
1948
1949 # Initial colon indicates main namespace rather than specified default
1950 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1951 if ( ':' == $dbkey{0} ) {
1952 $this->mNamespace = NS_MAIN;
1953 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1954 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1955 }
1956
1957 # Namespace or interwiki prefix
1958 $firstPass = true;
1959 do {
1960 $m = array();
1961 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1962 $p = $m[1];
1963 if ( $ns = $wgContLang->getNsIndex( $p )) {
1964 # Ordinary namespace
1965 $dbkey = $m[2];
1966 $this->mNamespace = $ns;
1967 } elseif( $this->getInterwikiLink( $p ) ) {
1968 if( !$firstPass ) {
1969 # Can't make a local interwiki link to an interwiki link.
1970 # That's just crazy!
1971 return false;
1972 }
1973
1974 # Interwiki link
1975 $dbkey = $m[2];
1976 $this->mInterwiki = $wgContLang->lc( $p );
1977
1978 # Redundant interwiki prefix to the local wiki
1979 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1980 if( $dbkey == '' ) {
1981 # Can't have an empty self-link
1982 return false;
1983 }
1984 $this->mInterwiki = '';
1985 $firstPass = false;
1986 # Do another namespace split...
1987 continue;
1988 }
1989
1990 # If there's an initial colon after the interwiki, that also
1991 # resets the default namespace
1992 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1993 $this->mNamespace = NS_MAIN;
1994 $dbkey = substr( $dbkey, 1 );
1995 }
1996 }
1997 # If there's no recognized interwiki or namespace,
1998 # then let the colon expression be part of the title.
1999 }
2000 break;
2001 } while( true );
2002
2003 # We already know that some pages won't be in the database!
2004 #
2005 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2006 $this->mArticleID = 0;
2007 }
2008 $fragment = strstr( $dbkey, '#' );
2009 if ( false !== $fragment ) {
2010 $this->setFragment( $fragment );
2011 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2012 # remove whitespace again: prevents "Foo_bar_#"
2013 # becoming "Foo_bar_"
2014 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2015 }
2016
2017 # Reject illegal characters.
2018 #
2019 if( preg_match( $rxTc, $dbkey ) ) {
2020 return false;
2021 }
2022
2023 /**
2024 * Pages with "/./" or "/../" appearing in the URLs will
2025 * often be unreachable due to the way web browsers deal
2026 * with 'relative' URLs. Forbid them explicitly.
2027 */
2028 if ( strpos( $dbkey, '.' ) !== false &&
2029 ( $dbkey === '.' || $dbkey === '..' ||
2030 strpos( $dbkey, './' ) === 0 ||
2031 strpos( $dbkey, '../' ) === 0 ||
2032 strpos( $dbkey, '/./' ) !== false ||
2033 strpos( $dbkey, '/../' ) !== false ) )
2034 {
2035 return false;
2036 }
2037
2038 /**
2039 * Magic tilde sequences? Nu-uh!
2040 */
2041 if( strpos( $dbkey, '~~~' ) !== false ) {
2042 return false;
2043 }
2044
2045 /**
2046 * Limit the size of titles to 255 bytes.
2047 * This is typically the size of the underlying database field.
2048 * We make an exception for special pages, which don't need to be stored
2049 * in the database, and may edge over 255 bytes due to subpage syntax
2050 * for long titles, e.g. [[Special:Block/Long name]]
2051 */
2052 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2053 strlen( $dbkey ) > 512 )
2054 {
2055 return false;
2056 }
2057
2058 /**
2059 * Normally, all wiki links are forced to have
2060 * an initial capital letter so [[foo]] and [[Foo]]
2061 * point to the same place.
2062 *
2063 * Don't force it for interwikis, since the other
2064 * site might be case-sensitive.
2065 */
2066 $this->mUserCaseDBKey = $dbkey;
2067 if( $wgCapitalLinks && $this->mInterwiki == '') {
2068 $dbkey = $wgContLang->ucfirst( $dbkey );
2069 }
2070
2071 /**
2072 * Can't make a link to a namespace alone...
2073 * "empty" local links can only be self-links
2074 * with a fragment identifier.
2075 */
2076 if( $dbkey == '' &&
2077 $this->mInterwiki == '' &&
2078 $this->mNamespace != NS_MAIN ) {
2079 return false;
2080 }
2081 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2082 // IP names are not allowed for accounts, and can only be referring to
2083 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2084 // there are numerous ways to present the same IP. Having sp:contribs scan
2085 // them all is silly and having some show the edits and others not is
2086 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2087 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2088 IP::sanitizeIP( $dbkey ) : $dbkey;
2089 // Any remaining initial :s are illegal.
2090 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2091 return false;
2092 }
2093
2094 # Fill fields
2095 $this->mDbkeyform = $dbkey;
2096 $this->mUrlform = wfUrlencode( $dbkey );
2097
2098 $this->mTextform = str_replace( '_', ' ', $dbkey );
2099
2100 return true;
2101 }
2102
2103 /**
2104 * Set the fragment for this title
2105 * This is kind of bad, since except for this rarely-used function, Title objects
2106 * are immutable. The reason this is here is because it's better than setting the
2107 * members directly, which is what Linker::formatComment was doing previously.
2108 *
2109 * @param string $fragment text
2110 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2111 */
2112 public function setFragment( $fragment ) {
2113 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2114 }
2115
2116 /**
2117 * Get a Title object associated with the talk page of this article
2118 * @return Title the object for the talk page
2119 */
2120 public function getTalkPage() {
2121 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2122 }
2123
2124 /**
2125 * Get a title object associated with the subject page of this
2126 * talk page
2127 *
2128 * @return Title the object for the subject page
2129 */
2130 public function getSubjectPage() {
2131 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2132 }
2133
2134 /**
2135 * Get an array of Title objects linking to this Title
2136 * Also stores the IDs in the link cache.
2137 *
2138 * WARNING: do not use this function on arbitrary user-supplied titles!
2139 * On heavily-used templates it will max out the memory.
2140 *
2141 * @param string $options may be FOR UPDATE
2142 * @return array the Title objects linking here
2143 */
2144 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2145 $linkCache =& LinkCache::singleton();
2146
2147 if ( $options ) {
2148 $db = wfGetDB( DB_MASTER );
2149 } else {
2150 $db = wfGetDB( DB_SLAVE );
2151 }
2152
2153 $res = $db->select( array( 'page', $table ),
2154 array( 'page_namespace', 'page_title', 'page_id' ),
2155 array(
2156 "{$prefix}_from=page_id",
2157 "{$prefix}_namespace" => $this->getNamespace(),
2158 "{$prefix}_title" => $this->getDBkey() ),
2159 'Title::getLinksTo',
2160 $options );
2161
2162 $retVal = array();
2163 if ( $db->numRows( $res ) ) {
2164 while ( $row = $db->fetchObject( $res ) ) {
2165 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2166 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
2167 $retVal[] = $titleObj;
2168 }
2169 }
2170 }
2171 $db->freeResult( $res );
2172 return $retVal;
2173 }
2174
2175 /**
2176 * Get an array of Title objects using this Title as a template
2177 * Also stores the IDs in the link cache.
2178 *
2179 * WARNING: do not use this function on arbitrary user-supplied titles!
2180 * On heavily-used templates it will max out the memory.
2181 *
2182 * @param string $options may be FOR UPDATE
2183 * @return array the Title objects linking here
2184 */
2185 public function getTemplateLinksTo( $options = '' ) {
2186 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2187 }
2188
2189 /**
2190 * Get an array of Title objects referring to non-existent articles linked from this page
2191 *
2192 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2193 * @param string $options may be FOR UPDATE
2194 * @return array the Title objects
2195 */
2196 public function getBrokenLinksFrom( $options = '' ) {
2197 if ( $this->getArticleId() == 0 ) {
2198 # All links from article ID 0 are false positives
2199 return array();
2200 }
2201
2202 if ( $options ) {
2203 $db = wfGetDB( DB_MASTER );
2204 } else {
2205 $db = wfGetDB( DB_SLAVE );
2206 }
2207
2208 $res = $db->safeQuery(
2209 "SELECT pl_namespace, pl_title
2210 FROM !
2211 LEFT JOIN !
2212 ON pl_namespace=page_namespace
2213 AND pl_title=page_title
2214 WHERE pl_from=?
2215 AND page_namespace IS NULL
2216 !",
2217 $db->tableName( 'pagelinks' ),
2218 $db->tableName( 'page' ),
2219 $this->getArticleId(),
2220 $options );
2221
2222 $retVal = array();
2223 if ( $db->numRows( $res ) ) {
2224 while ( $row = $db->fetchObject( $res ) ) {
2225 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2226 }
2227 }
2228 $db->freeResult( $res );
2229 return $retVal;
2230 }
2231
2232
2233 /**
2234 * Get a list of URLs to purge from the Squid cache when this
2235 * page changes
2236 *
2237 * @return array the URLs
2238 */
2239 public function getSquidURLs() {
2240 global $wgContLang;
2241
2242 $urls = array(
2243 $this->getInternalURL(),
2244 $this->getInternalURL( 'action=history' )
2245 );
2246
2247 // purge variant urls as well
2248 if($wgContLang->hasVariants()){
2249 $variants = $wgContLang->getVariants();
2250 foreach($variants as $vCode){
2251 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2252 $urls[] = $this->getInternalURL('',$vCode);
2253 }
2254 }
2255
2256 return $urls;
2257 }
2258
2259 public function purgeSquid() {
2260 global $wgUseSquid;
2261 if ( $wgUseSquid ) {
2262 $urls = $this->getSquidURLs();
2263 $u = new SquidUpdate( $urls );
2264 $u->doUpdate();
2265 }
2266 }
2267
2268 /**
2269 * Move this page without authentication
2270 * @param Title &$nt the new page Title
2271 */
2272 public function moveNoAuth( &$nt ) {
2273 return $this->moveTo( $nt, false );
2274 }
2275
2276 /**
2277 * Check whether a given move operation would be valid.
2278 * Returns true if ok, or a message key string for an error message
2279 * if invalid. (Scarrrrry ugly interface this.)
2280 * @param Title &$nt the new title
2281 * @param bool $auth indicates whether $wgUser's permissions
2282 * should be checked
2283 * @return mixed true on success, message name on failure
2284 */
2285 public function isValidMoveOperation( &$nt, $auth = true ) {
2286 if( !$this or !$nt ) {
2287 return 'badtitletext';
2288 }
2289 if( $this->equals( $nt ) ) {
2290 return 'selfmove';
2291 }
2292 if( !$this->isMovable() || !$nt->isMovable() ) {
2293 return 'immobile_namespace';
2294 }
2295
2296 $oldid = $this->getArticleID();
2297 $newid = $nt->getArticleID();
2298
2299 if ( strlen( $nt->getDBkey() ) < 1 ) {
2300 return 'articleexists';
2301 }
2302 if ( ( '' == $this->getDBkey() ) ||
2303 ( !$oldid ) ||
2304 ( '' == $nt->getDBkey() ) ) {
2305 return 'badarticleerror';
2306 }
2307
2308 if ( $auth && (
2309 !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
2310 !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
2311 return 'protectedpage';
2312 }
2313
2314 global $wgUser;
2315 $err = null;
2316 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
2317 return 'hookaborted';
2318 }
2319
2320 # The move is allowed only if (1) the target doesn't exist, or
2321 # (2) the target is a redirect to the source, and has no history
2322 # (so we can undo bad moves right after they're done).
2323
2324 if ( 0 != $newid ) { # Target exists; check for validity
2325 if ( ! $this->isValidMoveTarget( $nt ) ) {
2326 return 'articleexists';
2327 }
2328 } else {
2329 $tp = $nt->getTitleProtection();
2330 if ( $tp and !$wgUser->isAllowed( $tp['pt_create_perm'] ) ) {
2331 return 'cantmove-titleprotected';
2332 }
2333 }
2334 return true;
2335 }
2336
2337 /**
2338 * Move a title to a new location
2339 * @param Title &$nt the new title
2340 * @param bool $auth indicates whether $wgUser's permissions
2341 * should be checked
2342 * @param string $reason The reason for the move
2343 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2344 * Ignored if the user doesn't have the suppressredirect right.
2345 * @return mixed true on success, message name on failure
2346 */
2347 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2348 $err = $this->isValidMoveOperation( $nt, $auth );
2349 if( is_string( $err ) ) {
2350 return $err;
2351 }
2352
2353 $pageid = $this->getArticleID();
2354 if( $nt->exists() ) {
2355 $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2356 $pageCountChange = ($createRedirect ? 0 : -1);
2357 } else { # Target didn't exist, do normal move.
2358 $this->moveToNewTitle( $nt, $reason, $createRedirect );
2359 $pageCountChange = ($createRedirect ? 1 : 0);
2360 }
2361 $redirid = $this->getArticleID();
2362
2363 // Category memberships include a sort key which may be customized.
2364 // If it's left as the default (the page title), we need to update
2365 // the sort key to match the new title.
2366 //
2367 // Be careful to avoid resetting cl_timestamp, which may disturb
2368 // time-based lists on some sites.
2369 //
2370 // Warning -- if the sort key is *explicitly* set to the old title,
2371 // we can't actually distinguish it from a default here, and it'll
2372 // be set to the new title even though it really shouldn't.
2373 // It'll get corrected on the next edit, but resetting cl_timestamp.
2374 $dbw = wfGetDB( DB_MASTER );
2375 $dbw->update( 'categorylinks',
2376 array(
2377 'cl_sortkey' => $nt->getPrefixedText(),
2378 'cl_timestamp=cl_timestamp' ),
2379 array(
2380 'cl_from' => $pageid,
2381 'cl_sortkey' => $this->getPrefixedText() ),
2382 __METHOD__ );
2383
2384 # Update watchlists
2385
2386 $oldnamespace = $this->getNamespace() & ~1;
2387 $newnamespace = $nt->getNamespace() & ~1;
2388 $oldtitle = $this->getDBkey();
2389 $newtitle = $nt->getDBkey();
2390
2391 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2392 WatchedItem::duplicateEntries( $this, $nt );
2393 }
2394
2395 # Update search engine
2396 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2397 $u->doUpdate();
2398 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2399 $u->doUpdate();
2400
2401 # Update site_stats
2402 if( $this->isContentPage() && !$nt->isContentPage() ) {
2403 # No longer a content page
2404 # Not viewed, edited, removing
2405 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2406 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2407 # Now a content page
2408 # Not viewed, edited, adding
2409 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2410 } elseif( $pageCountChange ) {
2411 # Redirect added
2412 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2413 } else {
2414 # Nothing special
2415 $u = false;
2416 }
2417 if( $u )
2418 $u->doUpdate();
2419 # Update message cache for interface messages
2420 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2421 global $wgMessageCache;
2422 $newarticle = new Article( $nt );
2423 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2424 }
2425
2426 global $wgUser;
2427 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2428 return true;
2429 }
2430
2431 /**
2432 * Move page to a title which is at present a redirect to the
2433 * source page
2434 *
2435 * @param Title &$nt the page to move to, which should currently
2436 * be a redirect
2437 * @param string $reason The reason for the move
2438 * @param bool $createRedirect Whether to leave a redirect at the old title.
2439 * Ignored if the user doesn't have the suppressredirect right
2440 */
2441 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2442 global $wgUseSquid, $wgUser;
2443 $fname = 'Title::moveOverExistingRedirect';
2444 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2445
2446 if ( $reason ) {
2447 $comment .= ": $reason";
2448 }
2449
2450 $now = wfTimestampNow();
2451 $newid = $nt->getArticleID();
2452 $oldid = $this->getArticleID();
2453 $dbw = wfGetDB( DB_MASTER );
2454 $linkCache =& LinkCache::singleton();
2455
2456 # Delete the old redirect. We don't save it to history since
2457 # by definition if we've got here it's rather uninteresting.
2458 # We have to remove it so that the next step doesn't trigger
2459 # a conflict on the unique namespace+title index...
2460 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2461
2462 # Save a null revision in the page's history notifying of the move
2463 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2464 $nullRevId = $nullRevision->insertOn( $dbw );
2465
2466 # Change the name of the target page:
2467 $dbw->update( 'page',
2468 /* SET */ array(
2469 'page_touched' => $dbw->timestamp($now),
2470 'page_namespace' => $nt->getNamespace(),
2471 'page_title' => $nt->getDBkey(),
2472 'page_latest' => $nullRevId,
2473 ),
2474 /* WHERE */ array( 'page_id' => $oldid ),
2475 $fname
2476 );
2477 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2478
2479 # Recreate the redirect, this time in the other direction.
2480 if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
2481 {
2482 $mwRedir = MagicWord::get( 'redirect' );
2483 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2484 $redirectArticle = new Article( $this );
2485 $newid = $redirectArticle->insertOn( $dbw );
2486 $redirectRevision = new Revision( array(
2487 'page' => $newid,
2488 'comment' => $comment,
2489 'text' => $redirectText ) );
2490 $redirectRevision->insertOn( $dbw );
2491 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2492 $linkCache->clearLink( $this->getPrefixedDBkey() );
2493
2494 # Now, we record the link from the redirect to the new title.
2495 # It should have no other outgoing links...
2496 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2497 $dbw->insert( 'pagelinks',
2498 array(
2499 'pl_from' => $newid,
2500 'pl_namespace' => $nt->getNamespace(),
2501 'pl_title' => $nt->getDBkey() ),
2502 $fname );
2503 }
2504
2505 # Log the move
2506 $log = new LogPage( 'move' );
2507 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2508
2509 # Purge squid
2510 if ( $wgUseSquid ) {
2511 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2512 $u = new SquidUpdate( $urls );
2513 $u->doUpdate();
2514 }
2515 }
2516
2517 /**
2518 * Move page to non-existing title.
2519 * @param Title &$nt the new Title
2520 * @param string $reason The reason for the move
2521 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2522 * Ignored if the user doesn't have the suppressredirect right
2523 */
2524 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2525 global $wgUseSquid, $wgUser;
2526 $fname = 'MovePageForm::moveToNewTitle';
2527 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2528 if ( $reason ) {
2529 $comment .= ": $reason";
2530 }
2531
2532 $newid = $nt->getArticleID();
2533 $oldid = $this->getArticleID();
2534 $dbw = wfGetDB( DB_MASTER );
2535 $now = $dbw->timestamp();
2536 $linkCache =& LinkCache::singleton();
2537
2538 # Save a null revision in the page's history notifying of the move
2539 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2540 $nullRevId = $nullRevision->insertOn( $dbw );
2541
2542 # Rename cur entry
2543 $dbw->update( 'page',
2544 /* SET */ array(
2545 'page_touched' => $now,
2546 'page_namespace' => $nt->getNamespace(),
2547 'page_title' => $nt->getDBkey(),
2548 'page_latest' => $nullRevId,
2549 ),
2550 /* WHERE */ array( 'page_id' => $oldid ),
2551 $fname
2552 );
2553
2554 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2555
2556 if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
2557 {
2558 # Insert redirect
2559 $mwRedir = MagicWord::get( 'redirect' );
2560 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2561 $redirectArticle = new Article( $this );
2562 $newid = $redirectArticle->insertOn( $dbw );
2563 $redirectRevision = new Revision( array(
2564 'page' => $newid,
2565 'comment' => $comment,
2566 'text' => $redirectText ) );
2567 $redirectRevision->insertOn( $dbw );
2568 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2569 $linkCache->clearLink( $this->getPrefixedDBkey() );
2570 # Record the just-created redirect's linking to the page
2571 $dbw->insert( 'pagelinks',
2572 array(
2573 'pl_from' => $newid,
2574 'pl_namespace' => $nt->getNamespace(),
2575 'pl_title' => $nt->getDBkey() ),
2576 $fname );
2577 }
2578
2579 # Log the move
2580 $log = new LogPage( 'move' );
2581 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2582
2583 # Purge caches as per article creation
2584 Article::onArticleCreate( $nt );
2585
2586 # Purge old title from squid
2587 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2588 $this->purgeSquid();
2589 }
2590
2591 /**
2592 * Checks if $this can be moved to a given Title
2593 * - Selects for update, so don't call it unless you mean business
2594 *
2595 * @param Title &$nt the new title to check
2596 */
2597 public function isValidMoveTarget( $nt ) {
2598
2599 $fname = 'Title::isValidMoveTarget';
2600 $dbw = wfGetDB( DB_MASTER );
2601
2602 # Is it a redirect?
2603 $id = $nt->getArticleID();
2604 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2605 array( 'page_is_redirect','old_text','old_flags' ),
2606 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2607 $fname, 'FOR UPDATE' );
2608
2609 if ( !$obj || 0 == $obj->page_is_redirect ) {
2610 # Not a redirect
2611 wfDebug( __METHOD__ . ": not a redirect\n" );
2612 return false;
2613 }
2614 $text = Revision::getRevisionText( $obj );
2615
2616 # Does the redirect point to the source?
2617 # Or is it a broken self-redirect, usually caused by namespace collisions?
2618 $m = array();
2619 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2620 $redirTitle = Title::newFromText( $m[1] );
2621 if( !is_object( $redirTitle ) ||
2622 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2623 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2624 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2625 return false;
2626 }
2627 } else {
2628 # Fail safe
2629 wfDebug( __METHOD__ . ": failsafe\n" );
2630 return false;
2631 }
2632
2633 # Does the article have a history?
2634 $row = $dbw->selectRow( array( 'page', 'revision'),
2635 array( 'rev_id' ),
2636 array( 'page_namespace' => $nt->getNamespace(),
2637 'page_title' => $nt->getDBkey(),
2638 'page_id=rev_page AND page_latest != rev_id'
2639 ), $fname, 'FOR UPDATE'
2640 );
2641
2642 # Return true if there was no history
2643 return $row === false;
2644 }
2645
2646 /**
2647 * Can this title be added to a user's watchlist?
2648 *
2649 * @return bool
2650 */
2651 public function isWatchable() {
2652 return !$this->isExternal()
2653 && Namespace::isWatchable( $this->getNamespace() );
2654 }
2655
2656 /**
2657 * Get categories to which this Title belongs and return an array of
2658 * categories' names.
2659 *
2660 * @return array an array of parents in the form:
2661 * $parent => $currentarticle
2662 */
2663 public function getParentCategories() {
2664 global $wgContLang;
2665
2666 $titlekey = $this->getArticleId();
2667 $dbr = wfGetDB( DB_SLAVE );
2668 $categorylinks = $dbr->tableName( 'categorylinks' );
2669
2670 # NEW SQL
2671 $sql = "SELECT * FROM $categorylinks"
2672 ." WHERE cl_from='$titlekey'"
2673 ." AND cl_from <> '0'"
2674 ." ORDER BY cl_sortkey";
2675
2676 $res = $dbr->query ( $sql ) ;
2677
2678 if($dbr->numRows($res) > 0) {
2679 while ( $x = $dbr->fetchObject ( $res ) )
2680 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2681 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2682 $dbr->freeResult ( $res ) ;
2683 } else {
2684 $data = array();
2685 }
2686 return $data;
2687 }
2688
2689 /**
2690 * Get a tree of parent categories
2691 * @param array $children an array with the children in the keys, to check for circular refs
2692 * @return array
2693 */
2694 public function getParentCategoryTree( $children = array() ) {
2695 $parents = $this->getParentCategories();
2696
2697 if($parents != '') {
2698 foreach($parents as $parent => $current) {
2699 if ( array_key_exists( $parent, $children ) ) {
2700 # Circular reference
2701 $stack[$parent] = array();
2702 } else {
2703 $nt = Title::newFromText($parent);
2704 if ( $nt ) {
2705 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2706 }
2707 }
2708 }
2709 return $stack;
2710 } else {
2711 return array();
2712 }
2713 }
2714
2715
2716 /**
2717 * Get an associative array for selecting this title from
2718 * the "page" table
2719 *
2720 * @return array
2721 */
2722 public function pageCond() {
2723 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2724 }
2725
2726 /**
2727 * Get the revision ID of the previous revision
2728 *
2729 * @param integer $revision Revision ID. Get the revision that was before this one.
2730 * @return integer $oldrevision|false
2731 */
2732 public function getPreviousRevisionID( $revision ) {
2733 $dbr = wfGetDB( DB_SLAVE );
2734 return $dbr->selectField( 'revision', 'rev_id',
2735 'rev_page=' . intval( $this->getArticleId() ) .
2736 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2737 }
2738
2739 /**
2740 * Get the revision ID of the next revision
2741 *
2742 * @param integer $revision Revision ID. Get the revision that was after this one.
2743 * @return integer $oldrevision|false
2744 */
2745 public function getNextRevisionID( $revision ) {
2746 $dbr = wfGetDB( DB_SLAVE );
2747 return $dbr->selectField( 'revision', 'rev_id',
2748 'rev_page=' . intval( $this->getArticleId() ) .
2749 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2750 }
2751
2752 /**
2753 * Get the number of revisions between the given revision IDs.
2754 *
2755 * @param integer $old Revision ID.
2756 * @param integer $new Revision ID.
2757 * @return integer Number of revisions between these IDs.
2758 */
2759 public function countRevisionsBetween( $old, $new ) {
2760 $dbr = wfGetDB( DB_SLAVE );
2761 return $dbr->selectField( 'revision', 'count(*)',
2762 'rev_page = ' . intval( $this->getArticleId() ) .
2763 ' AND rev_id > ' . intval( $old ) .
2764 ' AND rev_id < ' . intval( $new ) );
2765 }
2766
2767 /**
2768 * Compare with another title.
2769 *
2770 * @param Title $title
2771 * @return bool
2772 */
2773 public function equals( $title ) {
2774 // Note: === is necessary for proper matching of number-like titles.
2775 return $this->getInterwiki() === $title->getInterwiki()
2776 && $this->getNamespace() == $title->getNamespace()
2777 && $this->getDBkey() === $title->getDBkey();
2778 }
2779
2780 /**
2781 * Return a string representation of this title
2782 *
2783 * @return string
2784 */
2785 public function __toString() {
2786 return $this->getPrefixedText();
2787 }
2788
2789 /**
2790 * Check if page exists
2791 * @return bool
2792 */
2793 public function exists() {
2794 return $this->getArticleId() != 0;
2795 }
2796
2797 /**
2798 * Do we know that this title definitely exists, or should we otherwise
2799 * consider that it exists?
2800 *
2801 * @return bool
2802 */
2803 public function isAlwaysKnown() {
2804 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
2805 // the full l10n of that language to be loaded. That takes much memory and
2806 // isn't needed. So we strip the language part away.
2807 // Also, extension messages which are not loaded, are shown as red, because
2808 // we don't call MessageCache::loadAllMessages.
2809 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
2810 return $this->isExternal()
2811 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
2812 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
2813 }
2814
2815 /**
2816 * Update page_touched timestamps and send squid purge messages for
2817 * pages linking to this title. May be sent to the job queue depending
2818 * on the number of links. Typically called on create and delete.
2819 */
2820 public function touchLinks() {
2821 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2822 $u->doUpdate();
2823
2824 if ( $this->getNamespace() == NS_CATEGORY ) {
2825 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2826 $u->doUpdate();
2827 }
2828 }
2829
2830 /**
2831 * Get the last touched timestamp
2832 */
2833 public function getTouched() {
2834 $dbr = wfGetDB( DB_SLAVE );
2835 $touched = $dbr->selectField( 'page', 'page_touched',
2836 array(
2837 'page_namespace' => $this->getNamespace(),
2838 'page_title' => $this->getDBkey()
2839 ), __METHOD__
2840 );
2841 return $touched;
2842 }
2843
2844 public function trackbackURL() {
2845 global $wgTitle, $wgScriptPath, $wgServer;
2846
2847 return "$wgServer$wgScriptPath/trackback.php?article="
2848 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2849 }
2850
2851 public function trackbackRDF() {
2852 $url = htmlspecialchars($this->getFullURL());
2853 $title = htmlspecialchars($this->getText());
2854 $tburl = $this->trackbackURL();
2855
2856 return "
2857 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2858 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2859 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2860 <rdf:Description
2861 rdf:about=\"$url\"
2862 dc:identifier=\"$url\"
2863 dc:title=\"$title\"
2864 trackback:ping=\"$tburl\" />
2865 </rdf:RDF>";
2866 }
2867
2868 /**
2869 * Generate strings used for xml 'id' names in monobook tabs
2870 * @return string
2871 */
2872 public function getNamespaceKey() {
2873 global $wgContLang;
2874 switch ($this->getNamespace()) {
2875 case NS_MAIN:
2876 case NS_TALK:
2877 return 'nstab-main';
2878 case NS_USER:
2879 case NS_USER_TALK:
2880 return 'nstab-user';
2881 case NS_MEDIA:
2882 return 'nstab-media';
2883 case NS_SPECIAL:
2884 return 'nstab-special';
2885 case NS_PROJECT:
2886 case NS_PROJECT_TALK:
2887 return 'nstab-project';
2888 case NS_IMAGE:
2889 case NS_IMAGE_TALK:
2890 return 'nstab-image';
2891 case NS_MEDIAWIKI:
2892 case NS_MEDIAWIKI_TALK:
2893 return 'nstab-mediawiki';
2894 case NS_TEMPLATE:
2895 case NS_TEMPLATE_TALK:
2896 return 'nstab-template';
2897 case NS_HELP:
2898 case NS_HELP_TALK:
2899 return 'nstab-help';
2900 case NS_CATEGORY:
2901 case NS_CATEGORY_TALK:
2902 return 'nstab-category';
2903 default:
2904 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2905 }
2906 }
2907
2908 /**
2909 * Returns true if this title resolves to the named special page
2910 * @param string $name The special page name
2911 */
2912 public function isSpecial( $name ) {
2913 if ( $this->getNamespace() == NS_SPECIAL ) {
2914 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2915 if ( $name == $thisName ) {
2916 return true;
2917 }
2918 }
2919 return false;
2920 }
2921
2922 /**
2923 * If the Title refers to a special page alias which is not the local default,
2924 * returns a new Title which points to the local default. Otherwise, returns $this.
2925 */
2926 public function fixSpecialName() {
2927 if ( $this->getNamespace() == NS_SPECIAL ) {
2928 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2929 if ( $canonicalName ) {
2930 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2931 if ( $localName != $this->mDbkeyform ) {
2932 return Title::makeTitle( NS_SPECIAL, $localName );
2933 }
2934 }
2935 }
2936 return $this;
2937 }
2938
2939 /**
2940 * Is this Title in a namespace which contains content?
2941 * In other words, is this a content page, for the purposes of calculating
2942 * statistics, etc?
2943 *
2944 * @return bool
2945 */
2946 public function isContentPage() {
2947 return Namespace::isContent( $this->getNamespace() );
2948 }
2949
2950 }