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