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