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