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