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