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