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