* Removed accidentally committed debugging
[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 // Cache to avoid multiple database queries for the same title
1344 if ( isset($this->mProtections) ) {
1345 return $this->mProtections;
1346 }
1347
1348 $conds = array(
1349 'pt_namespace' => $this->getNamespace(),
1350 'pt_title' => $this->getDBkey()
1351 );
1352
1353 $dbr = wfGetDB( DB_SLAVE );
1354 $res = $dbr->select( 'protected_titles', '*', $conds, __METHOD__ );
1355
1356 if ($row = $dbr->fetchRow( $res )) {
1357 $this->mProtections = $row;
1358 } else {
1359 $this->mProtections = false;
1360 }
1361
1362 return $this->mProtections;
1363 }
1364
1365 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1366 global $wgUser,$wgContLang;
1367
1368 if ($create_perm == implode(',',$this->getRestrictions('create'))
1369 && $expiry == $this->mRestrictionsExpiry) {
1370 // No change
1371 return true;
1372 }
1373
1374 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1375
1376 $dbw = wfGetDB( DB_MASTER );
1377
1378 $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
1379
1380 $expiry_description = '';
1381 if ( $encodedExpiry != 'infinity' ) {
1382 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1383 }
1384
1385 # Update protection table
1386 if ($create_perm != '' ) {
1387 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1388 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1389 , 'pt_create_perm' => $create_perm
1390 , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
1391 , 'pt_expiry' => $encodedExpiry
1392 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__ );
1393 } else {
1394 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1395 'pt_title' => $title ), __METHOD__ );
1396 }
1397 # Update the protection log
1398 $log = new LogPage( 'protect' );
1399
1400 if( $create_perm ) {
1401 $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
1402 } else {
1403 $log->addEntry( 'unprotect', $this, $reason );
1404 }
1405
1406 return true;
1407 }
1408
1409 /**
1410 * Remove any title protection (due to page existing
1411 */
1412 public function deleteTitleProtection() {
1413 $dbw = wfGetDB( DB_MASTER );
1414
1415 $dbw->delete( 'protected_titles',
1416 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
1417 }
1418
1419 /**
1420 * Can $wgUser edit this page?
1421 * @return boolean
1422 * @deprecated use userCan('edit')
1423 */
1424 public function userCanEdit( $doExpensiveQueries = true ) {
1425 return $this->userCan( 'edit', $doExpensiveQueries );
1426 }
1427
1428 /**
1429 * Can $wgUser create this page?
1430 * @return boolean
1431 * @deprecated use userCan('create')
1432 */
1433 public function userCanCreate( $doExpensiveQueries = true ) {
1434 return $this->userCan( 'create', $doExpensiveQueries );
1435 }
1436
1437 /**
1438 * Can $wgUser move this page?
1439 * @return boolean
1440 * @deprecated use userCan('move')
1441 */
1442 public function userCanMove( $doExpensiveQueries = true ) {
1443 return $this->userCan( 'move', $doExpensiveQueries );
1444 }
1445
1446 /**
1447 * Would anybody with sufficient privileges be able to move this page?
1448 * Some pages just aren't movable.
1449 *
1450 * @return boolean
1451 */
1452 public function isMovable() {
1453 return MWNamespace::isMovable( $this->getNamespace() )
1454 && $this->getInterwiki() == '';
1455 }
1456
1457 /**
1458 * Can $wgUser read this page?
1459 * @return boolean
1460 * @todo fold these checks into userCan()
1461 */
1462 public function userCanRead() {
1463 global $wgUser, $wgGroupPermissions;
1464
1465 $result = null;
1466 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1467 if ( $result !== null ) {
1468 return $result;
1469 }
1470
1471 # Shortcut for public wikis, allows skipping quite a bit of code
1472 if ($wgGroupPermissions['*']['read'])
1473 return true;
1474
1475 if( $wgUser->isAllowed( 'read' ) ) {
1476 return true;
1477 } else {
1478 global $wgWhitelistRead;
1479
1480 /**
1481 * Always grant access to the login page.
1482 * Even anons need to be able to log in.
1483 */
1484 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1485 return true;
1486 }
1487
1488 /**
1489 * Bail out if there isn't whitelist
1490 */
1491 if( !is_array($wgWhitelistRead) ) {
1492 return false;
1493 }
1494
1495 /**
1496 * Check for explicit whitelisting
1497 */
1498 $name = $this->getPrefixedText();
1499 $dbName = $this->getPrefixedDBKey();
1500 // Check with and without underscores
1501 if( in_array($name,$wgWhitelistRead,true) || in_array($dbName,$wgWhitelistRead,true) )
1502 return true;
1503
1504 /**
1505 * Old settings might have the title prefixed with
1506 * a colon for main-namespace pages
1507 */
1508 if( $this->getNamespace() == NS_MAIN ) {
1509 if( in_array( ':' . $name, $wgWhitelistRead ) )
1510 return true;
1511 }
1512
1513 /**
1514 * If it's a special page, ditch the subpage bit
1515 * and check again
1516 */
1517 if( $this->getNamespace() == NS_SPECIAL ) {
1518 $name = $this->getDBkey();
1519 list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
1520 if ( $name === false ) {
1521 # Invalid special page, but we show standard login required message
1522 return false;
1523 }
1524
1525 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1526 if( in_array( $pure, $wgWhitelistRead, true ) )
1527 return true;
1528 }
1529
1530 }
1531 return false;
1532 }
1533
1534 /**
1535 * Is this a talk page of some sort?
1536 * @return bool
1537 */
1538 public function isTalkPage() {
1539 return MWNamespace::isTalk( $this->getNamespace() );
1540 }
1541
1542 /**
1543 * Is this a subpage?
1544 * @return bool
1545 */
1546 public function isSubpage() {
1547 return MWNamespace::hasSubpages( $this->mNamespace )
1548 ? strpos( $this->getText(), '/' ) !== false
1549 : false;
1550 }
1551
1552 /**
1553 * Does this have subpages? (Warning, usually requires an extra DB query.)
1554 * @return bool
1555 */
1556 public function hasSubpages() {
1557 if( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1558 # Duh
1559 return false;
1560 }
1561
1562 # We dynamically add a member variable for the purpose of this method
1563 # alone to cache the result. There's no point in having it hanging
1564 # around uninitialized in every Title object; therefore we only add it
1565 # if needed and don't declare it statically.
1566 if( isset( $this->mHasSubpages ) ) {
1567 return $this->mHasSubpages;
1568 }
1569
1570 $db = wfGetDB( DB_SLAVE );
1571 return $this->mHasSubpages = (bool)$db->selectField( 'page', '1',
1572 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1573 . $db->escapeLike( $this->mDbkeyform ) . "/%'",
1574 __METHOD__
1575 );
1576 }
1577
1578 /**
1579 * Could this page contain custom CSS or JavaScript, based
1580 * on the title?
1581 *
1582 * @return bool
1583 */
1584 public function isCssOrJsPage() {
1585 return $this->mNamespace == NS_MEDIAWIKI
1586 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1587 }
1588
1589 /**
1590 * Is this a .css or .js subpage of a user page?
1591 * @return bool
1592 */
1593 public function isCssJsSubpage() {
1594 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1595 }
1596 /**
1597 * Is this a *valid* .css or .js subpage of a user page?
1598 * Check that the corresponding skin exists
1599 */
1600 public function isValidCssJsSubpage() {
1601 if ( $this->isCssJsSubpage() ) {
1602 $skinNames = Skin::getSkinNames();
1603 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1604 } else {
1605 return false;
1606 }
1607 }
1608 /**
1609 * Trim down a .css or .js subpage title to get the corresponding skin name
1610 */
1611 public function getSkinFromCssJsSubpage() {
1612 $subpage = explode( '/', $this->mTextform );
1613 $subpage = $subpage[ count( $subpage ) - 1 ];
1614 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1615 }
1616 /**
1617 * Is this a .css subpage of a user page?
1618 * @return bool
1619 */
1620 public function isCssSubpage() {
1621 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1622 }
1623 /**
1624 * Is this a .js subpage of a user page?
1625 * @return bool
1626 */
1627 public function isJsSubpage() {
1628 return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1629 }
1630 /**
1631 * Protect css/js subpages of user pages: can $wgUser edit
1632 * this page?
1633 *
1634 * @return boolean
1635 * @todo XXX: this might be better using restrictions
1636 */
1637 public function userCanEditCssJsSubpage() {
1638 global $wgUser;
1639 return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1640 }
1641
1642 /**
1643 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1644 *
1645 * @return bool If the page is subject to cascading restrictions.
1646 */
1647 public function isCascadeProtected() {
1648 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1649 return ( $sources > 0 );
1650 }
1651
1652 /**
1653 * Cascading protection: Get the source of any cascading restrictions on this page.
1654 *
1655 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1656 * @return array( mixed title array, restriction array)
1657 * 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.
1658 * The restriction array is an array of each type, each of which contains an array of unique groups
1659 */
1660 public function getCascadeProtectionSources( $get_pages = true ) {
1661 global $wgRestrictionTypes;
1662
1663 # Define our dimension of restrictions types
1664 $pagerestrictions = array();
1665 foreach( $wgRestrictionTypes as $action )
1666 $pagerestrictions[$action] = array();
1667
1668 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1669 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1670 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1671 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1672 }
1673
1674 wfProfileIn( __METHOD__ );
1675
1676 $dbr = wfGetDb( DB_SLAVE );
1677
1678 if ( $this->getNamespace() == NS_IMAGE ) {
1679 $tables = array ('imagelinks', 'page_restrictions');
1680 $where_clauses = array(
1681 'il_to' => $this->getDBkey(),
1682 'il_from=pr_page',
1683 'pr_cascade' => 1 );
1684 } else {
1685 $tables = array ('templatelinks', 'page_restrictions');
1686 $where_clauses = array(
1687 'tl_namespace' => $this->getNamespace(),
1688 'tl_title' => $this->getDBkey(),
1689 'tl_from=pr_page',
1690 'pr_cascade' => 1 );
1691 }
1692
1693 if ( $get_pages ) {
1694 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1695 $where_clauses[] = 'page_id=pr_page';
1696 $tables[] = 'page';
1697 } else {
1698 $cols = array( 'pr_expiry' );
1699 }
1700
1701 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1702
1703 $sources = $get_pages ? array() : false;
1704 $now = wfTimestampNow();
1705 $purgeExpired = false;
1706
1707 foreach( $res as $row ) {
1708 $expiry = Block::decodeExpiry( $row->pr_expiry );
1709 if( $expiry > $now ) {
1710 if ($get_pages) {
1711 $page_id = $row->pr_page;
1712 $page_ns = $row->page_namespace;
1713 $page_title = $row->page_title;
1714 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1715 # Add groups needed for each restriction type if its not already there
1716 # Make sure this restriction type still exists
1717 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1718 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1719 }
1720 } else {
1721 $sources = true;
1722 }
1723 } else {
1724 // Trigger lazy purge of expired restrictions from the db
1725 $purgeExpired = true;
1726 }
1727 }
1728 if( $purgeExpired ) {
1729 Title::purgeExpiredRestrictions();
1730 }
1731
1732 wfProfileOut( __METHOD__ );
1733
1734 if ( $get_pages ) {
1735 $this->mCascadeSources = $sources;
1736 $this->mCascadingRestrictions = $pagerestrictions;
1737 } else {
1738 $this->mHasCascadingRestrictions = $sources;
1739 }
1740
1741 return array( $sources, $pagerestrictions );
1742 }
1743
1744 function areRestrictionsCascading() {
1745 if (!$this->mRestrictionsLoaded) {
1746 $this->loadRestrictions();
1747 }
1748
1749 return $this->mCascadeRestriction;
1750 }
1751
1752 /**
1753 * Loads a string into mRestrictions array
1754 * @param resource $res restrictions as an SQL result.
1755 */
1756 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1757 global $wgRestrictionTypes;
1758 $dbr = wfGetDB( DB_SLAVE );
1759
1760 foreach( $wgRestrictionTypes as $type ){
1761 $this->mRestrictions[$type] = array();
1762 }
1763
1764 $this->mCascadeRestriction = false;
1765 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1766
1767 # Backwards-compatibility: also load the restrictions from the page record (old format).
1768
1769 if ( $oldFashionedRestrictions === NULL ) {
1770 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1771 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1772 }
1773
1774 if ($oldFashionedRestrictions != '') {
1775
1776 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1777 $temp = explode( '=', trim( $restrict ) );
1778 if(count($temp) == 1) {
1779 // old old format should be treated as edit/move restriction
1780 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
1781 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
1782 } else {
1783 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1784 }
1785 }
1786
1787 $this->mOldRestrictions = true;
1788
1789 }
1790
1791 if( $dbr->numRows( $res ) ) {
1792 # Current system - load second to make them override.
1793 $now = wfTimestampNow();
1794 $purgeExpired = false;
1795
1796 foreach( $res as $row ) {
1797 # Cycle through all the restrictions.
1798
1799 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1800 if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
1801 continue;
1802
1803 // This code should be refactored, now that it's being used more generally,
1804 // But I don't really see any harm in leaving it in Block for now -werdna
1805 $expiry = Block::decodeExpiry( $row->pr_expiry );
1806
1807 // Only apply the restrictions if they haven't expired!
1808 if ( !$expiry || $expiry > $now ) {
1809 $this->mRestrictionsExpiry = $expiry;
1810 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1811
1812 $this->mCascadeRestriction |= $row->pr_cascade;
1813 } else {
1814 // Trigger a lazy purge of expired restrictions
1815 $purgeExpired = true;
1816 }
1817 }
1818
1819 if( $purgeExpired ) {
1820 Title::purgeExpiredRestrictions();
1821 }
1822 }
1823
1824 $this->mRestrictionsLoaded = true;
1825 }
1826
1827 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1828 if( !$this->mRestrictionsLoaded ) {
1829 if ($this->exists()) {
1830 $dbr = wfGetDB( DB_SLAVE );
1831
1832 $res = $dbr->select( 'page_restrictions', '*',
1833 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1834
1835 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1836 } else {
1837 $title_protection = $this->getTitleProtection();
1838
1839 if (is_array($title_protection)) {
1840 extract($title_protection);
1841
1842 $now = wfTimestampNow();
1843 $expiry = Block::decodeExpiry($pt_expiry);
1844
1845 if (!$expiry || $expiry > $now) {
1846 // Apply the restrictions
1847 $this->mRestrictionsExpiry = $expiry;
1848 $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
1849 } else { // Get rid of the old restrictions
1850 Title::purgeExpiredRestrictions();
1851 }
1852 } else {
1853 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1854 }
1855 $this->mRestrictionsLoaded = true;
1856 }
1857 }
1858 }
1859
1860 /**
1861 * Purge expired restrictions from the page_restrictions table
1862 */
1863 static function purgeExpiredRestrictions() {
1864 $dbw = wfGetDB( DB_MASTER );
1865 $dbw->delete( 'page_restrictions',
1866 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1867 __METHOD__ );
1868
1869 $dbw->delete( 'protected_titles',
1870 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1871 __METHOD__ );
1872 }
1873
1874 /**
1875 * Accessor/initialisation for mRestrictions
1876 *
1877 * @param string $action action that permission needs to be checked for
1878 * @return array the array of groups allowed to edit this article
1879 */
1880 public function getRestrictions( $action ) {
1881 if( !$this->mRestrictionsLoaded ) {
1882 $this->loadRestrictions();
1883 }
1884 return isset( $this->mRestrictions[$action] )
1885 ? $this->mRestrictions[$action]
1886 : array();
1887 }
1888
1889 /**
1890 * Is there a version of this page in the deletion archive?
1891 * @return int the number of archived revisions
1892 */
1893 public function isDeleted() {
1894 if ( $this->getNamespace() < 0 ) {
1895 return 0;
1896 }
1897
1898 // Cache to avoid multiple queries for the same title
1899 if ( isset($this->mIsDeleted) ) {
1900 return $this->mIsDeleted;
1901 }
1902
1903 $dbr = wfGetDB( DB_SLAVE );
1904 $aConds = array(
1905 'ar_namespace' => $this->getNamespace(),
1906 'ar_title' => $this->getDBkey()
1907 );
1908 $n = $dbr->selectField( 'archive', 'COUNT(*)', $aConds, __METHOD__ );
1909
1910 if ( $this->getNamespace() == NS_IMAGE ) {
1911 $faConds = array( 'fa_name' => $this->getDBkey() );
1912 $n += $dbr->selectField( 'filearchive', 'COUNT(*)', $faConds , __METHOD__ );
1913 }
1914
1915 $this->mIsDeleted = (int) $n;
1916
1917 return $this->mIsDeleted;
1918 }
1919
1920 /**
1921 * Get the article ID for this Title from the link cache,
1922 * adding it if necessary
1923 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1924 * for update
1925 * @return int the ID
1926 */
1927 public function getArticleID( $flags = 0 ) {
1928 $linkCache = LinkCache::singleton();
1929 if ( $flags & GAID_FOR_UPDATE ) {
1930 $oldUpdate = $linkCache->forUpdate( true );
1931 $this->mArticleID = $linkCache->addLinkObj( $this );
1932 $linkCache->forUpdate( $oldUpdate );
1933 } else {
1934 if ( -1 == $this->mArticleID ) {
1935 $this->mArticleID = $linkCache->addLinkObj( $this );
1936 }
1937 }
1938 return $this->mArticleID;
1939 }
1940
1941 /**
1942 * Is this an article that is a redirect page?
1943 * Uses link cache, adding it if necessary
1944 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1945 * @return bool
1946 */
1947 public function isRedirect( $flags = 0 ) {
1948 if( !is_null($this->mRedirect) )
1949 return $this->mRedirect;
1950 # Zero for special pages.
1951 # Also, calling getArticleID() loads the field from cache!
1952 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1953 return false;
1954 }
1955 $linkCache = LinkCache::singleton();
1956 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1957
1958 return $this->mRedirect;
1959 }
1960
1961 /**
1962 * What is the length of this page?
1963 * Uses link cache, adding it if necessary
1964 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1965 * @return bool
1966 */
1967 public function getLength( $flags = 0 ) {
1968 if( $this->mLength != -1 )
1969 return $this->mLength;
1970 # Zero for special pages.
1971 # Also, calling getArticleID() loads the field from cache!
1972 if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
1973 return 0;
1974 }
1975 $linkCache = LinkCache::singleton();
1976 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1977
1978 return $this->mLength;
1979 }
1980
1981 /**
1982 * What is the page_latest field for this page?
1983 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
1984 * @return int
1985 */
1986 public function getLatestRevID( $flags = 0 ) {
1987 if ($this->mLatestID !== false)
1988 return $this->mLatestID;
1989
1990 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB(DB_MASTER) : wfGetDB(DB_SLAVE);
1991 return $this->mLatestID = $db->selectField( 'revision',
1992 "max(rev_id)",
1993 array('rev_page' => $this->getArticleID($flags)),
1994 'Title::getLatestRevID' );
1995 }
1996
1997 /**
1998 * This clears some fields in this object, and clears any associated
1999 * keys in the "bad links" section of the link cache.
2000 *
2001 * - This is called from Article::insertNewArticle() to allow
2002 * loading of the new page_id. It's also called from
2003 * Article::doDeleteArticle()
2004 *
2005 * @param int $newid the new Article ID
2006 */
2007 public function resetArticleID( $newid ) {
2008 $linkCache = LinkCache::singleton();
2009 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2010
2011 if ( 0 == $newid ) { $this->mArticleID = -1; }
2012 else { $this->mArticleID = $newid; }
2013 $this->mRestrictionsLoaded = false;
2014 $this->mRestrictions = array();
2015 }
2016
2017 /**
2018 * Updates page_touched for this page; called from LinksUpdate.php
2019 * @return bool true if the update succeded
2020 */
2021 public function invalidateCache() {
2022 global $wgUseFileCache;
2023
2024 if ( wfReadOnly() ) {
2025 return;
2026 }
2027
2028 $dbw = wfGetDB( DB_MASTER );
2029 $success = $dbw->update( 'page',
2030 array( /* SET */
2031 'page_touched' => $dbw->timestamp()
2032 ), array( /* WHERE */
2033 'page_namespace' => $this->getNamespace() ,
2034 'page_title' => $this->getDBkey()
2035 ), 'Title::invalidateCache'
2036 );
2037
2038 if ($wgUseFileCache) {
2039 $cache = new HTMLFileCache($this);
2040 @unlink($cache->fileCacheName());
2041 }
2042
2043 return $success;
2044 }
2045
2046 /**
2047 * Prefix some arbitrary text with the namespace or interwiki prefix
2048 * of this object
2049 *
2050 * @param string $name the text
2051 * @return string the prefixed text
2052 * @private
2053 */
2054 /* private */ function prefix( $name ) {
2055 $p = '';
2056 if ( '' != $this->mInterwiki ) {
2057 $p = $this->mInterwiki . ':';
2058 }
2059 if ( 0 != $this->mNamespace ) {
2060 $p .= $this->getNsText() . ':';
2061 }
2062 return $p . $name;
2063 }
2064
2065 /**
2066 * Secure and split - main initialisation function for this object
2067 *
2068 * Assumes that mDbkeyform has been set, and is urldecoded
2069 * and uses underscores, but not otherwise munged. This function
2070 * removes illegal characters, splits off the interwiki and
2071 * namespace prefixes, sets the other forms, and canonicalizes
2072 * everything.
2073 * @return bool true on success
2074 */
2075 private function secureAndSplit() {
2076 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2077
2078 # Initialisation
2079 static $rxTc = false;
2080 if( !$rxTc ) {
2081 # Matching titles will be held as illegal.
2082 $rxTc = '/' .
2083 # Any character not allowed is forbidden...
2084 '[^' . Title::legalChars() . ']' .
2085 # URL percent encoding sequences interfere with the ability
2086 # to round-trip titles -- you can't link to them consistently.
2087 '|%[0-9A-Fa-f]{2}' .
2088 # XML/HTML character references produce similar issues.
2089 '|&[A-Za-z0-9\x80-\xff]+;' .
2090 '|&#[0-9]+;' .
2091 '|&#x[0-9A-Fa-f]+;' .
2092 '/S';
2093 }
2094
2095 $this->mInterwiki = $this->mFragment = '';
2096 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2097
2098 $dbkey = $this->mDbkeyform;
2099
2100 # Strip Unicode bidi override characters.
2101 # Sometimes they slip into cut-n-pasted page titles, where the
2102 # override chars get included in list displays.
2103 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2104 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2105
2106 # Clean up whitespace
2107 #
2108 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2109 $dbkey = trim( $dbkey, '_' );
2110
2111 if ( '' == $dbkey ) {
2112 return false;
2113 }
2114
2115 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2116 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2117 return false;
2118 }
2119
2120 $this->mDbkeyform = $dbkey;
2121
2122 # Initial colon indicates main namespace rather than specified default
2123 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2124 if ( ':' == $dbkey{0} ) {
2125 $this->mNamespace = NS_MAIN;
2126 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2127 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2128 }
2129
2130 # Namespace or interwiki prefix
2131 $firstPass = true;
2132 do {
2133 $m = array();
2134 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2135 $p = $m[1];
2136 if ( $ns = $wgContLang->getNsIndex( $p )) {
2137 # Ordinary namespace
2138 $dbkey = $m[2];
2139 $this->mNamespace = $ns;
2140 } elseif( $this->getInterwikiLink( $p ) ) {
2141 if( !$firstPass ) {
2142 # Can't make a local interwiki link to an interwiki link.
2143 # That's just crazy!
2144 return false;
2145 }
2146
2147 # Interwiki link
2148 $dbkey = $m[2];
2149 $this->mInterwiki = $wgContLang->lc( $p );
2150
2151 # Redundant interwiki prefix to the local wiki
2152 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
2153 if( $dbkey == '' ) {
2154 # Can't have an empty self-link
2155 return false;
2156 }
2157 $this->mInterwiki = '';
2158 $firstPass = false;
2159 # Do another namespace split...
2160 continue;
2161 }
2162
2163 # If there's an initial colon after the interwiki, that also
2164 # resets the default namespace
2165 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2166 $this->mNamespace = NS_MAIN;
2167 $dbkey = substr( $dbkey, 1 );
2168 }
2169 }
2170 # If there's no recognized interwiki or namespace,
2171 # then let the colon expression be part of the title.
2172 }
2173 break;
2174 } while( true );
2175
2176 # We already know that some pages won't be in the database!
2177 #
2178 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
2179 $this->mArticleID = 0;
2180 }
2181 $fragment = strstr( $dbkey, '#' );
2182 if ( false !== $fragment ) {
2183 $this->setFragment( $fragment );
2184 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2185 # remove whitespace again: prevents "Foo_bar_#"
2186 # becoming "Foo_bar_"
2187 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2188 }
2189
2190 # Reject illegal characters.
2191 #
2192 if( preg_match( $rxTc, $dbkey ) ) {
2193 return false;
2194 }
2195
2196 /**
2197 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2198 * reachable due to the way web browsers deal with 'relative' URLs.
2199 * Also, they conflict with subpage syntax. Forbid them explicitly.
2200 */
2201 if ( strpos( $dbkey, '.' ) !== false &&
2202 ( $dbkey === '.' || $dbkey === '..' ||
2203 strpos( $dbkey, './' ) === 0 ||
2204 strpos( $dbkey, '../' ) === 0 ||
2205 strpos( $dbkey, '/./' ) !== false ||
2206 strpos( $dbkey, '/../' ) !== false ||
2207 substr( $dbkey, -2 ) == '/.' ||
2208 substr( $dbkey, -3 ) == '/..' ) )
2209 {
2210 return false;
2211 }
2212
2213 /**
2214 * Magic tilde sequences? Nu-uh!
2215 */
2216 if( strpos( $dbkey, '~~~' ) !== false ) {
2217 return false;
2218 }
2219
2220 /**
2221 * Limit the size of titles to 255 bytes.
2222 * This is typically the size of the underlying database field.
2223 * We make an exception for special pages, which don't need to be stored
2224 * in the database, and may edge over 255 bytes due to subpage syntax
2225 * for long titles, e.g. [[Special:Block/Long name]]
2226 */
2227 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2228 strlen( $dbkey ) > 512 )
2229 {
2230 return false;
2231 }
2232
2233 /**
2234 * Normally, all wiki links are forced to have
2235 * an initial capital letter so [[foo]] and [[Foo]]
2236 * point to the same place.
2237 *
2238 * Don't force it for interwikis, since the other
2239 * site might be case-sensitive.
2240 */
2241 $this->mUserCaseDBKey = $dbkey;
2242 if( $wgCapitalLinks && $this->mInterwiki == '') {
2243 $dbkey = $wgContLang->ucfirst( $dbkey );
2244 }
2245
2246 /**
2247 * Can't make a link to a namespace alone...
2248 * "empty" local links can only be self-links
2249 * with a fragment identifier.
2250 */
2251 if( $dbkey == '' &&
2252 $this->mInterwiki == '' &&
2253 $this->mNamespace != NS_MAIN ) {
2254 return false;
2255 }
2256 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2257 // IP names are not allowed for accounts, and can only be referring to
2258 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2259 // there are numerous ways to present the same IP. Having sp:contribs scan
2260 // them all is silly and having some show the edits and others not is
2261 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2262 $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
2263 IP::sanitizeIP( $dbkey ) : $dbkey;
2264 // Any remaining initial :s are illegal.
2265 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2266 return false;
2267 }
2268
2269 # Fill fields
2270 $this->mDbkeyform = $dbkey;
2271 $this->mUrlform = wfUrlencode( $dbkey );
2272
2273 $this->mTextform = str_replace( '_', ' ', $dbkey );
2274
2275 return true;
2276 }
2277
2278 /**
2279 * Set the fragment for this title
2280 * This is kind of bad, since except for this rarely-used function, Title objects
2281 * are immutable. The reason this is here is because it's better than setting the
2282 * members directly, which is what Linker::formatComment was doing previously.
2283 *
2284 * @param string $fragment text
2285 * @todo clarify whether access is supposed to be public (was marked as "kind of public")
2286 */
2287 public function setFragment( $fragment ) {
2288 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2289 }
2290
2291 /**
2292 * Get a Title object associated with the talk page of this article
2293 * @return Title the object for the talk page
2294 */
2295 public function getTalkPage() {
2296 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2297 }
2298
2299 /**
2300 * Get a title object associated with the subject page of this
2301 * talk page
2302 *
2303 * @return Title the object for the subject page
2304 */
2305 public function getSubjectPage() {
2306 return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
2307 }
2308
2309 /**
2310 * Get an array of Title objects linking to this Title
2311 * Also stores the IDs in the link cache.
2312 *
2313 * WARNING: do not use this function on arbitrary user-supplied titles!
2314 * On heavily-used templates it will max out the memory.
2315 *
2316 * @param string $options may be FOR UPDATE
2317 * @return array the Title objects linking here
2318 */
2319 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2320 $linkCache = LinkCache::singleton();
2321
2322 if ( $options ) {
2323 $db = wfGetDB( DB_MASTER );
2324 } else {
2325 $db = wfGetDB( DB_SLAVE );
2326 }
2327
2328 $res = $db->select( array( 'page', $table ),
2329 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2330 array(
2331 "{$prefix}_from=page_id",
2332 "{$prefix}_namespace" => $this->getNamespace(),
2333 "{$prefix}_title" => $this->getDBkey() ),
2334 __METHOD__,
2335 $options );
2336
2337 $retVal = array();
2338 if ( $db->numRows( $res ) ) {
2339 foreach( $res as $row ) {
2340 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
2341 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
2342 $retVal[] = $titleObj;
2343 }
2344 }
2345 }
2346 $db->freeResult( $res );
2347 return $retVal;
2348 }
2349
2350 /**
2351 * Get an array of Title objects using this Title as a template
2352 * Also stores the IDs in the link cache.
2353 *
2354 * WARNING: do not use this function on arbitrary user-supplied titles!
2355 * On heavily-used templates it will max out the memory.
2356 *
2357 * @param string $options may be FOR UPDATE
2358 * @return array the Title objects linking here
2359 */
2360 public function getTemplateLinksTo( $options = '' ) {
2361 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2362 }
2363
2364 /**
2365 * Get an array of Title objects referring to non-existent articles linked from this page
2366 *
2367 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2368 * @param string $options may be FOR UPDATE
2369 * @return array the Title objects
2370 */
2371 public function getBrokenLinksFrom( $options = '' ) {
2372 if ( $this->getArticleId() == 0 ) {
2373 # All links from article ID 0 are false positives
2374 return array();
2375 }
2376
2377 if ( $options ) {
2378 $db = wfGetDB( DB_MASTER );
2379 } else {
2380 $db = wfGetDB( DB_SLAVE );
2381 }
2382
2383 $res = $db->safeQuery(
2384 "SELECT pl_namespace, pl_title
2385 FROM !
2386 LEFT JOIN !
2387 ON pl_namespace=page_namespace
2388 AND pl_title=page_title
2389 WHERE pl_from=?
2390 AND page_namespace IS NULL
2391 !",
2392 $db->tableName( 'pagelinks' ),
2393 $db->tableName( 'page' ),
2394 $this->getArticleId(),
2395 $options );
2396
2397 $retVal = array();
2398 if ( $db->numRows( $res ) ) {
2399 foreach( $res as $row ) {
2400 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2401 }
2402 }
2403 $db->freeResult( $res );
2404 return $retVal;
2405 }
2406
2407
2408 /**
2409 * Get a list of URLs to purge from the Squid cache when this
2410 * page changes
2411 *
2412 * @return array the URLs
2413 */
2414 public function getSquidURLs() {
2415 global $wgContLang;
2416
2417 $urls = array(
2418 $this->getInternalURL(),
2419 $this->getInternalURL( 'action=history' )
2420 );
2421
2422 // purge variant urls as well
2423 if($wgContLang->hasVariants()){
2424 $variants = $wgContLang->getVariants();
2425 foreach($variants as $vCode){
2426 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2427 $urls[] = $this->getInternalURL('',$vCode);
2428 }
2429 }
2430
2431 return $urls;
2432 }
2433
2434 public function purgeSquid() {
2435 global $wgUseSquid;
2436 if ( $wgUseSquid ) {
2437 $urls = $this->getSquidURLs();
2438 $u = new SquidUpdate( $urls );
2439 $u->doUpdate();
2440 }
2441 }
2442
2443 /**
2444 * Move this page without authentication
2445 * @param Title &$nt the new page Title
2446 */
2447 public function moveNoAuth( &$nt ) {
2448 return $this->moveTo( $nt, false );
2449 }
2450
2451 /**
2452 * Check whether a given move operation would be valid.
2453 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2454 * @param Title &$nt the new title
2455 * @param bool $auth indicates whether $wgUser's permissions
2456 * should be checked
2457 * @param string $reason is the log summary of the move, used for spam checking
2458 * @return mixed True on success, getUserPermissionsErrors()-like array on failure
2459 */
2460 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2461 $errors = array();
2462 if( !$nt ) {
2463 // Normally we'd add this to $errors, but we'll get
2464 // lots of syntax errors if $nt is not an object
2465 return array(array('badtitletext'));
2466 }
2467 if( $this->equals( $nt ) ) {
2468 $errors[] = array('selfmove');
2469 }
2470 if( !$this->isMovable() || !$nt->isMovable() ) {
2471 $errors[] = array('immobile_namespace');
2472 }
2473
2474 $oldid = $this->getArticleID();
2475 $newid = $nt->getArticleID();
2476
2477 if ( strlen( $nt->getDBkey() ) < 1 ) {
2478 $errors[] = array('articleexists');
2479 }
2480 if ( ( '' == $this->getDBkey() ) ||
2481 ( !$oldid ) ||
2482 ( '' == $nt->getDBkey() ) ) {
2483 $errors[] = array('badarticleerror');
2484 }
2485
2486 // Image-specific checks
2487 if( $this->getNamespace() == NS_IMAGE ) {
2488 $file = wfLocalFile( $this );
2489 if( $file->exists() ) {
2490 if( $nt->getNamespace() != NS_IMAGE ) {
2491 $errors[] = array('imagenocrossnamespace');
2492 }
2493 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2494 $errors[] = array('imageinvalidfilename');
2495 }
2496 if( !File::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2497 $errors[] = array('imagetypemismatch');
2498 }
2499 }
2500 }
2501
2502 if ( $auth ) {
2503 global $wgUser;
2504 $errors = array_merge($errors,
2505 $this->getUserPermissionsErrors('move', $wgUser),
2506 $this->getUserPermissionsErrors('edit', $wgUser),
2507 $nt->getUserPermissionsErrors('move', $wgUser),
2508 $nt->getUserPermissionsErrors('edit', $wgUser));
2509 }
2510
2511 global $wgUser;
2512 $err = null;
2513 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2514 $errors[] = array('hookaborted', $err);
2515 }
2516
2517 # The move is allowed only if (1) the target doesn't exist, or
2518 # (2) the target is a redirect to the source, and has no history
2519 # (so we can undo bad moves right after they're done).
2520
2521 if ( 0 != $newid ) { # Target exists; check for validity
2522 if ( ! $this->isValidMoveTarget( $nt ) ) {
2523 $errors[] = array('articleexists');
2524 }
2525 } else {
2526 $tp = $nt->getTitleProtection();
2527 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
2528 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2529 $errors[] = array('cantmove-titleprotected');
2530 }
2531 }
2532 if(empty($errors))
2533 return true;
2534 return $errors;
2535 }
2536
2537 /**
2538 * Move a title to a new location
2539 * @param Title &$nt the new title
2540 * @param bool $auth indicates whether $wgUser's permissions
2541 * should be checked
2542 * @param string $reason The reason for the move
2543 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
2544 * Ignored if the user doesn't have the suppressredirect right.
2545 * @return mixed true on success, getUserPermissionsErrors()-like array on failure
2546 */
2547 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2548 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2549 if( is_array( $err ) ) {
2550 return $err;
2551 }
2552
2553 $pageid = $this->getArticleID();
2554 if( $nt->exists() ) {
2555 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2556 $pageCountChange = ($createRedirect ? 0 : -1);
2557 } else { # Target didn't exist, do normal move.
2558 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2559 $pageCountChange = ($createRedirect ? 1 : 0);
2560 }
2561
2562 if( is_array( $err ) ) {
2563 return $err;
2564 }
2565 $redirid = $this->getArticleID();
2566
2567 // Category memberships include a sort key which may be customized.
2568 // If it's left as the default (the page title), we need to update
2569 // the sort key to match the new title.
2570 //
2571 // Be careful to avoid resetting cl_timestamp, which may disturb
2572 // time-based lists on some sites.
2573 //
2574 // Warning -- if the sort key is *explicitly* set to the old title,
2575 // we can't actually distinguish it from a default here, and it'll
2576 // be set to the new title even though it really shouldn't.
2577 // It'll get corrected on the next edit, but resetting cl_timestamp.
2578 $dbw = wfGetDB( DB_MASTER );
2579 $dbw->update( 'categorylinks',
2580 array(
2581 'cl_sortkey' => $nt->getPrefixedText(),
2582 'cl_timestamp=cl_timestamp' ),
2583 array(
2584 'cl_from' => $pageid,
2585 'cl_sortkey' => $this->getPrefixedText() ),
2586 __METHOD__ );
2587
2588 # Update watchlists
2589
2590 $oldnamespace = $this->getNamespace() & ~1;
2591 $newnamespace = $nt->getNamespace() & ~1;
2592 $oldtitle = $this->getDBkey();
2593 $newtitle = $nt->getDBkey();
2594
2595 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2596 WatchedItem::duplicateEntries( $this, $nt );
2597 }
2598
2599 # Update search engine
2600 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2601 $u->doUpdate();
2602 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2603 $u->doUpdate();
2604
2605 # Update site_stats
2606 if( $this->isContentPage() && !$nt->isContentPage() ) {
2607 # No longer a content page
2608 # Not viewed, edited, removing
2609 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2610 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2611 # Now a content page
2612 # Not viewed, edited, adding
2613 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2614 } elseif( $pageCountChange ) {
2615 # Redirect added
2616 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2617 } else {
2618 # Nothing special
2619 $u = false;
2620 }
2621 if( $u )
2622 $u->doUpdate();
2623 # Update message cache for interface messages
2624 if( $nt->getNamespace() == NS_MEDIAWIKI ) {
2625 global $wgMessageCache;
2626 $oldarticle = new Article( $this );
2627 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2628 $newarticle = new Article( $nt );
2629 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2630 }
2631
2632 global $wgUser;
2633 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2634 return true;
2635 }
2636
2637 /**
2638 * Move page to a title which is at present a redirect to the
2639 * source page
2640 *
2641 * @param Title &$nt the page to move to, which should currently
2642 * be a redirect
2643 * @param string $reason The reason for the move
2644 * @param bool $createRedirect Whether to leave a redirect at the old title.
2645 * Ignored if the user doesn't have the suppressredirect right
2646 */
2647 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2648 global $wgUseSquid, $wgUser;
2649 $fname = 'Title::moveOverExistingRedirect';
2650 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2651
2652 if ( $reason ) {
2653 $comment .= ": $reason";
2654 }
2655
2656 $now = wfTimestampNow();
2657 $newid = $nt->getArticleID();
2658 $oldid = $this->getArticleID();
2659 $latest = $this->getLatestRevID();
2660
2661 $dbw = wfGetDB( DB_MASTER );
2662 $dbw->begin();
2663
2664 # Delete the old redirect. We don't save it to history since
2665 # by definition if we've got here it's rather uninteresting.
2666 # We have to remove it so that the next step doesn't trigger
2667 # a conflict on the unique namespace+title index...
2668 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2669 if ( !$dbw->cascadingDeletes() ) {
2670 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
2671 global $wgUseTrackbacks;
2672 if ($wgUseTrackbacks)
2673 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
2674 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
2675 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
2676 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
2677 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
2678 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
2679 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
2680 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
2681 }
2682
2683 # Save a null revision in the page's history notifying of the move
2684 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2685 $nullRevId = $nullRevision->insertOn( $dbw );
2686
2687 $article = new Article( $this );
2688 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2689
2690 # Change the name of the target page:
2691 $dbw->update( 'page',
2692 /* SET */ array(
2693 'page_touched' => $dbw->timestamp($now),
2694 'page_namespace' => $nt->getNamespace(),
2695 'page_title' => $nt->getDBkey(),
2696 'page_latest' => $nullRevId,
2697 ),
2698 /* WHERE */ array( 'page_id' => $oldid ),
2699 $fname
2700 );
2701 $nt->resetArticleID( $oldid );
2702
2703 # Recreate the redirect, this time in the other direction.
2704 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2705 $mwRedir = MagicWord::get( 'redirect' );
2706 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2707 $redirectArticle = new Article( $this );
2708 $newid = $redirectArticle->insertOn( $dbw );
2709 $redirectRevision = new Revision( array(
2710 'page' => $newid,
2711 'comment' => $comment,
2712 'text' => $redirectText ) );
2713 $redirectRevision->insertOn( $dbw );
2714 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2715
2716 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2717
2718 # Now, we record the link from the redirect to the new title.
2719 # It should have no other outgoing links...
2720 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2721 $dbw->insert( 'pagelinks',
2722 array(
2723 'pl_from' => $newid,
2724 'pl_namespace' => $nt->getNamespace(),
2725 'pl_title' => $nt->getDBkey() ),
2726 $fname );
2727 } else {
2728 $this->resetArticleID( 0 );
2729 }
2730
2731 # Move an image if this is a file
2732 if( $this->getNamespace() == NS_IMAGE ) {
2733 $file = wfLocalFile( $this );
2734 if( $file->exists() ) {
2735 $status = $file->move( $nt );
2736 if( !$status->isOk() ) {
2737 $dbw->rollback();
2738 return $status->getErrorsArray();
2739 }
2740 }
2741 }
2742 $dbw->commit();
2743
2744 # Log the move
2745 $log = new LogPage( 'move' );
2746 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2747
2748 # Purge squid
2749 if ( $wgUseSquid ) {
2750 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2751 $u = new SquidUpdate( $urls );
2752 $u->doUpdate();
2753 }
2754
2755 }
2756
2757 /**
2758 * Move page to non-existing title.
2759 * @param Title &$nt the new Title
2760 * @param string $reason The reason for the move
2761 * @param bool $createRedirect Whether to create a redirect from the old title to the new title
2762 * Ignored if the user doesn't have the suppressredirect right
2763 */
2764 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2765 global $wgUseSquid, $wgUser;
2766 $fname = 'MovePageForm::moveToNewTitle';
2767 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2768 if ( $reason ) {
2769 $comment .= ": $reason";
2770 }
2771
2772 $newid = $nt->getArticleID();
2773 $oldid = $this->getArticleID();
2774 $latest = $this->getLatestRevId();
2775
2776 $dbw = wfGetDB( DB_MASTER );
2777 $dbw->begin();
2778 $now = $dbw->timestamp();
2779
2780 # Save a null revision in the page's history notifying of the move
2781 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2782 $nullRevId = $nullRevision->insertOn( $dbw );
2783
2784 $article = new Article( $this );
2785 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2786
2787 # Rename page entry
2788 $dbw->update( 'page',
2789 /* SET */ array(
2790 'page_touched' => $now,
2791 'page_namespace' => $nt->getNamespace(),
2792 'page_title' => $nt->getDBkey(),
2793 'page_latest' => $nullRevId,
2794 ),
2795 /* WHERE */ array( 'page_id' => $oldid ),
2796 $fname
2797 );
2798 $nt->resetArticleID( $oldid );
2799
2800 if( $createRedirect || !$wgUser->isAllowed('suppressredirect') ) {
2801 # Insert redirect
2802 $mwRedir = MagicWord::get( 'redirect' );
2803 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2804 $redirectArticle = new Article( $this );
2805 $newid = $redirectArticle->insertOn( $dbw );
2806 $redirectRevision = new Revision( array(
2807 'page' => $newid,
2808 'comment' => $comment,
2809 'text' => $redirectText ) );
2810 $redirectRevision->insertOn( $dbw );
2811 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2812
2813 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2814
2815 # Record the just-created redirect's linking to the page
2816 $dbw->insert( 'pagelinks',
2817 array(
2818 'pl_from' => $newid,
2819 'pl_namespace' => $nt->getNamespace(),
2820 'pl_title' => $nt->getDBkey() ),
2821 $fname );
2822 } else {
2823 $this->resetArticleID( 0 );
2824 }
2825
2826 # Move an image if this is a file
2827 if( $this->getNamespace() == NS_IMAGE ) {
2828 $file = wfLocalFile( $this );
2829 if( $file->exists() ) {
2830 $status = $file->move( $nt );
2831 if( !$status->isOk() ) {
2832 $dbw->rollback();
2833 return $status->getErrorsArray();
2834 }
2835 }
2836 }
2837 $dbw->commit();
2838
2839 # Log the move
2840 $log = new LogPage( 'move' );
2841 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2842
2843 # Purge caches as per article creation
2844 Article::onArticleCreate( $nt );
2845
2846 # Purge old title from squid
2847 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2848 $this->purgeSquid();
2849
2850 }
2851
2852 /**
2853 * Checks if $this can be moved to a given Title
2854 * - Selects for update, so don't call it unless you mean business
2855 *
2856 * @param Title &$nt the new title to check
2857 */
2858 public function isValidMoveTarget( $nt ) {
2859
2860 $fname = 'Title::isValidMoveTarget';
2861 $dbw = wfGetDB( DB_MASTER );
2862
2863 # Is it an existsing file?
2864 if( $nt->getNamespace() == NS_IMAGE ) {
2865 $file = wfLocalFile( $nt );
2866 if( $file->exists() ) {
2867 wfDebug( __METHOD__ . ": file exists\n" );
2868 return false;
2869 }
2870 }
2871
2872 # Is it a redirect?
2873 $id = $nt->getArticleID();
2874 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2875 array( 'page_is_redirect','old_text','old_flags' ),
2876 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2877 $fname, 'FOR UPDATE' );
2878
2879 if ( !$obj || 0 == $obj->page_is_redirect ) {
2880 # Not a redirect
2881 wfDebug( __METHOD__ . ": not a redirect\n" );
2882 return false;
2883 }
2884 $text = Revision::getRevisionText( $obj );
2885
2886 # Does the redirect point to the source?
2887 # Or is it a broken self-redirect, usually caused by namespace collisions?
2888 $m = array();
2889 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2890 $redirTitle = Title::newFromText( $m[1] );
2891 if( !is_object( $redirTitle ) ||
2892 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2893 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2894 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2895 return false;
2896 }
2897 } else {
2898 # Fail safe
2899 wfDebug( __METHOD__ . ": failsafe\n" );
2900 return false;
2901 }
2902
2903 # Does the article have a history?
2904 $row = $dbw->selectRow( array( 'page', 'revision'),
2905 array( 'rev_id' ),
2906 array( 'page_namespace' => $nt->getNamespace(),
2907 'page_title' => $nt->getDBkey(),
2908 'page_id=rev_page AND page_latest != rev_id'
2909 ), $fname, 'FOR UPDATE'
2910 );
2911
2912 # Return true if there was no history
2913 return $row === false;
2914 }
2915
2916 /**
2917 * Can this title be added to a user's watchlist?
2918 *
2919 * @return bool
2920 */
2921 public function isWatchable() {
2922 return !$this->isExternal()
2923 && MWNamespace::isWatchable( $this->getNamespace() );
2924 }
2925
2926 /**
2927 * Get categories to which this Title belongs and return an array of
2928 * categories' names.
2929 *
2930 * @return array an array of parents in the form:
2931 * $parent => $currentarticle
2932 */
2933 public function getParentCategories() {
2934 global $wgContLang;
2935
2936 $titlekey = $this->getArticleId();
2937 $dbr = wfGetDB( DB_SLAVE );
2938 $categorylinks = $dbr->tableName( 'categorylinks' );
2939
2940 # NEW SQL
2941 $sql = "SELECT * FROM $categorylinks"
2942 ." WHERE cl_from='$titlekey'"
2943 ." AND cl_from <> '0'"
2944 ." ORDER BY cl_sortkey";
2945
2946 $res = $dbr->query( $sql );
2947
2948 if( $dbr->numRows( $res ) > 0 ) {
2949 foreach( $res as $row )
2950 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2951 $data[$wgContLang->getNSText( NS_CATEGORY ).':'.$row->cl_to] = $this->getFullText();
2952 $dbr->freeResult( $res );
2953 } else {
2954 $data = array();
2955 }
2956 return $data;
2957 }
2958
2959 /**
2960 * Get a tree of parent categories
2961 * @param array $children an array with the children in the keys, to check for circular refs
2962 * @return array
2963 */
2964 public function getParentCategoryTree( $children = array() ) {
2965 $stack = array();
2966 $parents = $this->getParentCategories();
2967
2968 if( $parents ) {
2969 foreach( $parents as $parent => $current ) {
2970 if ( array_key_exists( $parent, $children ) ) {
2971 # Circular reference
2972 $stack[$parent] = array();
2973 } else {
2974 $nt = Title::newFromText($parent);
2975 if ( $nt ) {
2976 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2977 }
2978 }
2979 }
2980 return $stack;
2981 } else {
2982 return array();
2983 }
2984 }
2985
2986
2987 /**
2988 * Get an associative array for selecting this title from
2989 * the "page" table
2990 *
2991 * @return array
2992 */
2993 public function pageCond() {
2994 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2995 }
2996
2997 /**
2998 * Get the revision ID of the previous revision
2999 *
3000 * @param integer $revId Revision ID. Get the revision that was before this one.
3001 * @param integer $flags, GAID_FOR_UPDATE
3002 * @return integer $oldrevision|false
3003 */
3004 public function getPreviousRevisionID( $revId, $flags=0 ) {
3005 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3006 return $db->selectField( 'revision', 'rev_id',
3007 array(
3008 'rev_page' => $this->getArticleId($flags),
3009 'rev_id < ' . intval( $revId )
3010 ),
3011 __METHOD__,
3012 array( 'ORDER BY' => 'rev_id DESC' )
3013 );
3014 }
3015
3016 /**
3017 * Get the revision ID of the next revision
3018 *
3019 * @param integer $revId Revision ID. Get the revision that was after this one.
3020 * @param integer $flags, GAID_FOR_UPDATE
3021 * @return integer $oldrevision|false
3022 */
3023 public function getNextRevisionID( $revId, $flags=0 ) {
3024 $db = ($flags & GAID_FOR_UPDATE) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3025 return $db->selectField( 'revision', 'rev_id',
3026 array(
3027 'rev_page' => $this->getArticleId($flags),
3028 'rev_id > ' . intval( $revId )
3029 ),
3030 __METHOD__,
3031 array( 'ORDER BY' => 'rev_id' )
3032 );
3033 }
3034
3035 /**
3036 * Get the number of revisions between the given revision IDs.
3037 * Used for diffs and other things that really need it.
3038 *
3039 * @param integer $old Revision ID.
3040 * @param integer $new Revision ID.
3041 * @return integer Number of revisions between these IDs.
3042 */
3043 public function countRevisionsBetween( $old, $new ) {
3044 $dbr = wfGetDB( DB_SLAVE );
3045 return $dbr->selectField( 'revision', 'count(*)',
3046 'rev_page = ' . intval( $this->getArticleId() ) .
3047 ' AND rev_id > ' . intval( $old ) .
3048 ' AND rev_id < ' . intval( $new ),
3049 __METHOD__,
3050 array( 'USE INDEX' => 'PRIMARY' ) );
3051 }
3052
3053 /**
3054 * Compare with another title.
3055 *
3056 * @param Title $title
3057 * @return bool
3058 */
3059 public function equals( Title $title ) {
3060 // Note: === is necessary for proper matching of number-like titles.
3061 return $this->getInterwiki() === $title->getInterwiki()
3062 && $this->getNamespace() == $title->getNamespace()
3063 && $this->getDBkey() === $title->getDBkey();
3064 }
3065
3066 /**
3067 * Callback for usort() to do title sorts by (namespace, title)
3068 */
3069 static function compare( $a, $b ) {
3070 if( $a->getNamespace() == $b->getNamespace() ) {
3071 return strcmp( $a->getText(), $b->getText() );
3072 } else {
3073 return $a->getNamespace() - $b->getNamespace();
3074 }
3075 }
3076
3077 /**
3078 * Return a string representation of this title
3079 *
3080 * @return string
3081 */
3082 public function __toString() {
3083 return $this->getPrefixedText();
3084 }
3085
3086 /**
3087 * Check if page exists
3088 * @return bool
3089 */
3090 public function exists() {
3091 return $this->getArticleId() != 0;
3092 }
3093
3094 /**
3095 * Do we know that this title definitely exists, or should we otherwise
3096 * consider that it exists?
3097 *
3098 * @return bool
3099 */
3100 public function isAlwaysKnown() {
3101 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3102 // the full l10n of that language to be loaded. That takes much memory and
3103 // isn't needed. So we strip the language part away.
3104 // Also, extension messages which are not loaded, are shown as red, because
3105 // we don't call MessageCache::loadAllMessages.
3106 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
3107 return $this->isExternal()
3108 || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
3109 || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
3110 }
3111
3112 /**
3113 * Update page_touched timestamps and send squid purge messages for
3114 * pages linking to this title. May be sent to the job queue depending
3115 * on the number of links. Typically called on create and delete.
3116 */
3117 public function touchLinks() {
3118 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3119 $u->doUpdate();
3120
3121 if ( $this->getNamespace() == NS_CATEGORY ) {
3122 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3123 $u->doUpdate();
3124 }
3125 }
3126
3127 /**
3128 * Get the last touched timestamp
3129 */
3130 public function getTouched() {
3131 $dbr = wfGetDB( DB_SLAVE );
3132 $touched = $dbr->selectField( 'page', 'page_touched',
3133 array(
3134 'page_namespace' => $this->getNamespace(),
3135 'page_title' => $this->getDBkey()
3136 ), __METHOD__
3137 );
3138 return $touched;
3139 }
3140
3141 public function trackbackURL() {
3142 global $wgTitle, $wgScriptPath, $wgServer;
3143
3144 return "$wgServer$wgScriptPath/trackback.php?article="
3145 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
3146 }
3147
3148 public function trackbackRDF() {
3149 $url = htmlspecialchars($this->getFullURL());
3150 $title = htmlspecialchars($this->getText());
3151 $tburl = $this->trackbackURL();
3152
3153 // Autodiscovery RDF is placed in comments so HTML validator
3154 // won't barf. This is a rather icky workaround, but seems
3155 // frequently used by this kind of RDF thingy.
3156 //
3157 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3158 return "<!--
3159 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3160 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3161 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3162 <rdf:Description
3163 rdf:about=\"$url\"
3164 dc:identifier=\"$url\"
3165 dc:title=\"$title\"
3166 trackback:ping=\"$tburl\" />
3167 </rdf:RDF>
3168 -->";
3169 }
3170
3171 /**
3172 * Generate strings used for xml 'id' names in monobook tabs
3173 * @return string
3174 */
3175 public function getNamespaceKey() {
3176 global $wgContLang;
3177 switch ($this->getNamespace()) {
3178 case NS_MAIN:
3179 case NS_TALK:
3180 return 'nstab-main';
3181 case NS_USER:
3182 case NS_USER_TALK:
3183 return 'nstab-user';
3184 case NS_MEDIA:
3185 return 'nstab-media';
3186 case NS_SPECIAL:
3187 return 'nstab-special';
3188 case NS_PROJECT:
3189 case NS_PROJECT_TALK:
3190 return 'nstab-project';
3191 case NS_IMAGE:
3192 case NS_IMAGE_TALK:
3193 return 'nstab-image';
3194 case NS_MEDIAWIKI:
3195 case NS_MEDIAWIKI_TALK:
3196 return 'nstab-mediawiki';
3197 case NS_TEMPLATE:
3198 case NS_TEMPLATE_TALK:
3199 return 'nstab-template';
3200 case NS_HELP:
3201 case NS_HELP_TALK:
3202 return 'nstab-help';
3203 case NS_CATEGORY:
3204 case NS_CATEGORY_TALK:
3205 return 'nstab-category';
3206 default:
3207 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3208 }
3209 }
3210
3211 /**
3212 * Returns true if this title resolves to the named special page
3213 * @param string $name The special page name
3214 */
3215 public function isSpecial( $name ) {
3216 if ( $this->getNamespace() == NS_SPECIAL ) {
3217 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3218 if ( $name == $thisName ) {
3219 return true;
3220 }
3221 }
3222 return false;
3223 }
3224
3225 /**
3226 * If the Title refers to a special page alias which is not the local default,
3227 * returns a new Title which points to the local default. Otherwise, returns $this.
3228 */
3229 public function fixSpecialName() {
3230 if ( $this->getNamespace() == NS_SPECIAL ) {
3231 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
3232 if ( $canonicalName ) {
3233 $localName = SpecialPage::getLocalNameFor( $canonicalName );
3234 if ( $localName != $this->mDbkeyform ) {
3235 return Title::makeTitle( NS_SPECIAL, $localName );
3236 }
3237 }
3238 }
3239 return $this;
3240 }
3241
3242 /**
3243 * Is this Title in a namespace which contains content?
3244 * In other words, is this a content page, for the purposes of calculating
3245 * statistics, etc?
3246 *
3247 * @return bool
3248 */
3249 public function isContentPage() {
3250 return MWNamespace::isContent( $this->getNamespace() );
3251 }
3252
3253 public function getRedirectsHere( $ns = null ) {
3254 $redirs = array();
3255
3256 $dbr = wfGetDB( DB_SLAVE );
3257 $where = array(
3258 'rd_namespace' => $this->getNamespace(),
3259 'rd_title' => $this->getDBkey(),
3260 'rd_from = page_id'
3261 );
3262 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3263
3264 $res = $dbr->select(
3265 array( 'redirect', 'page' ),
3266 array( 'page_namespace', 'page_title' ),
3267 $where,
3268 __METHOD__
3269 );
3270
3271
3272 foreach( $res as $row ) {
3273 $redirs[] = self::newFromRow( $row );
3274 }
3275 return $redirs;
3276 }
3277 }