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