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