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