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