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