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