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