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