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