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