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