2281fa8bff61e6ef7f1eb78f4d67f1246f1bb213
[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 global $wgContLang;
1100 $fname = 'Title::userCan';
1101 wfProfileIn( $fname );
1102
1103 $errors = array();
1104
1105 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1106 return $result ? array() : array( array( 'badaccess-group0' ) );
1107 }
1108
1109 if( NS_SPECIAL == $this->mNamespace ) {
1110 $errors[] = array('ns-specialprotected');
1111 }
1112
1113 if ( $this->isNamespaceProtected() ) {
1114 $errors[] = (NS_MEDIAWIKI == $this->mNamespace ? array('protectedinterface') : array( 'namespaceprotected', $wgContLang->getNSText( $this->mNamespace ) ) );
1115 }
1116
1117 if( $this->mDbkeyform == '_' ) {
1118 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1119 $errors[] = array('badaccess-group0');
1120 }
1121
1122 # protect css/js subpages of user pages
1123 # XXX: this might be better using restrictions
1124 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1125 if( $this->isCssJsSubpage()
1126 && !$user->isAllowed('editinterface')
1127 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
1128 $errors[] = array('customcssjsprotected');
1129 }
1130
1131 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1132 # We /could/ use the protection level on the source page, but it's fairly ugly
1133 # as we have to establish a precedence hierarchy for pages included by multiple
1134 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1135 # as they could remove the protection anyway.
1136 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1137 # Cascading protection depends on more than this page...
1138 # Several cascading protected pages may include this page...
1139 # Check each cascading level
1140 # This is only for protection restrictions, not for all actions
1141 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1142 foreach( $restrictions[$action] as $right ) {
1143 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1144 if( '' != $right && !$user->isAllowed( $right ) ) {
1145 $pages = '';
1146 foreach( $cascadeSources as $id => $page )
1147 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1148 $errors[] = array( 'cascadeprotected', array_len( $cascadingSources ), $pages );
1149 }
1150 }
1151 }
1152 }
1153
1154 foreach( $this->getRestrictions($action) as $right ) {
1155 // Backwards compatibility, rewrite sysop -> protect
1156 if ( $right == 'sysop' ) {
1157 $right = 'protect';
1158 }
1159 if( '' != $right && !$user->isAllowed( $right ) ) {
1160 $errors[] = array( 'protectedpagetext' );
1161 }
1162 }
1163
1164 if( $action == 'create' ) {
1165 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1166 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1167 $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
1168 }
1169 } elseif( $action == 'move' &&
1170 !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1171 $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
1172 } else if ( !$user->isAllowed( $action ) ) {
1173 $return = null;
1174 $groups = array();
1175 global $wgGroupPermissions;
1176 foreach( $wgGroupPermissions as $key => $value ) {
1177 if( isset( $value[$action] ) && $value[$action] == true ) {
1178 $groupName = User::getGroupName( $key );
1179 $groupPage = User::getGroupPage( $key );
1180 if( $groupPage ) {
1181 $skin = $user->getSkin();
1182 $groups[] = $skin->makeLinkObj( $groupPage, $groupName );
1183 } else {
1184 $groups[] = $groupName;
1185 }
1186 }
1187 }
1188 $n = count( $groups );
1189 $groups = implode( ', ', $groups );
1190 switch( $n ) {
1191 case 0:
1192 case 1:
1193 case 2:
1194 $return = array( "badaccess-group$n", $groups );
1195 break;
1196 default:
1197 $return = array( 'badaccess-groups', $groups );
1198 }
1199 $errors[] = $return;
1200 }
1201
1202 wfProfileOut( $fname );
1203 return $errors;
1204 }
1205
1206 /**
1207 * Can $wgUser edit this page?
1208 * @return boolean
1209 * @deprecated use userCan('edit')
1210 */
1211 public function userCanEdit( $doExpensiveQueries = true ) {
1212 return $this->userCan( 'edit', $doExpensiveQueries );
1213 }
1214
1215 /**
1216 * Can $wgUser create this page?
1217 * @return boolean
1218 * @deprecated use userCan('create')
1219 */
1220 public function userCanCreate( $doExpensiveQueries = true ) {
1221 return $this->userCan( 'create', $doExpensiveQueries );
1222 }
1223
1224 /**
1225 * Can $wgUser move this page?
1226 * @return boolean
1227 * @deprecated use userCan('move')
1228 */
1229 public function userCanMove( $doExpensiveQueries = true ) {
1230 return $this->userCan( 'move', $doExpensiveQueries );
1231 }
1232
1233 /**
1234 * Would anybody with sufficient privileges be able to move this page?
1235 * Some pages just aren't movable.
1236 *
1237 * @return boolean
1238 */
1239 public function isMovable() {
1240 return Namespace::isMovable( $this->getNamespace() )
1241 && $this->getInterwiki() == '';
1242 }
1243
1244 /**
1245 * Can $wgUser read this page?
1246 * @return boolean
1247 * @todo fold these checks into userCan()
1248 */
1249 public function userCanRead() {
1250 global $wgUser;
1251
1252 $result = null;
1253 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1254 if ( $result !== null ) {
1255 return $result;
1256 }
1257
1258 if( $wgUser->isAllowed( 'read' ) ) {
1259 return true;
1260 } else {
1261 global $wgWhitelistRead;
1262
1263 /**
1264 * Always grant access to the login page.
1265 * Even anons need to be able to log in.
1266 */
1267 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1268 return true;
1269 }
1270
1271 /**
1272 * Check for explicit whitelisting
1273 */
1274 $name = $this->getPrefixedText();
1275 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead, true ) )
1276 return true;
1277
1278 /**
1279 * Old settings might have the title prefixed with
1280 * a colon for main-namespace pages
1281 */
1282 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1283 if( in_array( ':' . $name, $wgWhitelistRead ) )
1284 return true;
1285 }
1286
1287 /**
1288 * If it's a special page, ditch the subpage bit
1289 * and check again
1290 */
1291 if( $this->getNamespace() == NS_SPECIAL ) {
1292 $name = $this->getText();
1293 list( $name, $subpage ) = SpecialPage::resolveAliasWithSubpage( $name );
1294 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1295 if( in_array( $pure, $wgWhitelistRead, true ) )
1296 return true;
1297 }
1298
1299 }
1300 return false;
1301 }
1302
1303 /**
1304 * Is this a talk page of some sort?
1305 * @return bool
1306 */
1307 public function isTalkPage() {
1308 return Namespace::isTalk( $this->getNamespace() );
1309 }
1310
1311 /**
1312 * Is this a subpage?
1313 * @return bool
1314 */
1315 public function isSubpage() {
1316 global $wgNamespacesWithSubpages;
1317
1318 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1319 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1320 } else {
1321 return false;
1322 }
1323 }
1324
1325 /**
1326 * Could this page contain custom CSS or JavaScript, based
1327 * on the title?
1328 *
1329 * @return bool
1330 */
1331 public function isCssOrJsPage() {
1332 return $this->mNamespace == NS_MEDIAWIKI
1333 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1334 }
1335
1336 /**
1337 * Is this a .css or .js subpage of a user page?
1338 * @return bool
1339 */
1340 public function isCssJsSubpage() {
1341 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1342 }
1343 /**
1344 * Is this a *valid* .css or .js subpage of a user page?
1345 * Check that the corresponding skin exists
1346 */
1347 public function isValidCssJsSubpage() {
1348 if ( $this->isCssJsSubpage() ) {
1349 $skinNames = Skin::getSkinNames();
1350 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1351 } else {
1352 return false;
1353 }
1354 }
1355 /**
1356 * Trim down a .css or .js subpage title to get the corresponding skin name
1357 */
1358 public function getSkinFromCssJsSubpage() {
1359 $subpage = explode( '/', $this->mTextform );
1360 $subpage = $subpage[ count( $subpage ) - 1 ];
1361 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1362 }
1363 /**
1364 * Is this a .css subpage of a user page?
1365 * @return bool
1366 */
1367 public function isCssSubpage() {
1368 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1369 }
1370 /**
1371 * Is this a .js subpage of a user page?
1372 * @return bool
1373 */
1374 public function isJsSubpage() {
1375 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1376 }
1377 /**
1378 * Protect css/js subpages of user pages: can $wgUser edit
1379 * this page?
1380 *
1381 * @return boolean
1382 * @todo XXX: this might be better using restrictions
1383 */
1384 public function userCanEditCssJsSubpage() {
1385 global $wgUser;
1386 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1387 }
1388
1389 /**
1390 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1391 *
1392 * @return bool If the page is subject to cascading restrictions.
1393 */
1394 public function isCascadeProtected() {
1395 list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false );
1396 return ( $sources > 0 );
1397 }
1398
1399 /**
1400 * Cascading protection: Get the source of any cascading restrictions on this page.
1401 *
1402 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1403 * @return array( mixed title array, restriction array)
1404 * 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.
1405 * The restriction array is an array of each type, each of which contains an array of unique groups
1406 */
1407 public function getCascadeProtectionSources( $get_pages = true ) {
1408 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1409
1410 # Define our dimension of restrictions types
1411 $pagerestrictions = array();
1412 foreach( $wgRestrictionTypes as $action )
1413 $pagerestrictions[$action] = array();
1414
1415 if (!$wgEnableCascadingProtection)
1416 return array( false, $pagerestrictions );
1417
1418 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1419 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1420 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1421 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1422 }
1423
1424 wfProfileIn( __METHOD__ );
1425
1426 $dbr = wfGetDb( DB_SLAVE );
1427
1428 if ( $this->getNamespace() == NS_IMAGE ) {
1429 $tables = array ('imagelinks', 'page_restrictions');
1430 $where_clauses = array(
1431 'il_to' => $this->getDBkey(),
1432 'il_from=pr_page',
1433 'pr_cascade' => 1 );
1434 } else {
1435 $tables = array ('templatelinks', 'page_restrictions');
1436 $where_clauses = array(
1437 'tl_namespace' => $this->getNamespace(),
1438 'tl_title' => $this->getDBkey(),
1439 'tl_from=pr_page',
1440 'pr_cascade' => 1 );
1441 }
1442
1443 if ( $get_pages ) {
1444 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1445 $where_clauses[] = 'page_id=pr_page';
1446 $tables[] = 'page';
1447 } else {
1448 $cols = array( 'pr_expiry' );
1449 }
1450
1451 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1452
1453 $sources = $get_pages ? array() : false;
1454 $now = wfTimestampNow();
1455 $purgeExpired = false;
1456
1457 while( $row = $dbr->fetchObject( $res ) ) {
1458 $expiry = Block::decodeExpiry( $row->pr_expiry );
1459 if( $expiry > $now ) {
1460 if ($get_pages) {
1461 $page_id = $row->pr_page;
1462 $page_ns = $row->page_namespace;
1463 $page_title = $row->page_title;
1464 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1465 # Add groups needed for each restriction type if its not already there
1466 # Make sure this restriction type still exists
1467 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1468 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1469 }
1470 } else {
1471 $sources = true;
1472 }
1473 } else {
1474 // Trigger lazy purge of expired restrictions from the db
1475 $purgeExpired = true;
1476 }
1477 }
1478 if( $purgeExpired ) {
1479 Title::purgeExpiredRestrictions();
1480 }
1481
1482 wfProfileOut( __METHOD__ );
1483
1484 if ( $get_pages ) {
1485 $this->mCascadeSources = $sources;
1486 $this->mCascadingRestrictions = $pagerestrictions;
1487 } else {
1488 $this->mHasCascadingRestrictions = $sources;
1489 }
1490
1491 return array( $sources, $pagerestrictions );
1492 }
1493
1494 function areRestrictionsCascading() {
1495 if (!$this->mRestrictionsLoaded) {
1496 $this->loadRestrictions();
1497 }
1498
1499 return $this->mCascadeRestriction;
1500 }
1501
1502 /**
1503 * Loads a string into mRestrictions array
1504 * @param resource $res restrictions as an SQL result.
1505 */
1506 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1507 $dbr = wfGetDb( DB_SLAVE );
1508
1509 $this->mRestrictions['edit'] = array();
1510 $this->mRestrictions['move'] = array();
1511
1512 # Backwards-compatibility: also load the restrictions from the page record (old format).
1513
1514 if ( $oldFashionedRestrictions == NULL ) {
1515 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1516 }
1517
1518 if ($oldFashionedRestrictions != '') {
1519
1520 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1521 $temp = explode( '=', trim( $restrict ) );
1522 if(count($temp) == 1) {
1523 // old old format should be treated as edit/move restriction
1524 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1525 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1526 } else {
1527 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1528 }
1529 }
1530
1531 $this->mOldRestrictions = true;
1532 $this->mCascadeRestriction = false;
1533 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1534
1535 }
1536
1537 if( $dbr->numRows( $res ) ) {
1538 # Current system - load second to make them override.
1539 $now = wfTimestampNow();
1540 $purgeExpired = false;
1541
1542 while ($row = $dbr->fetchObject( $res ) ) {
1543 # Cycle through all the restrictions.
1544
1545 // This code should be refactored, now that it's being used more generally,
1546 // But I don't really see any harm in leaving it in Block for now -werdna
1547 $expiry = Block::decodeExpiry( $row->pr_expiry );
1548
1549 // Only apply the restrictions if they haven't expired!
1550 if ( !$expiry || $expiry > $now ) {
1551 $this->mRestrictionsExpiry = $expiry;
1552 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1553
1554 $this->mCascadeRestriction |= $row->pr_cascade;
1555 } else {
1556 // Trigger a lazy purge of expired restrictions
1557 $purgeExpired = true;
1558 }
1559 }
1560
1561 if( $purgeExpired ) {
1562 Title::purgeExpiredRestrictions();
1563 }
1564 }
1565
1566 $this->mRestrictionsLoaded = true;
1567 }
1568
1569 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1570 if( !$this->mRestrictionsLoaded ) {
1571 $dbr = wfGetDB( DB_SLAVE );
1572
1573 $res = $dbr->select( 'page_restrictions', '*',
1574 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1575
1576 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1577 }
1578 }
1579
1580 /**
1581 * Purge expired restrictions from the page_restrictions table
1582 */
1583 static function purgeExpiredRestrictions() {
1584 $dbw = wfGetDB( DB_MASTER );
1585 $dbw->delete( 'page_restrictions',
1586 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1587 __METHOD__ );
1588 }
1589
1590 /**
1591 * Accessor/initialisation for mRestrictions
1592 *
1593 * @param string $action action that permission needs to be checked for
1594 * @return array the array of groups allowed to edit this article
1595 */
1596 public function getRestrictions( $action ) {
1597 if( $this->exists() ) {
1598 if( !$this->mRestrictionsLoaded ) {
1599 $this->loadRestrictions();
1600 }
1601 return isset( $this->mRestrictions[$action] )
1602 ? $this->mRestrictions[$action]
1603 : array();
1604 } else {
1605 return array();
1606 }
1607 }
1608
1609 /**
1610 * Is there a version of this page in the deletion archive?
1611 * @return int the number of archived revisions
1612 */
1613 public function isDeleted() {
1614 $fname = 'Title::isDeleted';
1615 if ( $this->getNamespace() < 0 ) {
1616 $n = 0;
1617 } else {
1618 $dbr = wfGetDB( DB_SLAVE );
1619 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1620 'ar_title' => $this->getDBkey() ), $fname );
1621 if( $this->getNamespace() == NS_IMAGE ) {
1622 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1623 array( 'fa_name' => $this->getDBkey() ), $fname );
1624 }
1625 }
1626 return (int)$n;
1627 }
1628
1629 /**
1630 * Get the article ID for this Title from the link cache,
1631 * adding it if necessary
1632 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1633 * for update
1634 * @return int the ID
1635 */
1636 public function getArticleID( $flags = 0 ) {
1637 $linkCache =& LinkCache::singleton();
1638 if ( $flags & GAID_FOR_UPDATE ) {
1639 $oldUpdate = $linkCache->forUpdate( true );
1640 $this->mArticleID = $linkCache->addLinkObj( $this );
1641 $linkCache->forUpdate( $oldUpdate );
1642 } else {
1643 if ( -1 == $this->mArticleID ) {
1644 $this->mArticleID = $linkCache->addLinkObj( $this );
1645 }
1646 }
1647 return $this->mArticleID;
1648 }
1649
1650 public function getLatestRevID() {
1651 if ($this->mLatestID !== false)
1652 return $this->mLatestID;
1653
1654 $db = wfGetDB(DB_SLAVE);
1655 return $this->mLatestID = $db->selectField( 'revision',
1656 "max(rev_id)",
1657 array('rev_page' => $this->getArticleID()),
1658 'Title::getLatestRevID' );
1659 }
1660
1661 /**
1662 * This clears some fields in this object, and clears any associated
1663 * keys in the "bad links" section of the link cache.
1664 *
1665 * - This is called from Article::insertNewArticle() to allow
1666 * loading of the new page_id. It's also called from
1667 * Article::doDeleteArticle()
1668 *
1669 * @param int $newid the new Article ID
1670 */
1671 public function resetArticleID( $newid ) {
1672 $linkCache =& LinkCache::singleton();
1673 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1674
1675 if ( 0 == $newid ) { $this->mArticleID = -1; }
1676 else { $this->mArticleID = $newid; }
1677 $this->mRestrictionsLoaded = false;
1678 $this->mRestrictions = array();
1679 }
1680
1681 /**
1682 * Updates page_touched for this page; called from LinksUpdate.php
1683 * @return bool true if the update succeded
1684 */
1685 public function invalidateCache() {
1686 global $wgUseFileCache;
1687
1688 if ( wfReadOnly() ) {
1689 return;
1690 }
1691
1692 $dbw = wfGetDB( DB_MASTER );
1693 $success = $dbw->update( 'page',
1694 array( /* SET */
1695 'page_touched' => $dbw->timestamp()
1696 ), array( /* WHERE */
1697 'page_namespace' => $this->getNamespace() ,
1698 'page_title' => $this->getDBkey()
1699 ), 'Title::invalidateCache'
1700 );
1701
1702 if ($wgUseFileCache) {
1703 $cache = new HTMLFileCache($this);
1704 @unlink($cache->fileCacheName());
1705 }
1706
1707 return $success;
1708 }
1709
1710 /**
1711 * Prefix some arbitrary text with the namespace or interwiki prefix
1712 * of this object
1713 *
1714 * @param string $name the text
1715 * @return string the prefixed text
1716 * @private
1717 */
1718 /* private */ function prefix( $name ) {
1719 $p = '';
1720 if ( '' != $this->mInterwiki ) {
1721 $p = $this->mInterwiki . ':';
1722 }
1723 if ( 0 != $this->mNamespace ) {
1724 $p .= $this->getNsText() . ':';
1725 }
1726 return $p . $name;
1727 }
1728
1729 /**
1730 * Secure and split - main initialisation function for this object
1731 *
1732 * Assumes that mDbkeyform has been set, and is urldecoded
1733 * and uses underscores, but not otherwise munged. This function
1734 * removes illegal characters, splits off the interwiki and
1735 * namespace prefixes, sets the other forms, and canonicalizes
1736 * everything.
1737 * @return bool true on success
1738 */
1739 private function secureAndSplit() {
1740 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1741
1742 # Initialisation
1743 static $rxTc = false;
1744 if( !$rxTc ) {
1745 # % is needed as well
1746 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1747 }
1748
1749 $this->mInterwiki = $this->mFragment = '';
1750 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1751
1752 $dbkey = $this->mDbkeyform;
1753
1754 # Strip Unicode bidi override characters.
1755 # Sometimes they slip into cut-n-pasted page titles, where the
1756 # override chars get included in list displays.
1757 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1758 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1759
1760 # Clean up whitespace
1761 #
1762 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1763 $dbkey = trim( $dbkey, '_' );
1764
1765 if ( '' == $dbkey ) {
1766 return false;
1767 }
1768
1769 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1770 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1771 return false;
1772 }
1773
1774 $this->mDbkeyform = $dbkey;
1775
1776 # Initial colon indicates main namespace rather than specified default
1777 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1778 if ( ':' == $dbkey{0} ) {
1779 $this->mNamespace = NS_MAIN;
1780 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1781 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
1782 }
1783
1784 # Namespace or interwiki prefix
1785 $firstPass = true;
1786 do {
1787 $m = array();
1788 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1789 $p = $m[1];
1790 if ( $ns = $wgContLang->getNsIndex( $p )) {
1791 # Ordinary namespace
1792 $dbkey = $m[2];
1793 $this->mNamespace = $ns;
1794 } elseif( $this->getInterwikiLink( $p ) ) {
1795 if( !$firstPass ) {
1796 # Can't make a local interwiki link to an interwiki link.
1797 # That's just crazy!
1798 return false;
1799 }
1800
1801 # Interwiki link
1802 $dbkey = $m[2];
1803 $this->mInterwiki = $wgContLang->lc( $p );
1804
1805 # Redundant interwiki prefix to the local wiki
1806 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1807 if( $dbkey == '' ) {
1808 # Can't have an empty self-link
1809 return false;
1810 }
1811 $this->mInterwiki = '';
1812 $firstPass = false;
1813 # Do another namespace split...
1814 continue;
1815 }
1816
1817 # If there's an initial colon after the interwiki, that also
1818 # resets the default namespace
1819 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1820 $this->mNamespace = NS_MAIN;
1821 $dbkey = substr( $dbkey, 1 );
1822 }
1823 }
1824 # If there's no recognized interwiki or namespace,
1825 # then let the colon expression be part of the title.
1826 }
1827 break;
1828 } while( true );
1829
1830 # We already know that some pages won't be in the database!
1831 #
1832 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1833 $this->mArticleID = 0;
1834 }
1835 $fragment = strstr( $dbkey, '#' );
1836 if ( false !== $fragment ) {
1837 $this->setFragment( $fragment );
1838 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1839 # remove whitespace again: prevents "Foo_bar_#"
1840 # becoming "Foo_bar_"
1841 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1842 }
1843
1844 # Reject illegal characters.
1845 #
1846 if( preg_match( $rxTc, $dbkey ) ) {
1847 return false;
1848 }
1849
1850 /**
1851 * Pages with "/./" or "/../" appearing in the URLs will
1852 * often be unreachable due to the way web browsers deal
1853 * with 'relative' URLs. Forbid them explicitly.
1854 */
1855 if ( strpos( $dbkey, '.' ) !== false &&
1856 ( $dbkey === '.' || $dbkey === '..' ||
1857 strpos( $dbkey, './' ) === 0 ||
1858 strpos( $dbkey, '../' ) === 0 ||
1859 strpos( $dbkey, '/./' ) !== false ||
1860 strpos( $dbkey, '/../' ) !== false ) )
1861 {
1862 return false;
1863 }
1864
1865 /**
1866 * Magic tilde sequences? Nu-uh!
1867 */
1868 if( strpos( $dbkey, '~~~' ) !== false ) {
1869 return false;
1870 }
1871
1872 /**
1873 * Limit the size of titles to 255 bytes.
1874 * This is typically the size of the underlying database field.
1875 * We make an exception for special pages, which don't need to be stored
1876 * in the database, and may edge over 255 bytes due to subpage syntax
1877 * for long titles, e.g. [[Special:Block/Long name]]
1878 */
1879 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1880 strlen( $dbkey ) > 512 )
1881 {
1882 return false;
1883 }
1884
1885 /**
1886 * Normally, all wiki links are forced to have
1887 * an initial capital letter so [[foo]] and [[Foo]]
1888 * point to the same place.
1889 *
1890 * Don't force it for interwikis, since the other
1891 * site might be case-sensitive.
1892 */
1893 $this->mUserCaseDBKey = $dbkey;
1894 if( $wgCapitalLinks && $this->mInterwiki == '') {
1895 $dbkey = $wgContLang->ucfirst( $dbkey );
1896 }
1897
1898 /**
1899 * Can't make a link to a namespace alone...
1900 * "empty" local links can only be self-links
1901 * with a fragment identifier.
1902 */
1903 if( $dbkey == '' &&
1904 $this->mInterwiki == '' &&
1905 $this->mNamespace != NS_MAIN ) {
1906 return false;
1907 }
1908
1909 // Any remaining initial :s are illegal.
1910 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1911 return false;
1912 }
1913
1914 # Fill fields
1915 $this->mDbkeyform = $dbkey;
1916 $this->mUrlform = wfUrlencode( $dbkey );
1917
1918 $this->mTextform = str_replace( '_', ' ', $dbkey );
1919
1920 return true;
1921 }
1922
1923 /**
1924 * Set the fragment for this title
1925 * This is kind of bad, since except for this rarely-used function, Title objects
1926 * are immutable. The reason this is here is because it's better than setting the
1927 * members directly, which is what Linker::formatComment was doing previously.
1928 *
1929 * @param string $fragment text
1930 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
1931 */
1932 public function setFragment( $fragment ) {
1933 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1934 }
1935
1936 /**
1937 * Get a Title object associated with the talk page of this article
1938 * @return Title the object for the talk page
1939 */
1940 public function getTalkPage() {
1941 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1942 }
1943
1944 /**
1945 * Get a title object associated with the subject page of this
1946 * talk page
1947 *
1948 * @return Title the object for the subject page
1949 */
1950 public function getSubjectPage() {
1951 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1952 }
1953
1954 /**
1955 * Get an array of Title objects linking to this Title
1956 * Also stores the IDs in the link cache.
1957 *
1958 * WARNING: do not use this function on arbitrary user-supplied titles!
1959 * On heavily-used templates it will max out the memory.
1960 *
1961 * @param string $options may be FOR UPDATE
1962 * @return array the Title objects linking here
1963 */
1964 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1965 $linkCache =& LinkCache::singleton();
1966
1967 if ( $options ) {
1968 $db = wfGetDB( DB_MASTER );
1969 } else {
1970 $db = wfGetDB( DB_SLAVE );
1971 }
1972
1973 $res = $db->select( array( 'page', $table ),
1974 array( 'page_namespace', 'page_title', 'page_id' ),
1975 array(
1976 "{$prefix}_from=page_id",
1977 "{$prefix}_namespace" => $this->getNamespace(),
1978 "{$prefix}_title" => $this->getDbKey() ),
1979 'Title::getLinksTo',
1980 $options );
1981
1982 $retVal = array();
1983 if ( $db->numRows( $res ) ) {
1984 while ( $row = $db->fetchObject( $res ) ) {
1985 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1986 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1987 $retVal[] = $titleObj;
1988 }
1989 }
1990 }
1991 $db->freeResult( $res );
1992 return $retVal;
1993 }
1994
1995 /**
1996 * Get an array of Title objects using this Title as a template
1997 * Also stores the IDs in the link cache.
1998 *
1999 * WARNING: do not use this function on arbitrary user-supplied titles!
2000 * On heavily-used templates it will max out the memory.
2001 *
2002 * @param string $options may be FOR UPDATE
2003 * @return array the Title objects linking here
2004 */
2005 public function getTemplateLinksTo( $options = '' ) {
2006 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2007 }
2008
2009 /**
2010 * Get an array of Title objects referring to non-existent articles linked from this page
2011 *
2012 * @param string $options may be FOR UPDATE
2013 * @return array the Title objects
2014 */
2015 public function getBrokenLinksFrom( $options = '' ) {
2016 if ( $options ) {
2017 $db = wfGetDB( DB_MASTER );
2018 } else {
2019 $db = wfGetDB( DB_SLAVE );
2020 }
2021
2022 $res = $db->safeQuery(
2023 "SELECT pl_namespace, pl_title
2024 FROM !
2025 LEFT JOIN !
2026 ON pl_namespace=page_namespace
2027 AND pl_title=page_title
2028 WHERE pl_from=?
2029 AND page_namespace IS NULL
2030 !",
2031 $db->tableName( 'pagelinks' ),
2032 $db->tableName( 'page' ),
2033 $this->getArticleId(),
2034 $options );
2035
2036 $retVal = array();
2037 if ( $db->numRows( $res ) ) {
2038 while ( $row = $db->fetchObject( $res ) ) {
2039 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2040 }
2041 }
2042 $db->freeResult( $res );
2043 return $retVal;
2044 }
2045
2046
2047 /**
2048 * Get a list of URLs to purge from the Squid cache when this
2049 * page changes
2050 *
2051 * @return array the URLs
2052 */
2053 public function getSquidURLs() {
2054 global $wgContLang;
2055
2056 $urls = array(
2057 $this->getInternalURL(),
2058 $this->getInternalURL( 'action=history' )
2059 );
2060
2061 // purge variant urls as well
2062 if($wgContLang->hasVariants()){
2063 $variants = $wgContLang->getVariants();
2064 foreach($variants as $vCode){
2065 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2066 $urls[] = $this->getInternalURL('',$vCode);
2067 }
2068 }
2069
2070 return $urls;
2071 }
2072
2073 public function purgeSquid() {
2074 global $wgUseSquid;
2075 if ( $wgUseSquid ) {
2076 $urls = $this->getSquidURLs();
2077 $u = new SquidUpdate( $urls );
2078 $u->doUpdate();
2079 }
2080 }
2081
2082 /**
2083 * Move this page without authentication
2084 * @param Title &$nt the new page Title
2085 */
2086 public function moveNoAuth( &$nt ) {
2087 return $this->moveTo( $nt, false );
2088 }
2089
2090 /**
2091 * Check whether a given move operation would be valid.
2092 * Returns true if ok, or a message key string for an error message
2093 * if invalid. (Scarrrrry ugly interface this.)
2094 * @param Title &$nt the new title
2095 * @param bool $auth indicates whether $wgUser's permissions
2096 * should be checked
2097 * @return mixed true on success, message name on failure
2098 */
2099 public function isValidMoveOperation( &$nt, $auth = true ) {
2100 if( !$this or !$nt ) {
2101 return 'badtitletext';
2102 }
2103 if( $this->equals( $nt ) ) {
2104 return 'selfmove';
2105 }
2106 if( !$this->isMovable() || !$nt->isMovable() ) {
2107 return 'immobile_namespace';
2108 }
2109
2110 $oldid = $this->getArticleID();
2111 $newid = $nt->getArticleID();
2112
2113 if ( strlen( $nt->getDBkey() ) < 1 ) {
2114 return 'articleexists';
2115 }
2116 if ( ( '' == $this->getDBkey() ) ||
2117 ( !$oldid ) ||
2118 ( '' == $nt->getDBkey() ) ) {
2119 return 'badarticleerror';
2120 }
2121
2122 if ( $auth && (
2123 !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
2124 !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
2125 return 'protectedpage';
2126 }
2127
2128 # The move is allowed only if (1) the target doesn't exist, or
2129 # (2) the target is a redirect to the source, and has no history
2130 # (so we can undo bad moves right after they're done).
2131
2132 if ( 0 != $newid ) { # Target exists; check for validity
2133 if ( ! $this->isValidMoveTarget( $nt ) ) {
2134 return 'articleexists';
2135 }
2136 }
2137 return true;
2138 }
2139
2140 /**
2141 * Move a title to a new location
2142 * @param Title &$nt the new title
2143 * @param bool $auth indicates whether $wgUser's permissions
2144 * should be checked
2145 * @return mixed true on success, message name on failure
2146 */
2147 public function moveTo( &$nt, $auth = true, $reason = '' ) {
2148 $err = $this->isValidMoveOperation( $nt, $auth );
2149 if( is_string( $err ) ) {
2150 return $err;
2151 }
2152
2153 $pageid = $this->getArticleID();
2154 if( $nt->exists() ) {
2155 $this->moveOverExistingRedirect( $nt, $reason );
2156 $pageCountChange = 0;
2157 } else { # Target didn't exist, do normal move.
2158 $this->moveToNewTitle( $nt, $reason );
2159 $pageCountChange = 1;
2160 }
2161 $redirid = $this->getArticleID();
2162
2163 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2164 $dbw = wfGetDB( DB_MASTER );
2165 $categorylinks = $dbw->tableName( 'categorylinks' );
2166 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2167 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2168 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2169 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2170
2171 # Update watchlists
2172
2173 $oldnamespace = $this->getNamespace() & ~1;
2174 $newnamespace = $nt->getNamespace() & ~1;
2175 $oldtitle = $this->getDBkey();
2176 $newtitle = $nt->getDBkey();
2177
2178 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2179 WatchedItem::duplicateEntries( $this, $nt );
2180 }
2181
2182 # Update search engine
2183 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2184 $u->doUpdate();
2185 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2186 $u->doUpdate();
2187
2188 # Update site_stats
2189 if( $this->isContentPage() && !$nt->isContentPage() ) {
2190 # No longer a content page
2191 # Not viewed, edited, removing
2192 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2193 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2194 # Now a content page
2195 # Not viewed, edited, adding
2196 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2197 } elseif( $pageCountChange ) {
2198 # Redirect added
2199 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2200 } else {
2201 # Nothing special
2202 $u = false;
2203 }
2204 if( $u )
2205 $u->doUpdate();
2206
2207 global $wgUser;
2208 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2209 return true;
2210 }
2211
2212 /**
2213 * Move page to a title which is at present a redirect to the
2214 * source page
2215 *
2216 * @param Title &$nt the page to move to, which should currently
2217 * be a redirect
2218 */
2219 private function moveOverExistingRedirect( &$nt, $reason = '' ) {
2220 global $wgUseSquid;
2221 $fname = 'Title::moveOverExistingRedirect';
2222 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2223
2224 if ( $reason ) {
2225 $comment .= ": $reason";
2226 }
2227
2228 $now = wfTimestampNow();
2229 $newid = $nt->getArticleID();
2230 $oldid = $this->getArticleID();
2231 $dbw = wfGetDB( DB_MASTER );
2232 $linkCache =& LinkCache::singleton();
2233
2234 # Delete the old redirect. We don't save it to history since
2235 # by definition if we've got here it's rather uninteresting.
2236 # We have to remove it so that the next step doesn't trigger
2237 # a conflict on the unique namespace+title index...
2238 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2239
2240 # Save a null revision in the page's history notifying of the move
2241 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2242 $nullRevId = $nullRevision->insertOn( $dbw );
2243
2244 # Change the name of the target page:
2245 $dbw->update( 'page',
2246 /* SET */ array(
2247 'page_touched' => $dbw->timestamp($now),
2248 'page_namespace' => $nt->getNamespace(),
2249 'page_title' => $nt->getDBkey(),
2250 'page_latest' => $nullRevId,
2251 ),
2252 /* WHERE */ array( 'page_id' => $oldid ),
2253 $fname
2254 );
2255 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2256
2257 # Recreate the redirect, this time in the other direction.
2258 $mwRedir = MagicWord::get( 'redirect' );
2259 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2260 $redirectArticle = new Article( $this );
2261 $newid = $redirectArticle->insertOn( $dbw );
2262 $redirectRevision = new Revision( array(
2263 'page' => $newid,
2264 'comment' => $comment,
2265 'text' => $redirectText ) );
2266 $redirectRevision->insertOn( $dbw );
2267 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2268 $linkCache->clearLink( $this->getPrefixedDBkey() );
2269
2270 # Log the move
2271 $log = new LogPage( 'move' );
2272 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2273
2274 # Now, we record the link from the redirect to the new title.
2275 # It should have no other outgoing links...
2276 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2277 $dbw->insert( 'pagelinks',
2278 array(
2279 'pl_from' => $newid,
2280 'pl_namespace' => $nt->getNamespace(),
2281 'pl_title' => $nt->getDbKey() ),
2282 $fname );
2283
2284 # Purge squid
2285 if ( $wgUseSquid ) {
2286 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2287 $u = new SquidUpdate( $urls );
2288 $u->doUpdate();
2289 }
2290 }
2291
2292 /**
2293 * Move page to non-existing title.
2294 * @param Title &$nt the new Title
2295 */
2296 private function moveToNewTitle( &$nt, $reason = '' ) {
2297 global $wgUseSquid;
2298 $fname = 'MovePageForm::moveToNewTitle';
2299 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2300 if ( $reason ) {
2301 $comment .= ": $reason";
2302 }
2303
2304 $newid = $nt->getArticleID();
2305 $oldid = $this->getArticleID();
2306 $dbw = wfGetDB( DB_MASTER );
2307 $now = $dbw->timestamp();
2308 $linkCache =& LinkCache::singleton();
2309
2310 # Save a null revision in the page's history notifying of the move
2311 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2312 $nullRevId = $nullRevision->insertOn( $dbw );
2313
2314 # Rename cur entry
2315 $dbw->update( 'page',
2316 /* SET */ array(
2317 'page_touched' => $now,
2318 'page_namespace' => $nt->getNamespace(),
2319 'page_title' => $nt->getDBkey(),
2320 'page_latest' => $nullRevId,
2321 ),
2322 /* WHERE */ array( 'page_id' => $oldid ),
2323 $fname
2324 );
2325
2326 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2327
2328 # Insert redirect
2329 $mwRedir = MagicWord::get( 'redirect' );
2330 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2331 $redirectArticle = new Article( $this );
2332 $newid = $redirectArticle->insertOn( $dbw );
2333 $redirectRevision = new Revision( array(
2334 'page' => $newid,
2335 'comment' => $comment,
2336 'text' => $redirectText ) );
2337 $redirectRevision->insertOn( $dbw );
2338 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2339 $linkCache->clearLink( $this->getPrefixedDBkey() );
2340
2341 # Log the move
2342 $log = new LogPage( 'move' );
2343 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2344
2345 # Purge caches as per article creation
2346 Article::onArticleCreate( $nt );
2347
2348 # Record the just-created redirect's linking to the page
2349 $dbw->insert( 'pagelinks',
2350 array(
2351 'pl_from' => $newid,
2352 'pl_namespace' => $nt->getNamespace(),
2353 'pl_title' => $nt->getDBkey() ),
2354 $fname );
2355
2356 # Purge old title from squid
2357 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2358 $this->purgeSquid();
2359 }
2360
2361 /**
2362 * Checks if $this can be moved to a given Title
2363 * - Selects for update, so don't call it unless you mean business
2364 *
2365 * @param Title &$nt the new title to check
2366 */
2367 public function isValidMoveTarget( $nt ) {
2368
2369 $fname = 'Title::isValidMoveTarget';
2370 $dbw = wfGetDB( DB_MASTER );
2371
2372 # Is it a redirect?
2373 $id = $nt->getArticleID();
2374 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2375 array( 'page_is_redirect','old_text','old_flags' ),
2376 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2377 $fname, 'FOR UPDATE' );
2378
2379 if ( !$obj || 0 == $obj->page_is_redirect ) {
2380 # Not a redirect
2381 wfDebug( __METHOD__ . ": not a redirect\n" );
2382 return false;
2383 }
2384 $text = Revision::getRevisionText( $obj );
2385
2386 # Does the redirect point to the source?
2387 # Or is it a broken self-redirect, usually caused by namespace collisions?
2388 $m = array();
2389 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2390 $redirTitle = Title::newFromText( $m[1] );
2391 if( !is_object( $redirTitle ) ||
2392 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2393 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2394 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2395 return false;
2396 }
2397 } else {
2398 # Fail safe
2399 wfDebug( __METHOD__ . ": failsafe\n" );
2400 return false;
2401 }
2402
2403 # Does the article have a history?
2404 $row = $dbw->selectRow( array( 'page', 'revision'),
2405 array( 'rev_id' ),
2406 array( 'page_namespace' => $nt->getNamespace(),
2407 'page_title' => $nt->getDBkey(),
2408 'page_id=rev_page AND page_latest != rev_id'
2409 ), $fname, 'FOR UPDATE'
2410 );
2411
2412 # Return true if there was no history
2413 return $row === false;
2414 }
2415
2416 /**
2417 * Can this title be added to a user's watchlist?
2418 *
2419 * @return bool
2420 */
2421 public function isWatchable() {
2422 return !$this->isExternal()
2423 && Namespace::isWatchable( $this->getNamespace() );
2424 }
2425
2426 /**
2427 * Get categories to which this Title belongs and return an array of
2428 * categories' names.
2429 *
2430 * @return array an array of parents in the form:
2431 * $parent => $currentarticle
2432 */
2433 public function getParentCategories() {
2434 global $wgContLang;
2435
2436 $titlekey = $this->getArticleId();
2437 $dbr = wfGetDB( DB_SLAVE );
2438 $categorylinks = $dbr->tableName( 'categorylinks' );
2439
2440 # NEW SQL
2441 $sql = "SELECT * FROM $categorylinks"
2442 ." WHERE cl_from='$titlekey'"
2443 ." AND cl_from <> '0'"
2444 ." ORDER BY cl_sortkey";
2445
2446 $res = $dbr->query ( $sql ) ;
2447
2448 if($dbr->numRows($res) > 0) {
2449 while ( $x = $dbr->fetchObject ( $res ) )
2450 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2451 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2452 $dbr->freeResult ( $res ) ;
2453 } else {
2454 $data = '';
2455 }
2456 return $data;
2457 }
2458
2459 /**
2460 * Get a tree of parent categories
2461 * @param array $children an array with the children in the keys, to check for circular refs
2462 * @return array
2463 */
2464 public function getParentCategoryTree( $children = array() ) {
2465 $parents = $this->getParentCategories();
2466
2467 if($parents != '') {
2468 foreach($parents as $parent => $current) {
2469 if ( array_key_exists( $parent, $children ) ) {
2470 # Circular reference
2471 $stack[$parent] = array();
2472 } else {
2473 $nt = Title::newFromText($parent);
2474 if ( $nt ) {
2475 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2476 }
2477 }
2478 }
2479 return $stack;
2480 } else {
2481 return array();
2482 }
2483 }
2484
2485
2486 /**
2487 * Get an associative array for selecting this title from
2488 * the "page" table
2489 *
2490 * @return array
2491 */
2492 public function pageCond() {
2493 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2494 }
2495
2496 /**
2497 * Get the revision ID of the previous revision
2498 *
2499 * @param integer $revision Revision ID. Get the revision that was before this one.
2500 * @return integer $oldrevision|false
2501 */
2502 public function getPreviousRevisionID( $revision ) {
2503 $dbr = wfGetDB( DB_SLAVE );
2504 return $dbr->selectField( 'revision', 'rev_id',
2505 'rev_page=' . intval( $this->getArticleId() ) .
2506 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2507 }
2508
2509 /**
2510 * Get the revision ID of the next revision
2511 *
2512 * @param integer $revision Revision ID. Get the revision that was after this one.
2513 * @return integer $oldrevision|false
2514 */
2515 public function getNextRevisionID( $revision ) {
2516 $dbr = wfGetDB( DB_SLAVE );
2517 return $dbr->selectField( 'revision', 'rev_id',
2518 'rev_page=' . intval( $this->getArticleId() ) .
2519 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2520 }
2521
2522 /**
2523 * Get the number of revisions between the given revision IDs.
2524 *
2525 * @param integer $old Revision ID.
2526 * @param integer $new Revision ID.
2527 * @return integer Number of revisions between these IDs.
2528 */
2529 public function countRevisionsBetween( $old, $new ) {
2530 $dbr = wfGetDB( DB_SLAVE );
2531 return $dbr->selectField( 'revision', 'count(*)',
2532 'rev_page = ' . intval( $this->getArticleId() ) .
2533 ' AND rev_id > ' . intval( $old ) .
2534 ' AND rev_id < ' . intval( $new ) );
2535 }
2536
2537 /**
2538 * Compare with another title.
2539 *
2540 * @param Title $title
2541 * @return bool
2542 */
2543 public function equals( $title ) {
2544 // Note: === is necessary for proper matching of number-like titles.
2545 return $this->getInterwiki() === $title->getInterwiki()
2546 && $this->getNamespace() == $title->getNamespace()
2547 && $this->getDbkey() === $title->getDbkey();
2548 }
2549
2550 /**
2551 * Return a string representation of this title
2552 *
2553 * @return string
2554 */
2555 public function __toString() {
2556 return $this->getPrefixedText();
2557 }
2558
2559 /**
2560 * Check if page exists
2561 * @return bool
2562 */
2563 public function exists() {
2564 return $this->getArticleId() != 0;
2565 }
2566
2567 /**
2568 * Do we know that this title definitely exists, or should we otherwise
2569 * consider that it exists?
2570 *
2571 * @return bool
2572 */
2573 public function isAlwaysKnown() {
2574 return $this->isExternal()
2575 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
2576 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $this->mDbkeyform ) );
2577 }
2578
2579 /**
2580 * Update page_touched timestamps and send squid purge messages for
2581 * pages linking to this title. May be sent to the job queue depending
2582 * on the number of links. Typically called on create and delete.
2583 */
2584 public function touchLinks() {
2585 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2586 $u->doUpdate();
2587
2588 if ( $this->getNamespace() == NS_CATEGORY ) {
2589 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2590 $u->doUpdate();
2591 }
2592 }
2593
2594 /**
2595 * Get the last touched timestamp
2596 */
2597 public function getTouched() {
2598 $dbr = wfGetDB( DB_SLAVE );
2599 $touched = $dbr->selectField( 'page', 'page_touched',
2600 array(
2601 'page_namespace' => $this->getNamespace(),
2602 'page_title' => $this->getDBkey()
2603 ), __METHOD__
2604 );
2605 return $touched;
2606 }
2607
2608 public function trackbackURL() {
2609 global $wgTitle, $wgScriptPath, $wgServer;
2610
2611 return "$wgServer$wgScriptPath/trackback.php?article="
2612 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2613 }
2614
2615 public function trackbackRDF() {
2616 $url = htmlspecialchars($this->getFullURL());
2617 $title = htmlspecialchars($this->getText());
2618 $tburl = $this->trackbackURL();
2619
2620 return "
2621 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2622 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2623 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2624 <rdf:Description
2625 rdf:about=\"$url\"
2626 dc:identifier=\"$url\"
2627 dc:title=\"$title\"
2628 trackback:ping=\"$tburl\" />
2629 </rdf:RDF>";
2630 }
2631
2632 /**
2633 * Generate strings used for xml 'id' names in monobook tabs
2634 * @return string
2635 */
2636 public function getNamespaceKey() {
2637 global $wgContLang;
2638 switch ($this->getNamespace()) {
2639 case NS_MAIN:
2640 case NS_TALK:
2641 return 'nstab-main';
2642 case NS_USER:
2643 case NS_USER_TALK:
2644 return 'nstab-user';
2645 case NS_MEDIA:
2646 return 'nstab-media';
2647 case NS_SPECIAL:
2648 return 'nstab-special';
2649 case NS_PROJECT:
2650 case NS_PROJECT_TALK:
2651 return 'nstab-project';
2652 case NS_IMAGE:
2653 case NS_IMAGE_TALK:
2654 return 'nstab-image';
2655 case NS_MEDIAWIKI:
2656 case NS_MEDIAWIKI_TALK:
2657 return 'nstab-mediawiki';
2658 case NS_TEMPLATE:
2659 case NS_TEMPLATE_TALK:
2660 return 'nstab-template';
2661 case NS_HELP:
2662 case NS_HELP_TALK:
2663 return 'nstab-help';
2664 case NS_CATEGORY:
2665 case NS_CATEGORY_TALK:
2666 return 'nstab-category';
2667 default:
2668 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2669 }
2670 }
2671
2672 /**
2673 * Returns true if this title resolves to the named special page
2674 * @param string $name The special page name
2675 */
2676 public function isSpecial( $name ) {
2677 if ( $this->getNamespace() == NS_SPECIAL ) {
2678 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2679 if ( $name == $thisName ) {
2680 return true;
2681 }
2682 }
2683 return false;
2684 }
2685
2686 /**
2687 * If the Title refers to a special page alias which is not the local default,
2688 * returns a new Title which points to the local default. Otherwise, returns $this.
2689 */
2690 public function fixSpecialName() {
2691 if ( $this->getNamespace() == NS_SPECIAL ) {
2692 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2693 if ( $canonicalName ) {
2694 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2695 if ( $localName != $this->mDbkeyform ) {
2696 return Title::makeTitle( NS_SPECIAL, $localName );
2697 }
2698 }
2699 }
2700 return $this;
2701 }
2702
2703 /**
2704 * Is this Title in a namespace which contains content?
2705 * In other words, is this a content page, for the purposes of calculating
2706 * statistics, etc?
2707 *
2708 * @return bool
2709 */
2710 public function isContentPage() {
2711 return Namespace::isContent( $this->getNamespace() );
2712 }
2713
2714 }
2715
2716