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