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