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