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