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