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