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