* (bug 17160) Gender specific display text for User namespace
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
6
7 /**
8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
11 */
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname( __FILE__ ) . '/normal/UtfNormal.php' );
14 }
15
16 /**
17 * @deprecated This used to be a define, but was moved to
18 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
19 */
20 define( 'GAID_FOR_UPDATE', Title::GAID_FOR_UPDATE );
21
22 /**
23 * Represents a title within MediaWiki.
24 * Optionally may contain an interwiki designation or namespace.
25 * @note This class can fetch various kinds of data from the database;
26 * however, it does so inefficiently.
27 *
28 * @internal documentation reviewed 15 Mar 2010
29 */
30 class Title {
31 /** @name Static cache variables */
32 // @{
33 static private $titleCache = array();
34 // @}
35
36 /**
37 * Title::newFromText maintains a cache to avoid expensive re-normalization of
38 * commonly used titles. On a batch operation this can become a memory leak
39 * if not bounded. After hitting this many titles reset the cache.
40 */
41 const CACHE_MAX = 1000;
42
43 /**
44 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
45 * to use the master DB
46 */
47 const GAID_FOR_UPDATE = 1;
48
49
50 /**
51 * @name Private member variables
52 * Please use the accessor functions instead.
53 * @private
54 */
55 // @{
56
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
67 var $mOldRestrictions = false;
68 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
69 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
70 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
71 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
72 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
73 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
74 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
75 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
76 # Don't change the following default, NS_MAIN is hardcoded in several
77 # places. See bug 696.
78 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
79 # Zero except in {{transclusion}} tags
80 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
81 var $mLength = -1; // /< The page length, 0 for special pages
82 var $mRedirect = null; // /< Is the article at this title a redirect?
83 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
84 var $mBacklinkCache = null; // /< Cache of links to this title
85 // @}
86
87
88 /**
89 * Constructor
90 * @private
91 */
92 /* private */ function __construct() { }
93
94 /**
95 * Create a new Title from a prefixed DB key
96 *
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
99 * interwiki prefixes
100 * @return Title, or NULL on an error
101 */
102 public static function newFromDBkey( $key ) {
103 $t = new Title();
104 $t->mDbkeyform = $key;
105 if ( $t->secureAndSplit() ) {
106 return $t;
107 } else {
108 return null;
109 }
110 }
111
112 /**
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
115 *
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
121 * makeTitleSafe().
122 * @return Title, or null on an error.
123 */
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
127 }
128
129 /**
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
133 * caching them.
134 *
135 * In theory these are value objects and won't get changed...
136 */
137 if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
138 return Title::$titleCache[$text];
139 }
140
141 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
142 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
143
144 $t = new Title();
145 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace = $defaultNamespace;
147
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN ) {
151 if ( $cachedcount >= self::CACHE_MAX ) {
152 # Avoid memory leaks on mass operations...
153 Title::$titleCache = array();
154 $cachedcount = 0;
155 }
156 $cachedcount++;
157 Title::$titleCache[$text] =& $t;
158 }
159 return $t;
160 } else {
161 $ret = null;
162 return $ret;
163 }
164 }
165
166 /**
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
168 *
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
171 *
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
174 *
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
177 *
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
180 */
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
183 $t = new Title();
184
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
190 }
191
192 $t->mDbkeyform = str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
194 return $t;
195 } else {
196 return null;
197 }
198 }
199
200 /**
201 * Create a new Title from an article ID
202 *
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
206 */
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
210 if ( $row !== false ) {
211 $title = Title::newFromRow( $row );
212 } else {
213 $title = null;
214 }
215 return $title;
216 }
217
218 /**
219 * Make an array of titles from an array of IDs
220 *
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
223 */
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
226 return array();
227 }
228 $dbr = wfGetDB( DB_SLAVE );
229
230 $res = $dbr->select(
231 'page',
232 array(
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
235 ),
236 array( 'page_id' => $ids ),
237 __METHOD__
238 );
239
240 $titles = array();
241 foreach ( $res as $row ) {
242 $titles[] = Title::newFromRow( $row );
243 }
244 return $titles;
245 }
246
247 /**
248 * Make a Title object from a DB row
249 *
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
252 */
253 public static function newFromRow( $row ) {
254 $t = self::makeTitle( $row->page_namespace, $row->page_title );
255
256 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
257 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
258 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
259 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
260
261 return $t;
262 }
263
264 /**
265 * Create a new Title from a namespace index and a DB key.
266 * It's assumed that $ns and $title are *valid*, for instance when
267 * they came directly from the database or a special page name.
268 * For convenience, spaces are converted to underscores so that
269 * eg user_text fields can be used directly.
270 *
271 * @param $ns Int the namespace of the article
272 * @param $title String the unprefixed database key form
273 * @param $fragment String the link fragment (after the "#")
274 * @param $interwiki String the interwiki prefix
275 * @return Title the new object
276 */
277 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
278 $t = new Title();
279 $t->mInterwiki = $interwiki;
280 $t->mFragment = $fragment;
281 $t->mNamespace = $ns = intval( $ns );
282 $t->mDbkeyform = str_replace( ' ', '_', $title );
283 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
284 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
285 $t->mTextform = str_replace( '_', ' ', $title );
286 return $t;
287 }
288
289 /**
290 * Create a new Title from a namespace index and a DB key.
291 * The parameters will be checked for validity, which is a bit slower
292 * than makeTitle() but safer for user-provided data.
293 *
294 * @param $ns Int the namespace of the article
295 * @param $title String database key form
296 * @param $fragment String the link fragment (after the "#")
297 * @param $interwiki String interwiki prefix
298 * @return Title the new object, or NULL on an error
299 */
300 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
301 $t = new Title();
302 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
303 if ( $t->secureAndSplit() ) {
304 return $t;
305 } else {
306 return null;
307 }
308 }
309
310 /**
311 * Create a new Title for the Main Page
312 *
313 * @return Title the new object
314 */
315 public static function newMainPage() {
316 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
317 // Don't give fatal errors if the message is broken
318 if ( !$title ) {
319 $title = Title::newFromText( 'Main Page' );
320 }
321 return $title;
322 }
323
324 /**
325 * Extract a redirect destination from a string and return the
326 * Title, or null if the text doesn't contain a valid redirect
327 * This will only return the very next target, useful for
328 * the redirect table and other checks that don't need full recursion
329 *
330 * @param $text String: Text with possible redirect
331 * @return Title: The corresponding Title
332 */
333 public static function newFromRedirect( $text ) {
334 return self::newFromRedirectInternal( $text );
335 }
336
337 /**
338 * Extract a redirect destination from a string and return the
339 * Title, or null if the text doesn't contain a valid redirect
340 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
341 * in order to provide (hopefully) the Title of the final destination instead of another redirect
342 *
343 * @param $text String Text with possible redirect
344 * @return Title
345 */
346 public static function newFromRedirectRecurse( $text ) {
347 $titles = self::newFromRedirectArray( $text );
348 return $titles ? array_pop( $titles ) : null;
349 }
350
351 /**
352 * Extract a redirect destination from a string and return an
353 * array of Titles, or null if the text doesn't contain a valid redirect
354 * The last element in the array is the final destination after all redirects
355 * have been resolved (up to $wgMaxRedirects times)
356 *
357 * @param $text String Text with possible redirect
358 * @return Array of Titles, with the destination last
359 */
360 public static function newFromRedirectArray( $text ) {
361 global $wgMaxRedirects;
362 // are redirects disabled?
363 if ( $wgMaxRedirects < 1 ) {
364 return null;
365 }
366 $title = self::newFromRedirectInternal( $text );
367 if ( is_null( $title ) ) {
368 return null;
369 }
370 // recursive check to follow double redirects
371 $recurse = $wgMaxRedirects;
372 $titles = array( $title );
373 while ( --$recurse > 0 ) {
374 if ( $title->isRedirect() ) {
375 $article = new Article( $title, 0 );
376 $newtitle = $article->getRedirectTarget();
377 } else {
378 break;
379 }
380 // Redirects to some special pages are not permitted
381 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
382 // the new title passes the checks, so make that our current title so that further recursion can be checked
383 $title = $newtitle;
384 $titles[] = $newtitle;
385 } else {
386 break;
387 }
388 }
389 return $titles;
390 }
391
392 /**
393 * Really extract the redirect destination
394 * Do not call this function directly, use one of the newFromRedirect* functions above
395 *
396 * @param $text String Text with possible redirect
397 * @return Title
398 */
399 protected static function newFromRedirectInternal( $text ) {
400 $redir = MagicWord::get( 'redirect' );
401 $text = trim( $text );
402 if ( $redir->matchStartAndRemove( $text ) ) {
403 // Extract the first link and see if it's usable
404 // Ensure that it really does come directly after #REDIRECT
405 // Some older redirects included a colon, so don't freak about that!
406 $m = array();
407 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
408 // Strip preceding colon used to "escape" categories, etc.
409 // and URL-decode links
410 if ( strpos( $m[1], '%' ) !== false ) {
411 // Match behavior of inline link parsing here;
412 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
413 }
414 $title = Title::newFromText( $m[1] );
415 // If the title is a redirect to bad special pages or is invalid, return null
416 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
417 return null;
418 }
419 return $title;
420 }
421 }
422 return null;
423 }
424
425 # ----------------------------------------------------------------------------
426 # Static functions
427 # ----------------------------------------------------------------------------
428
429 /**
430 * Get the prefixed DB key associated with an ID
431 *
432 * @param $id Int the page_id of the article
433 * @return Title an object representing the article, or NULL if no such article was found
434 */
435 public static function nameOf( $id ) {
436 $dbr = wfGetDB( DB_SLAVE );
437
438 $s = $dbr->selectRow(
439 'page',
440 array( 'page_namespace', 'page_title' ),
441 array( 'page_id' => $id ),
442 __METHOD__
443 );
444 if ( $s === false ) {
445 return null;
446 }
447
448 $n = self::makeName( $s->page_namespace, $s->page_title );
449 return $n;
450 }
451
452 /**
453 * Get a regex character class describing the legal characters in a link
454 *
455 * @return String the list of characters, not delimited
456 */
457 public static function legalChars() {
458 global $wgLegalTitleChars;
459 return $wgLegalTitleChars;
460 }
461
462 /**
463 * Get a string representation of a title suitable for
464 * including in a search index
465 *
466 * @param $ns Int a namespace index
467 * @param $title String text-form main part
468 * @return String a stripped-down title string ready for the search index
469 */
470 public static function indexTitle( $ns, $title ) {
471 global $wgContLang;
472
473 $lc = SearchEngine::legalSearchChars() . '&#;';
474 $t = $wgContLang->normalizeForSearch( $title );
475 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
476 $t = $wgContLang->lc( $t );
477
478 # Handle 's, s'
479 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
480 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
481
482 $t = preg_replace( "/\\s+/", ' ', $t );
483
484 if ( $ns == NS_FILE ) {
485 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
486 }
487 return trim( $t );
488 }
489
490 /**
491 * Make a prefixed DB key from a DB key and a namespace index
492 *
493 * @param $ns Int numerical representation of the namespace
494 * @param $title String the DB key form the title
495 * @param $fragment String The link fragment (after the "#")
496 * @param $interwiki String The interwiki prefix
497 * @return String the prefixed form of the title
498 */
499 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
500 global $wgContLang;
501
502 $namespace = $wgContLang->getNsText( $ns );
503 $name = $namespace == '' ? $title : "$namespace:$title";
504 if ( strval( $interwiki ) != '' ) {
505 $name = "$interwiki:$name";
506 }
507 if ( strval( $fragment ) != '' ) {
508 $name .= '#' . $fragment;
509 }
510 return $name;
511 }
512
513 /**
514 * Determine whether the object refers to a page within
515 * this project.
516 *
517 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
518 */
519 public function isLocal() {
520 if ( $this->mInterwiki != '' ) {
521 return Interwiki::fetch( $this->mInterwiki )->isLocal();
522 } else {
523 return true;
524 }
525 }
526
527 /**
528 * Determine whether the object refers to a page within
529 * this project and is transcludable.
530 *
531 * @return Bool TRUE if this is transcludable
532 */
533 public function isTrans() {
534 if ( $this->mInterwiki == '' ) {
535 return false;
536 }
537
538 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
539 }
540
541 /**
542 * Returns the DB name of the distant wiki which owns the object.
543 *
544 * @return String the DB name
545 */
546 public function getTransWikiID() {
547 if ( $this->mInterwiki == '' ) {
548 return false;
549 }
550
551 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
552 }
553
554 /**
555 * Escape a text fragment, say from a link, for a URL
556 *
557 * @param $fragment string containing a URL or link fragment (after the "#")
558 * @return String: escaped string
559 */
560 static function escapeFragmentForURL( $fragment ) {
561 # Note that we don't urlencode the fragment. urlencoded Unicode
562 # fragments appear not to work in IE (at least up to 7) or in at least
563 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
564 # to care if they aren't encoded.
565 return Sanitizer::escapeId( $fragment, 'noninitial' );
566 }
567
568 # ----------------------------------------------------------------------------
569 # Other stuff
570 # ----------------------------------------------------------------------------
571
572 /** Simple accessors */
573 /**
574 * Get the text form (spaces not underscores) of the main part
575 *
576 * @return String Main part of the title
577 */
578 public function getText() { return $this->mTextform; }
579
580 /**
581 * Get the URL-encoded form of the main part
582 *
583 * @return String Main part of the title, URL-encoded
584 */
585 public function getPartialURL() { return $this->mUrlform; }
586
587 /**
588 * Get the main part with underscores
589 *
590 * @return String: Main part of the title, with underscores
591 */
592 public function getDBkey() { return $this->mDbkeyform; }
593
594 /**
595 * Get the namespace index, i.e. one of the NS_xxxx constants.
596 *
597 * @return Integer: Namespace index
598 */
599 public function getNamespace() { return $this->mNamespace; }
600
601 /**
602 * Get the namespace text
603 *
604 * @return String: Namespace text
605 */
606 public function getNsText() {
607 global $wgContLang;
608
609 if ( $this->mInterwiki != '' ) {
610 // This probably shouldn't even happen. ohh man, oh yuck.
611 // But for interwiki transclusion it sometimes does.
612 // Shit. Shit shit shit.
613 //
614 // Use the canonical namespaces if possible to try to
615 // resolve a foreign namespace.
616 if ( MWNamespace::exists( $this->mNamespace ) ) {
617 return MWNamespace::getCanonicalName( $this->mNamespace );
618 }
619 }
620
621 if ( $wgContLang->needsGenderDistinction() &&
622 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
623 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
624 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
625 }
626
627 return $wgContLang->getNsText( $this->mNamespace );
628 }
629
630 /**
631 * Get the DB key with the initial letter case as specified by the user
632 *
633 * @return String DB key
634 */
635 function getUserCaseDBKey() {
636 return $this->mUserCaseDBKey;
637 }
638
639 /**
640 * Get the namespace text of the subject (rather than talk) page
641 *
642 * @return String Namespace text
643 */
644 public function getSubjectNsText() {
645 global $wgContLang;
646 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
647 }
648
649 /**
650 * Get the namespace text of the talk page
651 *
652 * @return String Namespace text
653 */
654 public function getTalkNsText() {
655 global $wgContLang;
656 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
657 }
658
659 /**
660 * Could this title have a corresponding talk page?
661 *
662 * @return Bool TRUE or FALSE
663 */
664 public function canTalk() {
665 return( MWNamespace::canTalk( $this->mNamespace ) );
666 }
667
668 /**
669 * Get the interwiki prefix (or null string)
670 *
671 * @return String Interwiki prefix
672 */
673 public function getInterwiki() { return $this->mInterwiki; }
674
675 /**
676 * Get the Title fragment (i.e.\ the bit after the #) in text form
677 *
678 * @return String Title fragment
679 */
680 public function getFragment() { return $this->mFragment; }
681
682 /**
683 * Get the fragment in URL form, including the "#" character if there is one
684 * @return String Fragment in URL form
685 */
686 public function getFragmentForURL() {
687 if ( $this->mFragment == '' ) {
688 return '';
689 } else {
690 return '#' . Title::escapeFragmentForURL( $this->mFragment );
691 }
692 }
693
694 /**
695 * Get the default namespace index, for when there is no namespace
696 *
697 * @return Int Default namespace index
698 */
699 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
700
701 /**
702 * Get title for search index
703 *
704 * @return String a stripped-down title string ready for the
705 * search index
706 */
707 public function getIndexTitle() {
708 return Title::indexTitle( $this->mNamespace, $this->mTextform );
709 }
710
711 /**
712 * Get the prefixed database key form
713 *
714 * @return String the prefixed title, with underscores and
715 * any interwiki and namespace prefixes
716 */
717 public function getPrefixedDBkey() {
718 $s = $this->prefix( $this->mDbkeyform );
719 $s = str_replace( ' ', '_', $s );
720 return $s;
721 }
722
723 /**
724 * Get the prefixed title with spaces.
725 * This is the form usually used for display
726 *
727 * @return String the prefixed title, with spaces
728 */
729 public function getPrefixedText() {
730 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
731 $s = $this->prefix( $this->mTextform );
732 $s = str_replace( '_', ' ', $s );
733 $this->mPrefixedText = $s;
734 }
735 return $this->mPrefixedText;
736 }
737
738 /**
739 * Get the prefixed title with spaces, plus any fragment
740 * (part beginning with '#')
741 *
742 * @return String the prefixed title, with spaces and the fragment, including '#'
743 */
744 public function getFullText() {
745 $text = $this->getPrefixedText();
746 if ( $this->mFragment != '' ) {
747 $text .= '#' . $this->mFragment;
748 }
749 return $text;
750 }
751
752 /**
753 * Get the base name, i.e. the leftmost parts before the /
754 *
755 * @return String Base name
756 */
757 public function getBaseText() {
758 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
759 return $this->getText();
760 }
761
762 $parts = explode( '/', $this->getText() );
763 # Don't discard the real title if there's no subpage involved
764 if ( count( $parts ) > 1 ) {
765 unset( $parts[count( $parts ) - 1] );
766 }
767 return implode( '/', $parts );
768 }
769
770 /**
771 * Get the lowest-level subpage name, i.e. the rightmost part after /
772 *
773 * @return String Subpage name
774 */
775 public function getSubpageText() {
776 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
777 return( $this->mTextform );
778 }
779 $parts = explode( '/', $this->mTextform );
780 return( $parts[count( $parts ) - 1] );
781 }
782
783 /**
784 * Get a URL-encoded form of the subpage text
785 *
786 * @return String URL-encoded subpage name
787 */
788 public function getSubpageUrlForm() {
789 $text = $this->getSubpageText();
790 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
791 return( $text );
792 }
793
794 /**
795 * Get a URL-encoded title (not an actual URL) including interwiki
796 *
797 * @return String the URL-encoded form
798 */
799 public function getPrefixedURL() {
800 $s = $this->prefix( $this->mDbkeyform );
801 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
802 return $s;
803 }
804
805 /**
806 * Get a real URL referring to this title, with interwiki link and
807 * fragment
808 *
809 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
810 * links. Can be specified as an associative array as well, e.g.,
811 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
812 * @param $variant String language variant of url (for sr, zh..)
813 * @return String the URL
814 */
815 public function getFullURL( $query = '', $variant = false ) {
816 global $wgServer, $wgRequest;
817
818 if ( is_array( $query ) ) {
819 $query = wfArrayToCGI( $query );
820 }
821
822 $interwiki = Interwiki::fetch( $this->mInterwiki );
823 if ( !$interwiki ) {
824 $url = $this->getLocalURL( $query, $variant );
825
826 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
827 // Correct fix would be to move the prepending elsewhere.
828 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
829 $url = $wgServer . $url;
830 }
831 } else {
832 $baseUrl = $interwiki->getURL();
833
834 $namespace = wfUrlencode( $this->getNsText() );
835 if ( $namespace != '' ) {
836 # Can this actually happen? Interwikis shouldn't be parsed.
837 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
838 $namespace .= ':';
839 }
840 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
841 $url = wfAppendQuery( $url, $query );
842 }
843
844 # Finally, add the fragment.
845 $url .= $this->getFragmentForURL();
846
847 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
848 return $url;
849 }
850
851 /**
852 * Get a URL with no fragment or server name. If this page is generated
853 * with action=render, $wgServer is prepended.
854 *
855 * @param $query Mixed: an optional query string; if not specified,
856 * $wgArticlePath will be used. Can be specified as an associative array
857 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
858 * URL-escaped).
859 * @param $variant String language variant of url (for sr, zh..)
860 * @return String the URL
861 */
862 public function getLocalURL( $query = '', $variant = false ) {
863 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
864 global $wgVariantArticlePath, $wgContLang;
865
866 if ( is_array( $query ) ) {
867 $query = wfArrayToCGI( $query );
868 }
869
870 if ( $this->isExternal() ) {
871 $url = $this->getFullURL();
872 if ( $query ) {
873 // This is currently only used for edit section links in the
874 // context of interwiki transclusion. In theory we should
875 // append the query to the end of any existing query string,
876 // but interwiki transclusion is already broken in that case.
877 $url .= "?$query";
878 }
879 } else {
880 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
881 if ( $query == '' ) {
882 if ( $variant != false && $wgContLang->hasVariants() ) {
883 if ( !$wgVariantArticlePath ) {
884 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
885 } else {
886 $variantArticlePath = $wgVariantArticlePath;
887 }
888 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
889 $url = str_replace( '$1', $dbkey, $url );
890 } else {
891 $url = str_replace( '$1', $dbkey, $wgArticlePath );
892 }
893 } else {
894 global $wgActionPaths;
895 $url = false;
896 $matches = array();
897 if ( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
899 {
900 $action = urldecode( $matches[2] );
901 if ( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if ( isset( $matches[4] ) ) {
904 $query .= $matches[4];
905 }
906 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
907 if ( $query != '' ) {
908 $url = wfAppendQuery( $url, $query );
909 }
910 }
911 }
912 if ( $url === false ) {
913 if ( $query == '-' ) {
914 $query = '';
915 }
916 $url = "{$wgScript}?title={$dbkey}&{$query}";
917 }
918 }
919
920 // FIXME: this causes breakage in various places when we
921 // actually expected a local URL and end up with dupe prefixes.
922 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
923 $url = $wgServer . $url;
924 }
925 }
926 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
927 return $url;
928 }
929
930 /**
931 * Get a URL that's the simplest URL that will be valid to link, locally,
932 * to the current Title. It includes the fragment, but does not include
933 * the server unless action=render is used (or the link is external). If
934 * there's a fragment but the prefixed text is empty, we just return a link
935 * to the fragment.
936 *
937 * The result obviously should not be URL-escaped, but does need to be
938 * HTML-escaped if it's being output in HTML.
939 *
940 * @param $query Array of Strings An associative array of key => value pairs for the
941 * query string. Keys and values will be escaped.
942 * @param $variant String language variant of URL (for sr, zh..). Ignored
943 * for external links. Default is "false" (same variant as current page,
944 * for anonymous users).
945 * @return String the URL
946 */
947 public function getLinkUrl( $query = array(), $variant = false ) {
948 wfProfileIn( __METHOD__ );
949 if ( $this->isExternal() ) {
950 $ret = $this->getFullURL( $query );
951 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
952 $ret = $this->getFragmentForURL();
953 } else {
954 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
955 }
956 wfProfileOut( __METHOD__ );
957 return $ret;
958 }
959
960 /**
961 * Get an HTML-escaped version of the URL form, suitable for
962 * using in a link, without a server name or fragment
963 *
964 * @param $query String an optional query string
965 * @return String the URL
966 */
967 public function escapeLocalURL( $query = '' ) {
968 return htmlspecialchars( $this->getLocalURL( $query ) );
969 }
970
971 /**
972 * Get an HTML-escaped version of the URL form, suitable for
973 * using in a link, including the server name and fragment
974 *
975 * @param $query String an optional query string
976 * @return String the URL
977 */
978 public function escapeFullURL( $query = '' ) {
979 return htmlspecialchars( $this->getFullURL( $query ) );
980 }
981
982 /**
983 * Get the URL form for an internal link.
984 * - Used in various Squid-related code, in case we have a different
985 * internal hostname for the server from the exposed one.
986 *
987 * @param $query String an optional query string
988 * @param $variant String language variant of url (for sr, zh..)
989 * @return String the URL
990 */
991 public function getInternalURL( $query = '', $variant = false ) {
992 global $wgInternalServer;
993 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
994 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
995 return $url;
996 }
997
998 /**
999 * Get the edit URL for this Title
1000 *
1001 * @return String the URL, or a null string if this is an
1002 * interwiki link
1003 */
1004 public function getEditURL() {
1005 if ( $this->mInterwiki != '' ) {
1006 return '';
1007 }
1008 $s = $this->getLocalURL( 'action=edit' );
1009
1010 return $s;
1011 }
1012
1013 /**
1014 * Get the HTML-escaped displayable text form.
1015 * Used for the title field in <a> tags.
1016 *
1017 * @return String the text, including any prefixes
1018 */
1019 public function getEscapedText() {
1020 return htmlspecialchars( $this->getPrefixedText() );
1021 }
1022
1023 /**
1024 * Is this Title interwiki?
1025 *
1026 * @return Bool
1027 */
1028 public function isExternal() {
1029 return ( $this->mInterwiki != '' );
1030 }
1031
1032 /**
1033 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1034 *
1035 * @param $action String Action to check (default: edit)
1036 * @return Bool
1037 */
1038 public function isSemiProtected( $action = 'edit' ) {
1039 if ( $this->exists() ) {
1040 $restrictions = $this->getRestrictions( $action );
1041 if ( count( $restrictions ) > 0 ) {
1042 foreach ( $restrictions as $restriction ) {
1043 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1044 return false;
1045 }
1046 }
1047 } else {
1048 # Not protected
1049 return false;
1050 }
1051 return true;
1052 } else {
1053 # If it doesn't exist, it can't be protected
1054 return false;
1055 }
1056 }
1057
1058 /**
1059 * Does the title correspond to a protected article?
1060 *
1061 * @param $action String the action the page is protected from,
1062 * by default checks all actions.
1063 * @return Bool
1064 */
1065 public function isProtected( $action = '' ) {
1066 global $wgRestrictionLevels;
1067
1068 $restrictionTypes = $this->getRestrictionTypes();
1069
1070 # Special pages have inherent protection
1071 if( $this->getNamespace() == NS_SPECIAL ) {
1072 return true;
1073 }
1074
1075 # Check regular protection levels
1076 foreach ( $restrictionTypes as $type ) {
1077 if ( $action == $type || $action == '' ) {
1078 $r = $this->getRestrictions( $type );
1079 foreach ( $wgRestrictionLevels as $level ) {
1080 if ( in_array( $level, $r ) && $level != '' ) {
1081 return true;
1082 }
1083 }
1084 }
1085 }
1086
1087 return false;
1088 }
1089
1090 /**
1091 * Is this a conversion table for the LanguageConverter?
1092 *
1093 * @return Bool
1094 */
1095 public function isConversionTable() {
1096 if(
1097 $this->getNamespace() == NS_MEDIAWIKI &&
1098 strpos( $this->getText(), 'Conversiontable' ) !== false
1099 )
1100 {
1101 return true;
1102 }
1103
1104 return false;
1105 }
1106
1107 /**
1108 * Is $wgUser watching this page?
1109 *
1110 * @return Bool
1111 */
1112 public function userIsWatching() {
1113 global $wgUser;
1114
1115 if ( is_null( $this->mWatched ) ) {
1116 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1117 $this->mWatched = false;
1118 } else {
1119 $this->mWatched = $wgUser->isWatched( $this );
1120 }
1121 }
1122 return $this->mWatched;
1123 }
1124
1125 /**
1126 * Can $wgUser perform $action on this page?
1127 * This skips potentially expensive cascading permission checks
1128 * as well as avoids expensive error formatting
1129 *
1130 * Suitable for use for nonessential UI controls in common cases, but
1131 * _not_ for functional access control.
1132 *
1133 * May provide false positives, but should never provide a false negative.
1134 *
1135 * @param $action String action that permission needs to be checked for
1136 * @return Bool
1137 */
1138 public function quickUserCan( $action ) {
1139 return $this->userCan( $action, false );
1140 }
1141
1142 /**
1143 * Determines if $user is unable to edit this page because it has been protected
1144 * by $wgNamespaceProtection.
1145 *
1146 * @param $user User object, $wgUser will be used if not passed
1147 * @return Bool
1148 */
1149 public function isNamespaceProtected( User $user = null ) {
1150 global $wgNamespaceProtection;
1151
1152 if ( $user === null ) {
1153 global $wgUser;
1154 $user = $wgUser;
1155 }
1156
1157 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1158 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1159 if ( $right != '' && !$user->isAllowed( $right ) ) {
1160 return true;
1161 }
1162 }
1163 }
1164 return false;
1165 }
1166
1167 /**
1168 * Can $wgUser perform $action on this page?
1169 *
1170 * @param $action String action that permission needs to be checked for
1171 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1172 * @return Bool
1173 */
1174 public function userCan( $action, $doExpensiveQueries = true ) {
1175 global $wgUser;
1176 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1177 }
1178
1179 /**
1180 * Can $user perform $action on this page?
1181 *
1182 * FIXME: This *does not* check throttles (User::pingLimiter()).
1183 *
1184 * @param $action String action that permission needs to be checked for
1185 * @param $user User to check
1186 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1187 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1188 * @return Array of arguments to wfMsg to explain permissions problems.
1189 */
1190 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1191 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1192
1193 // Remove the errors being ignored.
1194 foreach ( $errors as $index => $error ) {
1195 $error_key = is_array( $error ) ? $error[0] : $error;
1196
1197 if ( in_array( $error_key, $ignoreErrors ) ) {
1198 unset( $errors[$index] );
1199 }
1200 }
1201
1202 return $errors;
1203 }
1204
1205 /**
1206 * Permissions checks that fail most often, and which are easiest to test.
1207 *
1208 * @param $action String the action to check
1209 * @param $user User user to check
1210 * @param $errors Array list of current errors
1211 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1212 * @param $short Boolean short circuit on first error
1213 *
1214 * @return Array list of errors
1215 */
1216 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1217 if ( $action == 'create' ) {
1218 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1219 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1220 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1221 }
1222 } elseif ( $action == 'move' ) {
1223 if ( !$user->isAllowed( 'move-rootuserpages' )
1224 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1225 // Show user page-specific message only if the user can move other pages
1226 $errors[] = array( 'cant-move-user-page' );
1227 }
1228
1229 // Check if user is allowed to move files if it's a file
1230 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1231 $errors[] = array( 'movenotallowedfile' );
1232 }
1233
1234 if ( !$user->isAllowed( 'move' ) ) {
1235 // User can't move anything
1236 global $wgGroupPermissions;
1237 $userCanMove = false;
1238 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1239 $userCanMove = $wgGroupPermissions['user']['move'];
1240 }
1241 $autoconfirmedCanMove = false;
1242 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1243 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1244 }
1245 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1246 // custom message if logged-in users without any special rights can move
1247 $errors[] = array( 'movenologintext' );
1248 } else {
1249 $errors[] = array( 'movenotallowed' );
1250 }
1251 }
1252 } elseif ( $action == 'move-target' ) {
1253 if ( !$user->isAllowed( 'move' ) ) {
1254 // User can't move anything
1255 $errors[] = array( 'movenotallowed' );
1256 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1257 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1258 // Show user page-specific message only if the user can move other pages
1259 $errors[] = array( 'cant-move-to-user-page' );
1260 }
1261 } elseif ( !$user->isAllowed( $action ) ) {
1262 // We avoid expensive display logic for quickUserCan's and such
1263 $groups = false;
1264 if ( !$short ) {
1265 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1266 User::getGroupsWithPermission( $action ) );
1267 }
1268
1269 if ( $groups ) {
1270 global $wgLang;
1271 $return = array(
1272 'badaccess-groups',
1273 $wgLang->commaList( $groups ),
1274 count( $groups )
1275 );
1276 } else {
1277 $return = array( 'badaccess-group0' );
1278 }
1279 $errors[] = $return;
1280 }
1281
1282 return $errors;
1283 }
1284
1285 /**
1286 * Add the resulting error code to the errors array
1287 *
1288 * @param $errors Array list of current errors
1289 * @param $result Mixed result of errors
1290 *
1291 * @return Array list of errors
1292 */
1293 private function resultToError( $errors, $result ) {
1294 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1295 // A single array representing an error
1296 $errors[] = $result;
1297 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1298 // A nested array representing multiple errors
1299 $errors = array_merge( $errors, $result );
1300 } else if ( $result !== '' && is_string( $result ) ) {
1301 // A string representing a message-id
1302 $errors[] = array( $result );
1303 } else if ( $result === false ) {
1304 // a generic "We don't want them to do that"
1305 $errors[] = array( 'badaccess-group0' );
1306 }
1307 return $errors;
1308 }
1309
1310 /**
1311 * Check various permission hooks
1312 *
1313 * @param $action String the action to check
1314 * @param $user User user to check
1315 * @param $errors Array list of current errors
1316 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1317 * @param $short Boolean short circuit on first error
1318 *
1319 * @return Array list of errors
1320 */
1321 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1322 // Use getUserPermissionsErrors instead
1323 $result = '';
1324 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1325 return $result ? array() : array( array( 'badaccess-group0' ) );
1326 }
1327 // Check getUserPermissionsErrors hook
1328 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1329 $errors = $this->resultToError( $errors, $result );
1330 }
1331 // Check getUserPermissionsErrorsExpensive hook
1332 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1333 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1334 $errors = $this->resultToError( $errors, $result );
1335 }
1336
1337 return $errors;
1338 }
1339
1340 /**
1341 * Check permissions on special pages & namespaces
1342 *
1343 * @param $action String the action to check
1344 * @param $user User user to check
1345 * @param $errors Array list of current errors
1346 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1347 * @param $short Boolean short circuit on first error
1348 *
1349 * @return Array list of errors
1350 */
1351 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1352 # Only 'createaccount' and 'execute' can be performed on
1353 # special pages, which don't actually exist in the DB.
1354 $specialOKActions = array( 'createaccount', 'execute' );
1355 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1356 $errors[] = array( 'ns-specialprotected' );
1357 }
1358
1359 # Check $wgNamespaceProtection for restricted namespaces
1360 if ( $this->isNamespaceProtected( $user ) ) {
1361 $ns = $this->mNamespace == NS_MAIN ?
1362 wfMsg( 'nstab-main' ) : $this->getNsText();
1363 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1364 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1365 }
1366
1367 return $errors;
1368 }
1369
1370 /**
1371 * Check CSS/JS sub-page permissions
1372 *
1373 * @param $action String the action to check
1374 * @param $user User user to check
1375 * @param $errors Array list of current errors
1376 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1377 * @param $short Boolean short circuit on first error
1378 *
1379 * @return Array list of errors
1380 */
1381 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1382 # Protect css/js subpages of user pages
1383 # XXX: this might be better using restrictions
1384 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1385 # and $this->userCanEditJsSubpage() from working
1386 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1387 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1388 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1389 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1390 $errors[] = array( 'customcssjsprotected' );
1391 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1392 $errors[] = array( 'customcssjsprotected' );
1393 }
1394 }
1395
1396 return $errors;
1397 }
1398
1399 /**
1400 * Check against page_restrictions table requirements on this
1401 * page. The user must possess all required rights for this
1402 * action.
1403 *
1404 * @param $action String the action to check
1405 * @param $user User user to check
1406 * @param $errors Array list of current errors
1407 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1408 * @param $short Boolean short circuit on first error
1409 *
1410 * @return Array list of errors
1411 */
1412 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1413 foreach ( $this->getRestrictions( $action ) as $right ) {
1414 // Backwards compatibility, rewrite sysop -> protect
1415 if ( $right == 'sysop' ) {
1416 $right = 'protect';
1417 }
1418 if ( $right != '' && !$user->isAllowed( $right ) ) {
1419 // Users with 'editprotected' permission can edit protected pages
1420 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1421 // Users with 'editprotected' permission cannot edit protected pages
1422 // with cascading option turned on.
1423 if ( $this->mCascadeRestriction ) {
1424 $errors[] = array( 'protectedpagetext', $right );
1425 }
1426 } else {
1427 $errors[] = array( 'protectedpagetext', $right );
1428 }
1429 }
1430 }
1431
1432 return $errors;
1433 }
1434
1435 /**
1436 * Check restrictions on cascading pages.
1437 *
1438 * @param $action String the action to check
1439 * @param $user User to check
1440 * @param $errors Array list of current errors
1441 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1442 * @param $short Boolean short circuit on first error
1443 *
1444 * @return Array list of errors
1445 */
1446 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1447 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1448 # We /could/ use the protection level on the source page, but it's
1449 # fairly ugly as we have to establish a precedence hierarchy for pages
1450 # included by multiple cascade-protected pages. So just restrict
1451 # it to people with 'protect' permission, as they could remove the
1452 # protection anyway.
1453 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1454 # Cascading protection depends on more than this page...
1455 # Several cascading protected pages may include this page...
1456 # Check each cascading level
1457 # This is only for protection restrictions, not for all actions
1458 if ( isset( $restrictions[$action] ) ) {
1459 foreach ( $restrictions[$action] as $right ) {
1460 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1461 if ( $right != '' && !$user->isAllowed( $right ) ) {
1462 $pages = '';
1463 foreach ( $cascadingSources as $page )
1464 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1465 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1466 }
1467 }
1468 }
1469 }
1470
1471 return $errors;
1472 }
1473
1474 /**
1475 * Check action permissions not already checked in checkQuickPermissions
1476 *
1477 * @param $action String the action to check
1478 * @param $user User to check
1479 * @param $errors Array list of current errors
1480 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1481 * @param $short Boolean short circuit on first error
1482 *
1483 * @return Array list of errors
1484 */
1485 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1486 if ( $action == 'protect' ) {
1487 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1488 // If they can't edit, they shouldn't protect.
1489 $errors[] = array( 'protect-cantedit' );
1490 }
1491 } elseif ( $action == 'create' ) {
1492 $title_protection = $this->getTitleProtection();
1493 if( $title_protection ) {
1494 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1495 $title_protection['pt_create_perm'] = 'protect'; // B/C
1496 }
1497 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1498 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1499 }
1500 }
1501 } elseif ( $action == 'move' ) {
1502 // Check for immobile pages
1503 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1504 // Specific message for this case
1505 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1506 } elseif ( !$this->isMovable() ) {
1507 // Less specific message for rarer cases
1508 $errors[] = array( 'immobile-page' );
1509 }
1510 } elseif ( $action == 'move-target' ) {
1511 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1512 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1513 } elseif ( !$this->isMovable() ) {
1514 $errors[] = array( 'immobile-target-page' );
1515 }
1516 }
1517 return $errors;
1518 }
1519
1520 /**
1521 * Check that the user isn't blocked from editting.
1522 *
1523 * @param $action String the action to check
1524 * @param $user User to check
1525 * @param $errors Array list of current errors
1526 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1527 * @param $short Boolean short circuit on first error
1528 *
1529 * @return Array list of errors
1530 */
1531 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1532 if( $short && count( $errors ) > 0 ) {
1533 return $errors;
1534 }
1535
1536 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1537
1538 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1539 $errors[] = array( 'confirmedittext' );
1540 }
1541
1542 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1543 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1544 $block = $user->mBlock;
1545
1546 // This is from OutputPage::blockedPage
1547 // Copied at r23888 by werdna
1548
1549 $id = $user->blockedBy();
1550 $reason = $user->blockedFor();
1551 if ( $reason == '' ) {
1552 $reason = wfMsg( 'blockednoreason' );
1553 }
1554 $ip = wfGetIP();
1555
1556 if ( is_numeric( $id ) ) {
1557 $name = User::whoIs( $id );
1558 } else {
1559 $name = $id;
1560 }
1561
1562 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1563 $blockid = $block->mId;
1564 $blockExpiry = $user->mBlock->mExpiry;
1565 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1566 if ( $blockExpiry == 'infinity' ) {
1567 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1568 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1569
1570 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1571 if ( !strpos( $option, ':' ) )
1572 continue;
1573
1574 list( $show, $value ) = explode( ':', $option );
1575
1576 if ( $value == 'infinite' || $value == 'indefinite' ) {
1577 $blockExpiry = $show;
1578 break;
1579 }
1580 }
1581 } else {
1582 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1583 }
1584
1585 $intended = $user->mBlock->mAddress;
1586
1587 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1588 $blockid, $blockExpiry, $intended, $blockTimestamp );
1589 }
1590
1591 return $errors;
1592 }
1593
1594 /**
1595 * Can $user perform $action on this page? This is an internal function,
1596 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1597 * checks on wfReadOnly() and blocks)
1598 *
1599 * @param $action String action that permission needs to be checked for
1600 * @param $user User to check
1601 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1602 * @param $short Bool Set this to true to stop after the first permission error.
1603 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1604 */
1605 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1606 wfProfileIn( __METHOD__ );
1607
1608 $errors = array();
1609 $checks = array(
1610 'checkQuickPermissions',
1611 'checkPermissionHooks',
1612 'checkSpecialsAndNSPermissions',
1613 'checkCSSandJSPermissions',
1614 'checkPageRestrictions',
1615 'checkCascadingSourcesRestrictions',
1616 'checkActionPermissions',
1617 'checkUserBlock'
1618 );
1619
1620 while( count( $checks ) > 0 &&
1621 !( $short && count( $errors ) > 0 ) ) {
1622 $method = array_shift( $checks );
1623 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1624 }
1625
1626 wfProfileOut( __METHOD__ );
1627 return $errors;
1628 }
1629
1630 /**
1631 * Is this title subject to title protection?
1632 * Title protection is the one applied against creation of such title.
1633 *
1634 * @return Mixed An associative array representing any existent title
1635 * protection, or false if there's none.
1636 */
1637 private function getTitleProtection() {
1638 // Can't protect pages in special namespaces
1639 if ( $this->getNamespace() < 0 ) {
1640 return false;
1641 }
1642
1643 // Can't protect pages that exist.
1644 if ( $this->exists() ) {
1645 return false;
1646 }
1647
1648 if ( !isset( $this->mTitleProtection ) ) {
1649 $dbr = wfGetDB( DB_SLAVE );
1650 $res = $dbr->select( 'protected_titles', '*',
1651 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1652 __METHOD__ );
1653
1654 // fetchRow returns false if there are no rows.
1655 $this->mTitleProtection = $dbr->fetchRow( $res );
1656 }
1657 return $this->mTitleProtection;
1658 }
1659
1660 /**
1661 * Update the title protection status
1662 *
1663 * @param $create_perm String Permission required for creation
1664 * @param $reason String Reason for protection
1665 * @param $expiry String Expiry timestamp
1666 * @return boolean true
1667 */
1668 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1669 global $wgUser, $wgContLang;
1670
1671 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1672 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1673 // No change
1674 return true;
1675 }
1676
1677 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1678
1679 $dbw = wfGetDB( DB_MASTER );
1680
1681 $encodedExpiry = Block::encodeExpiry( $expiry, $dbw );
1682
1683 $expiry_description = '';
1684 if ( $encodedExpiry != 'infinity' ) {
1685 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1686 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1687 } else {
1688 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1689 }
1690
1691 # Update protection table
1692 if ( $create_perm != '' ) {
1693 $this->mTitleProtection = array(
1694 'pt_namespace' => $namespace,
1695 'pt_title' => $title,
1696 'pt_create_perm' => $create_perm,
1697 'pt_timestamp' => Block::encodeExpiry( wfTimestampNow(), $dbw ),
1698 'pt_expiry' => $encodedExpiry,
1699 'pt_user' => $wgUser->getId(),
1700 'pt_reason' => $reason,
1701 );
1702 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1703 $this->mTitleProtection, __METHOD__ );
1704 } else {
1705 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1706 'pt_title' => $title ), __METHOD__ );
1707 $this->mTitleProtection = false;
1708 }
1709
1710 # Update the protection log
1711 if ( $dbw->affectedRows() ) {
1712 $log = new LogPage( 'protect' );
1713
1714 if ( $create_perm ) {
1715 $params = array( "[create=$create_perm] $expiry_description", '' );
1716 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1717 } else {
1718 $log->addEntry( 'unprotect', $this, $reason );
1719 }
1720 }
1721
1722 return true;
1723 }
1724
1725 /**
1726 * Remove any title protection due to page existing
1727 */
1728 public function deleteTitleProtection() {
1729 $dbw = wfGetDB( DB_MASTER );
1730
1731 $dbw->delete(
1732 'protected_titles',
1733 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1734 __METHOD__
1735 );
1736 $this->mTitleProtection = false;
1737 }
1738
1739 /**
1740 * Would anybody with sufficient privileges be able to move this page?
1741 * Some pages just aren't movable.
1742 *
1743 * @return Bool TRUE or FALSE
1744 */
1745 public function isMovable() {
1746 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1747 }
1748
1749 /**
1750 * Can $wgUser read this page?
1751 *
1752 * @return Bool
1753 * @todo fold these checks into userCan()
1754 */
1755 public function userCanRead() {
1756 global $wgUser, $wgGroupPermissions;
1757
1758 static $useShortcut = null;
1759
1760 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1761 if ( is_null( $useShortcut ) ) {
1762 global $wgRevokePermissions;
1763 $useShortcut = true;
1764 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1765 # Not a public wiki, so no shortcut
1766 $useShortcut = false;
1767 } elseif ( !empty( $wgRevokePermissions ) ) {
1768 /*
1769 * Iterate through each group with permissions being revoked (key not included since we don't care
1770 * what the group name is), then check if the read permission is being revoked. If it is, then
1771 * we don't use the shortcut below since the user might not be able to read, even though anon
1772 * reading is allowed.
1773 */
1774 foreach ( $wgRevokePermissions as $perms ) {
1775 if ( !empty( $perms['read'] ) ) {
1776 # We might be removing the read right from the user, so no shortcut
1777 $useShortcut = false;
1778 break;
1779 }
1780 }
1781 }
1782 }
1783
1784 $result = null;
1785 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1786 if ( $result !== null ) {
1787 return $result;
1788 }
1789
1790 # Shortcut for public wikis, allows skipping quite a bit of code
1791 if ( $useShortcut ) {
1792 return true;
1793 }
1794
1795 if ( $wgUser->isAllowed( 'read' ) ) {
1796 return true;
1797 } else {
1798 global $wgWhitelistRead;
1799
1800 # Always grant access to the login page.
1801 # Even anons need to be able to log in.
1802 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1803 return true;
1804 }
1805
1806 # Bail out if there isn't whitelist
1807 if ( !is_array( $wgWhitelistRead ) ) {
1808 return false;
1809 }
1810
1811 # Check for explicit whitelisting
1812 $name = $this->getPrefixedText();
1813 $dbName = $this->getPrefixedDBKey();
1814 // Check with and without underscores
1815 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1816 return true;
1817
1818 # Old settings might have the title prefixed with
1819 # a colon for main-namespace pages
1820 if ( $this->getNamespace() == NS_MAIN ) {
1821 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1822 return true;
1823 }
1824 }
1825
1826 # If it's a special page, ditch the subpage bit and check again
1827 if ( $this->getNamespace() == NS_SPECIAL ) {
1828 $name = $this->getDBkey();
1829 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1830 if ( $name === false ) {
1831 # Invalid special page, but we show standard login required message
1832 return false;
1833 }
1834
1835 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1836 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1837 return true;
1838 }
1839 }
1840
1841 }
1842 return false;
1843 }
1844
1845 /**
1846 * Is this the mainpage?
1847 * @note Title::newFromText seams to be sufficiently optimized by the title
1848 * cache that we don't need to over-optimize by doing direct comparisons and
1849 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1850 * ends up reporting something differently than $title->isMainPage();
1851 *
1852 * @return Bool
1853 */
1854 public function isMainPage() {
1855 return $this->equals( Title::newMainPage() );
1856 }
1857
1858 /**
1859 * Is this a talk page of some sort?
1860 *
1861 * @return Bool
1862 */
1863 public function isTalkPage() {
1864 return MWNamespace::isTalk( $this->getNamespace() );
1865 }
1866
1867 /**
1868 * Is this a subpage?
1869 *
1870 * @return Bool
1871 */
1872 public function isSubpage() {
1873 return MWNamespace::hasSubpages( $this->mNamespace )
1874 ? strpos( $this->getText(), '/' ) !== false
1875 : false;
1876 }
1877
1878 /**
1879 * Does this have subpages? (Warning, usually requires an extra DB query.)
1880 *
1881 * @return Bool
1882 */
1883 public function hasSubpages() {
1884 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1885 # Duh
1886 return false;
1887 }
1888
1889 # We dynamically add a member variable for the purpose of this method
1890 # alone to cache the result. There's no point in having it hanging
1891 # around uninitialized in every Title object; therefore we only add it
1892 # if needed and don't declare it statically.
1893 if ( isset( $this->mHasSubpages ) ) {
1894 return $this->mHasSubpages;
1895 }
1896
1897 $subpages = $this->getSubpages( 1 );
1898 if ( $subpages instanceof TitleArray ) {
1899 return $this->mHasSubpages = (bool)$subpages->count();
1900 }
1901 return $this->mHasSubpages = false;
1902 }
1903
1904 /**
1905 * Get all subpages of this page.
1906 *
1907 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1908 * @return mixed TitleArray, or empty array if this page's namespace
1909 * doesn't allow subpages
1910 */
1911 public function getSubpages( $limit = -1 ) {
1912 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1913 return array();
1914 }
1915
1916 $dbr = wfGetDB( DB_SLAVE );
1917 $conds['page_namespace'] = $this->getNamespace();
1918 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1919 $options = array();
1920 if ( $limit > -1 ) {
1921 $options['LIMIT'] = $limit;
1922 }
1923 return $this->mSubpages = TitleArray::newFromResult(
1924 $dbr->select( 'page',
1925 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1926 $conds,
1927 __METHOD__,
1928 $options
1929 )
1930 );
1931 }
1932
1933 /**
1934 * Could this page contain custom CSS or JavaScript, based
1935 * on the title?
1936 *
1937 * @return Bool
1938 */
1939 public function isCssOrJsPage() {
1940 return $this->mNamespace == NS_MEDIAWIKI
1941 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1942 }
1943
1944 /**
1945 * Is this a .css or .js subpage of a user page?
1946 * @return Bool
1947 */
1948 public function isCssJsSubpage() {
1949 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1950 }
1951
1952 /**
1953 * Is this a *valid* .css or .js subpage of a user page?
1954 *
1955 * @return Bool
1956 * @deprecated @since 1.17
1957 */
1958 public function isValidCssJsSubpage() {
1959 return $this->isCssJsSubpage();
1960 }
1961
1962 /**
1963 * Trim down a .css or .js subpage title to get the corresponding skin name
1964 *
1965 * @return string containing skin name from .css or .js subpage title
1966 */
1967 public function getSkinFromCssJsSubpage() {
1968 $subpage = explode( '/', $this->mTextform );
1969 $subpage = $subpage[ count( $subpage ) - 1 ];
1970 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1971 }
1972
1973 /**
1974 * Is this a .css subpage of a user page?
1975 *
1976 * @return Bool
1977 */
1978 public function isCssSubpage() {
1979 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1980 }
1981
1982 /**
1983 * Is this a .js subpage of a user page?
1984 *
1985 * @return Bool
1986 */
1987 public function isJsSubpage() {
1988 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1989 }
1990
1991 /**
1992 * Protect css subpages of user pages: can $wgUser edit
1993 * this page?
1994 *
1995 * @return Bool
1996 * @todo XXX: this might be better using restrictions
1997 */
1998 public function userCanEditCssSubpage() {
1999 global $wgUser;
2000 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
2001 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2002 }
2003
2004 /**
2005 * Protect js subpages of user pages: can $wgUser edit
2006 * this page?
2007 *
2008 * @return Bool
2009 * @todo XXX: this might be better using restrictions
2010 */
2011 public function userCanEditJsSubpage() {
2012 global $wgUser;
2013 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
2014 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2015 }
2016
2017 /**
2018 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2019 *
2020 * @return Bool If the page is subject to cascading restrictions.
2021 */
2022 public function isCascadeProtected() {
2023 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2024 return ( $sources > 0 );
2025 }
2026
2027 /**
2028 * Cascading protection: Get the source of any cascading restrictions on this page.
2029 *
2030 * @param $getPages Bool Whether or not to retrieve the actual pages
2031 * that the restrictions have come from.
2032 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2033 * have come, false for none, or true if such restrictions exist, but $getPages
2034 * was not set. The restriction array is an array of each type, each of which
2035 * contains a array of unique groups.
2036 */
2037 public function getCascadeProtectionSources( $getPages = true ) {
2038 $pagerestrictions = array();
2039
2040 if ( isset( $this->mCascadeSources ) && $getPages ) {
2041 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2042 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2043 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2044 }
2045
2046 wfProfileIn( __METHOD__ );
2047
2048 $dbr = wfGetDB( DB_SLAVE );
2049
2050 if ( $this->getNamespace() == NS_FILE ) {
2051 $tables = array( 'imagelinks', 'page_restrictions' );
2052 $where_clauses = array(
2053 'il_to' => $this->getDBkey(),
2054 'il_from=pr_page',
2055 'pr_cascade' => 1
2056 );
2057 } else {
2058 $tables = array( 'templatelinks', 'page_restrictions' );
2059 $where_clauses = array(
2060 'tl_namespace' => $this->getNamespace(),
2061 'tl_title' => $this->getDBkey(),
2062 'tl_from=pr_page',
2063 'pr_cascade' => 1
2064 );
2065 }
2066
2067 if ( $getPages ) {
2068 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2069 'pr_expiry', 'pr_type', 'pr_level' );
2070 $where_clauses[] = 'page_id=pr_page';
2071 $tables[] = 'page';
2072 } else {
2073 $cols = array( 'pr_expiry' );
2074 }
2075
2076 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2077
2078 $sources = $getPages ? array() : false;
2079 $now = wfTimestampNow();
2080 $purgeExpired = false;
2081
2082 foreach ( $res as $row ) {
2083 $expiry = Block::decodeExpiry( $row->pr_expiry );
2084 if ( $expiry > $now ) {
2085 if ( $getPages ) {
2086 $page_id = $row->pr_page;
2087 $page_ns = $row->page_namespace;
2088 $page_title = $row->page_title;
2089 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2090 # Add groups needed for each restriction type if its not already there
2091 # Make sure this restriction type still exists
2092
2093 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2094 $pagerestrictions[$row->pr_type] = array();
2095 }
2096
2097 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2098 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2099 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2100 }
2101 } else {
2102 $sources = true;
2103 }
2104 } else {
2105 // Trigger lazy purge of expired restrictions from the db
2106 $purgeExpired = true;
2107 }
2108 }
2109 if ( $purgeExpired ) {
2110 Title::purgeExpiredRestrictions();
2111 }
2112
2113 if ( $getPages ) {
2114 $this->mCascadeSources = $sources;
2115 $this->mCascadingRestrictions = $pagerestrictions;
2116 } else {
2117 $this->mHasCascadingRestrictions = $sources;
2118 }
2119
2120 wfProfileOut( __METHOD__ );
2121 return array( $sources, $pagerestrictions );
2122 }
2123
2124 /**
2125 * Returns cascading restrictions for the current article
2126 *
2127 * @return Boolean
2128 */
2129 function areRestrictionsCascading() {
2130 if ( !$this->mRestrictionsLoaded ) {
2131 $this->loadRestrictions();
2132 }
2133
2134 return $this->mCascadeRestriction;
2135 }
2136
2137 /**
2138 * Loads a string into mRestrictions array
2139 *
2140 * @param $res Resource restrictions as an SQL result.
2141 * @param $oldFashionedRestrictions String comma-separated list of page
2142 * restrictions from page table (pre 1.10)
2143 */
2144 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2145 $rows = array();
2146
2147 foreach ( $res as $row ) {
2148 $rows[] = $row;
2149 }
2150
2151 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2152 }
2153
2154 /**
2155 * Compiles list of active page restrictions from both page table (pre 1.10)
2156 * and page_restrictions table for this existing page.
2157 * Public for usage by LiquidThreads.
2158 *
2159 * @param $rows array of db result objects
2160 * @param $oldFashionedRestrictions string comma-separated list of page
2161 * restrictions from page table (pre 1.10)
2162 */
2163 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2164 $dbr = wfGetDB( DB_SLAVE );
2165
2166 $restrictionTypes = $this->getRestrictionTypes();
2167
2168 foreach ( $restrictionTypes as $type ) {
2169 $this->mRestrictions[$type] = array();
2170 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry( '' );
2171 }
2172
2173 $this->mCascadeRestriction = false;
2174
2175 # Backwards-compatibility: also load the restrictions from the page record (old format).
2176
2177 if ( $oldFashionedRestrictions === null ) {
2178 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2179 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2180 }
2181
2182 if ( $oldFashionedRestrictions != '' ) {
2183
2184 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2185 $temp = explode( '=', trim( $restrict ) );
2186 if ( count( $temp ) == 1 ) {
2187 // old old format should be treated as edit/move restriction
2188 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2189 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2190 } else {
2191 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2192 }
2193 }
2194
2195 $this->mOldRestrictions = true;
2196
2197 }
2198
2199 if ( count( $rows ) ) {
2200 # Current system - load second to make them override.
2201 $now = wfTimestampNow();
2202 $purgeExpired = false;
2203
2204 # Cycle through all the restrictions.
2205 foreach ( $rows as $row ) {
2206
2207 // Don't take care of restrictions types that aren't allowed
2208 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2209 continue;
2210
2211 // This code should be refactored, now that it's being used more generally,
2212 // But I don't really see any harm in leaving it in Block for now -werdna
2213 $expiry = Block::decodeExpiry( $row->pr_expiry );
2214
2215 // Only apply the restrictions if they haven't expired!
2216 if ( !$expiry || $expiry > $now ) {
2217 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2218 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2219
2220 $this->mCascadeRestriction |= $row->pr_cascade;
2221 } else {
2222 // Trigger a lazy purge of expired restrictions
2223 $purgeExpired = true;
2224 }
2225 }
2226
2227 if ( $purgeExpired ) {
2228 Title::purgeExpiredRestrictions();
2229 }
2230 }
2231
2232 $this->mRestrictionsLoaded = true;
2233 }
2234
2235 /**
2236 * Load restrictions from the page_restrictions table
2237 *
2238 * @param $oldFashionedRestrictions String comma-separated list of page
2239 * restrictions from page table (pre 1.10)
2240 */
2241 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2242 if ( !$this->mRestrictionsLoaded ) {
2243 if ( $this->exists() ) {
2244 $dbr = wfGetDB( DB_SLAVE );
2245
2246 $res = $dbr->select( 'page_restrictions', '*',
2247 array( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2248
2249 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2250 } else {
2251 $title_protection = $this->getTitleProtection();
2252
2253 if ( $title_protection ) {
2254 $now = wfTimestampNow();
2255 $expiry = Block::decodeExpiry( $title_protection['pt_expiry'] );
2256
2257 if ( !$expiry || $expiry > $now ) {
2258 // Apply the restrictions
2259 $this->mRestrictionsExpiry['create'] = $expiry;
2260 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2261 } else { // Get rid of the old restrictions
2262 Title::purgeExpiredRestrictions();
2263 $this->mTitleProtection = false;
2264 }
2265 } else {
2266 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry( '' );
2267 }
2268 $this->mRestrictionsLoaded = true;
2269 }
2270 }
2271 }
2272
2273 /**
2274 * Purge expired restrictions from the page_restrictions table
2275 */
2276 static function purgeExpiredRestrictions() {
2277 $dbw = wfGetDB( DB_MASTER );
2278 $dbw->delete(
2279 'page_restrictions',
2280 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2281 __METHOD__
2282 );
2283
2284 $dbw->delete(
2285 'protected_titles',
2286 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2287 __METHOD__
2288 );
2289 }
2290
2291 /**
2292 * Accessor/initialisation for mRestrictions
2293 *
2294 * @param $action String action that permission needs to be checked for
2295 * @return Array of Strings the array of groups allowed to edit this article
2296 */
2297 public function getRestrictions( $action ) {
2298 if ( !$this->mRestrictionsLoaded ) {
2299 $this->loadRestrictions();
2300 }
2301 return isset( $this->mRestrictions[$action] )
2302 ? $this->mRestrictions[$action]
2303 : array();
2304 }
2305
2306 /**
2307 * Get the expiry time for the restriction against a given action
2308 *
2309 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2310 * or not protected at all, or false if the action is not recognised.
2311 */
2312 public function getRestrictionExpiry( $action ) {
2313 if ( !$this->mRestrictionsLoaded ) {
2314 $this->loadRestrictions();
2315 }
2316 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2317 }
2318
2319 /**
2320 * Is there a version of this page in the deletion archive?
2321 *
2322 * @return Int the number of archived revisions
2323 */
2324 public function isDeleted() {
2325 if ( $this->getNamespace() < 0 ) {
2326 $n = 0;
2327 } else {
2328 $dbr = wfGetDB( DB_SLAVE );
2329 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2330 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2331 __METHOD__
2332 );
2333 if ( $this->getNamespace() == NS_FILE ) {
2334 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2335 array( 'fa_name' => $this->getDBkey() ),
2336 __METHOD__
2337 );
2338 }
2339 }
2340 return (int)$n;
2341 }
2342
2343 /**
2344 * Is there a version of this page in the deletion archive?
2345 *
2346 * @return Boolean
2347 */
2348 public function isDeletedQuick() {
2349 if ( $this->getNamespace() < 0 ) {
2350 return false;
2351 }
2352 $dbr = wfGetDB( DB_SLAVE );
2353 $deleted = (bool)$dbr->selectField( 'archive', '1',
2354 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2355 __METHOD__
2356 );
2357 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2358 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2359 array( 'fa_name' => $this->getDBkey() ),
2360 __METHOD__
2361 );
2362 }
2363 return $deleted;
2364 }
2365
2366 /**
2367 * Get the article ID for this Title from the link cache,
2368 * adding it if necessary
2369 *
2370 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2371 * for update
2372 * @return Int the ID
2373 */
2374 public function getArticleID( $flags = 0 ) {
2375 if ( $this->getNamespace() < 0 ) {
2376 return $this->mArticleID = 0;
2377 }
2378 $linkCache = LinkCache::singleton();
2379 if ( $flags & self::GAID_FOR_UPDATE ) {
2380 $oldUpdate = $linkCache->forUpdate( true );
2381 $linkCache->clearLink( $this );
2382 $this->mArticleID = $linkCache->addLinkObj( $this );
2383 $linkCache->forUpdate( $oldUpdate );
2384 } else {
2385 if ( -1 == $this->mArticleID ) {
2386 $this->mArticleID = $linkCache->addLinkObj( $this );
2387 }
2388 }
2389 return $this->mArticleID;
2390 }
2391
2392 /**
2393 * Is this an article that is a redirect page?
2394 * Uses link cache, adding it if necessary
2395 *
2396 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2397 * @return Bool
2398 */
2399 public function isRedirect( $flags = 0 ) {
2400 if ( !is_null( $this->mRedirect ) ) {
2401 return $this->mRedirect;
2402 }
2403 # Calling getArticleID() loads the field from cache as needed
2404 if ( !$this->getArticleID( $flags ) ) {
2405 return $this->mRedirect = false;
2406 }
2407 $linkCache = LinkCache::singleton();
2408 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2409
2410 return $this->mRedirect;
2411 }
2412
2413 /**
2414 * What is the length of this page?
2415 * Uses link cache, adding it if necessary
2416 *
2417 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2418 * @return Int
2419 */
2420 public function getLength( $flags = 0 ) {
2421 if ( $this->mLength != -1 ) {
2422 return $this->mLength;
2423 }
2424 # Calling getArticleID() loads the field from cache as needed
2425 if ( !$this->getArticleID( $flags ) ) {
2426 return $this->mLength = 0;
2427 }
2428 $linkCache = LinkCache::singleton();
2429 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2430
2431 return $this->mLength;
2432 }
2433
2434 /**
2435 * What is the page_latest field for this page?
2436 *
2437 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2438 * @return Int or 0 if the page doesn't exist
2439 */
2440 public function getLatestRevID( $flags = 0 ) {
2441 if ( $this->mLatestID !== false ) {
2442 return intval( $this->mLatestID );
2443 }
2444 # Calling getArticleID() loads the field from cache as needed
2445 if ( !$this->getArticleID( $flags ) ) {
2446 return $this->mLatestID = 0;
2447 }
2448 $linkCache = LinkCache::singleton();
2449 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2450
2451 return $this->mLatestID;
2452 }
2453
2454 /**
2455 * This clears some fields in this object, and clears any associated
2456 * keys in the "bad links" section of the link cache.
2457 *
2458 * - This is called from Article::doEdit() and Article::insertOn() to allow
2459 * loading of the new page_id. It's also called from
2460 * Article::doDeleteArticle()
2461 *
2462 * @param $newid Int the new Article ID
2463 */
2464 public function resetArticleID( $newid ) {
2465 $linkCache = LinkCache::singleton();
2466 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2467
2468 if ( $newid === false ) {
2469 $this->mArticleID = -1;
2470 } else {
2471 $this->mArticleID = intval( $newid );
2472 }
2473 $this->mRestrictionsLoaded = false;
2474 $this->mRestrictions = array();
2475 $this->mRedirect = null;
2476 $this->mLength = -1;
2477 $this->mLatestID = false;
2478 }
2479
2480 /**
2481 * Updates page_touched for this page; called from LinksUpdate.php
2482 *
2483 * @return Bool true if the update succeded
2484 */
2485 public function invalidateCache() {
2486 if ( wfReadOnly() ) {
2487 return;
2488 }
2489 $dbw = wfGetDB( DB_MASTER );
2490 $success = $dbw->update(
2491 'page',
2492 array( 'page_touched' => $dbw->timestamp() ),
2493 $this->pageCond(),
2494 __METHOD__
2495 );
2496 HTMLFileCache::clearFileCache( $this );
2497 return $success;
2498 }
2499
2500 /**
2501 * Prefix some arbitrary text with the namespace or interwiki prefix
2502 * of this object
2503 *
2504 * @param $name String the text
2505 * @return String the prefixed text
2506 * @private
2507 */
2508 /* private */ function prefix( $name ) {
2509 $p = '';
2510 if ( $this->mInterwiki != '' ) {
2511 $p = $this->mInterwiki . ':';
2512 }
2513
2514 if ( 0 != $this->mNamespace ) {
2515 $p .= $this->getNsText() . ':';
2516 }
2517 return $p . $name;
2518 }
2519
2520 /**
2521 * Returns a simple regex that will match on characters and sequences invalid in titles.
2522 * Note that this doesn't pick up many things that could be wrong with titles, but that
2523 * replacing this regex with something valid will make many titles valid.
2524 *
2525 * @return String regex string
2526 */
2527 static function getTitleInvalidRegex() {
2528 static $rxTc = false;
2529 if ( !$rxTc ) {
2530 # Matching titles will be held as illegal.
2531 $rxTc = '/' .
2532 # Any character not allowed is forbidden...
2533 '[^' . Title::legalChars() . ']' .
2534 # URL percent encoding sequences interfere with the ability
2535 # to round-trip titles -- you can't link to them consistently.
2536 '|%[0-9A-Fa-f]{2}' .
2537 # XML/HTML character references produce similar issues.
2538 '|&[A-Za-z0-9\x80-\xff]+;' .
2539 '|&#[0-9]+;' .
2540 '|&#x[0-9A-Fa-f]+;' .
2541 '/S';
2542 }
2543
2544 return $rxTc;
2545 }
2546
2547 /**
2548 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2549 *
2550 * @param $text String containing title to capitalize
2551 * @param $ns int namespace index, defaults to NS_MAIN
2552 * @return String containing capitalized title
2553 */
2554 public static function capitalize( $text, $ns = NS_MAIN ) {
2555 global $wgContLang;
2556
2557 if ( MWNamespace::isCapitalized( $ns ) ) {
2558 return $wgContLang->ucfirst( $text );
2559 } else {
2560 return $text;
2561 }
2562 }
2563
2564 /**
2565 * Secure and split - main initialisation function for this object
2566 *
2567 * Assumes that mDbkeyform has been set, and is urldecoded
2568 * and uses underscores, but not otherwise munged. This function
2569 * removes illegal characters, splits off the interwiki and
2570 * namespace prefixes, sets the other forms, and canonicalizes
2571 * everything.
2572 *
2573 * @return Bool true on success
2574 */
2575 private function secureAndSplit() {
2576 global $wgContLang, $wgLocalInterwiki;
2577
2578 # Initialisation
2579 $rxTc = self::getTitleInvalidRegex();
2580
2581 $this->mInterwiki = $this->mFragment = '';
2582 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2583
2584 $dbkey = $this->mDbkeyform;
2585
2586 # Strip Unicode bidi override characters.
2587 # Sometimes they slip into cut-n-pasted page titles, where the
2588 # override chars get included in list displays.
2589 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2590
2591 # Clean up whitespace
2592 # Note: use of the /u option on preg_replace here will cause
2593 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2594 # conveniently disabling them.
2595 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2596 $dbkey = trim( $dbkey, '_' );
2597
2598 if ( $dbkey == '' ) {
2599 return false;
2600 }
2601
2602 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2603 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2604 return false;
2605 }
2606
2607 $this->mDbkeyform = $dbkey;
2608
2609 # Initial colon indicates main namespace rather than specified default
2610 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2611 if ( ':' == $dbkey { 0 } ) {
2612 $this->mNamespace = NS_MAIN;
2613 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2614 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2615 }
2616
2617 # Namespace or interwiki prefix
2618 $firstPass = true;
2619 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2620 do {
2621 $m = array();
2622 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2623 $p = $m[1];
2624 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2625 # Ordinary namespace
2626 $dbkey = $m[2];
2627 $this->mNamespace = $ns;
2628 # For Talk:X pages, check if X has a "namespace" prefix
2629 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2630 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2631 # Disallow Talk:File:x type titles...
2632 return false;
2633 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2634 # Disallow Talk:Interwiki:x type titles...
2635 return false;
2636 }
2637 }
2638 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2639 if ( !$firstPass ) {
2640 # Can't make a local interwiki link to an interwiki link.
2641 # That's just crazy!
2642 return false;
2643 }
2644
2645 # Interwiki link
2646 $dbkey = $m[2];
2647 $this->mInterwiki = $wgContLang->lc( $p );
2648
2649 # Redundant interwiki prefix to the local wiki
2650 if ( $wgLocalInterwiki !== false
2651 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2652 {
2653 if ( $dbkey == '' ) {
2654 # Can't have an empty self-link
2655 return false;
2656 }
2657 $this->mInterwiki = '';
2658 $firstPass = false;
2659 # Do another namespace split...
2660 continue;
2661 }
2662
2663 # If there's an initial colon after the interwiki, that also
2664 # resets the default namespace
2665 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2666 $this->mNamespace = NS_MAIN;
2667 $dbkey = substr( $dbkey, 1 );
2668 }
2669 }
2670 # If there's no recognized interwiki or namespace,
2671 # then let the colon expression be part of the title.
2672 }
2673 break;
2674 } while ( true );
2675
2676 # We already know that some pages won't be in the database!
2677 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2678 $this->mArticleID = 0;
2679 }
2680 $fragment = strstr( $dbkey, '#' );
2681 if ( false !== $fragment ) {
2682 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2683 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2684 # remove whitespace again: prevents "Foo_bar_#"
2685 # becoming "Foo_bar_"
2686 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2687 }
2688
2689 # Reject illegal characters.
2690 if ( preg_match( $rxTc, $dbkey ) ) {
2691 return false;
2692 }
2693
2694 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2695 # reachable due to the way web browsers deal with 'relative' URLs.
2696 # Also, they conflict with subpage syntax. Forbid them explicitly.
2697 if ( strpos( $dbkey, '.' ) !== false &&
2698 ( $dbkey === '.' || $dbkey === '..' ||
2699 strpos( $dbkey, './' ) === 0 ||
2700 strpos( $dbkey, '../' ) === 0 ||
2701 strpos( $dbkey, '/./' ) !== false ||
2702 strpos( $dbkey, '/../' ) !== false ||
2703 substr( $dbkey, -2 ) == '/.' ||
2704 substr( $dbkey, -3 ) == '/..' ) )
2705 {
2706 return false;
2707 }
2708
2709 # Magic tilde sequences? Nu-uh!
2710 if ( strpos( $dbkey, '~~~' ) !== false ) {
2711 return false;
2712 }
2713
2714 # Limit the size of titles to 255 bytes. This is typically the size of the
2715 # underlying database field. We make an exception for special pages, which
2716 # don't need to be stored in the database, and may edge over 255 bytes due
2717 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2718 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2719 strlen( $dbkey ) > 512 )
2720 {
2721 return false;
2722 }
2723
2724 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2725 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2726 # other site might be case-sensitive.
2727 $this->mUserCaseDBKey = $dbkey;
2728 if ( $this->mInterwiki == '' ) {
2729 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2730 }
2731
2732 # Can't make a link to a namespace alone... "empty" local links can only be
2733 # self-links with a fragment identifier.
2734 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2735 return false;
2736 }
2737
2738 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2739 // IP names are not allowed for accounts, and can only be referring to
2740 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2741 // there are numerous ways to present the same IP. Having sp:contribs scan
2742 // them all is silly and having some show the edits and others not is
2743 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2744 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2745 ? IP::sanitizeIP( $dbkey )
2746 : $dbkey;
2747
2748 // Any remaining initial :s are illegal.
2749 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2750 return false;
2751 }
2752
2753 # Fill fields
2754 $this->mDbkeyform = $dbkey;
2755 $this->mUrlform = wfUrlencode( $dbkey );
2756
2757 $this->mTextform = str_replace( '_', ' ', $dbkey );
2758
2759 return true;
2760 }
2761
2762 /**
2763 * Set the fragment for this title. Removes the first character from the
2764 * specified fragment before setting, so it assumes you're passing it with
2765 * an initial "#".
2766 *
2767 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2768 * Still in active use privately.
2769 *
2770 * @param $fragment String text
2771 */
2772 public function setFragment( $fragment ) {
2773 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2774 }
2775
2776 /**
2777 * Get a Title object associated with the talk page of this article
2778 *
2779 * @return Title the object for the talk page
2780 */
2781 public function getTalkPage() {
2782 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2783 }
2784
2785 /**
2786 * Get a title object associated with the subject page of this
2787 * talk page
2788 *
2789 * @return Title the object for the subject page
2790 */
2791 public function getSubjectPage() {
2792 // Is this the same title?
2793 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2794 if ( $this->getNamespace() == $subjectNS ) {
2795 return $this;
2796 }
2797 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2798 }
2799
2800 /**
2801 * Get an array of Title objects linking to this Title
2802 * Also stores the IDs in the link cache.
2803 *
2804 * WARNING: do not use this function on arbitrary user-supplied titles!
2805 * On heavily-used templates it will max out the memory.
2806 *
2807 * @param $options Array: may be FOR UPDATE
2808 * @param $table String: table name
2809 * @param $prefix String: fields prefix
2810 * @return Array of Title objects linking here
2811 */
2812 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2813 $linkCache = LinkCache::singleton();
2814
2815 if ( count( $options ) > 0 ) {
2816 $db = wfGetDB( DB_MASTER );
2817 } else {
2818 $db = wfGetDB( DB_SLAVE );
2819 }
2820
2821 $res = $db->select(
2822 array( 'page', $table ),
2823 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2824 array(
2825 "{$prefix}_from=page_id",
2826 "{$prefix}_namespace" => $this->getNamespace(),
2827 "{$prefix}_title" => $this->getDBkey() ),
2828 __METHOD__,
2829 $options
2830 );
2831
2832 $retVal = array();
2833 if ( $db->numRows( $res ) ) {
2834 foreach ( $res as $row ) {
2835 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2836 if ( $titleObj ) {
2837 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2838 $retVal[] = $titleObj;
2839 }
2840 }
2841 }
2842 return $retVal;
2843 }
2844
2845 /**
2846 * Get an array of Title objects using this Title as a template
2847 * Also stores the IDs in the link cache.
2848 *
2849 * WARNING: do not use this function on arbitrary user-supplied titles!
2850 * On heavily-used templates it will max out the memory.
2851 *
2852 * @param $options Array: may be FOR UPDATE
2853 * @return Array of Title the Title objects linking here
2854 */
2855 public function getTemplateLinksTo( $options = array() ) {
2856 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2857 }
2858
2859 /**
2860 * Get an array of Title objects referring to non-existent articles linked from this page
2861 *
2862 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2863 * @return Array of Title the Title objects
2864 */
2865 public function getBrokenLinksFrom() {
2866 if ( $this->getArticleId() == 0 ) {
2867 # All links from article ID 0 are false positives
2868 return array();
2869 }
2870
2871 $dbr = wfGetDB( DB_SLAVE );
2872 $res = $dbr->select(
2873 array( 'page', 'pagelinks' ),
2874 array( 'pl_namespace', 'pl_title' ),
2875 array(
2876 'pl_from' => $this->getArticleId(),
2877 'page_namespace IS NULL'
2878 ),
2879 __METHOD__, array(),
2880 array(
2881 'page' => array(
2882 'LEFT JOIN',
2883 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2884 )
2885 )
2886 );
2887
2888 $retVal = array();
2889 foreach ( $res as $row ) {
2890 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2891 }
2892 return $retVal;
2893 }
2894
2895
2896 /**
2897 * Get a list of URLs to purge from the Squid cache when this
2898 * page changes
2899 *
2900 * @return Array of String the URLs
2901 */
2902 public function getSquidURLs() {
2903 global $wgContLang;
2904
2905 $urls = array(
2906 $this->getInternalURL(),
2907 $this->getInternalURL( 'action=history' )
2908 );
2909
2910 // purge variant urls as well
2911 if ( $wgContLang->hasVariants() ) {
2912 $variants = $wgContLang->getVariants();
2913 foreach ( $variants as $vCode ) {
2914 $urls[] = $this->getInternalURL( '', $vCode );
2915 }
2916 }
2917
2918 return $urls;
2919 }
2920
2921 /**
2922 * Purge all applicable Squid URLs
2923 */
2924 public function purgeSquid() {
2925 global $wgUseSquid;
2926 if ( $wgUseSquid ) {
2927 $urls = $this->getSquidURLs();
2928 $u = new SquidUpdate( $urls );
2929 $u->doUpdate();
2930 }
2931 }
2932
2933 /**
2934 * Move this page without authentication
2935 *
2936 * @param $nt Title the new page Title
2937 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2938 */
2939 public function moveNoAuth( &$nt ) {
2940 return $this->moveTo( $nt, false );
2941 }
2942
2943 /**
2944 * Check whether a given move operation would be valid.
2945 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2946 *
2947 * @param $nt Title the new title
2948 * @param $auth Bool indicates whether $wgUser's permissions
2949 * should be checked
2950 * @param $reason String is the log summary of the move, used for spam checking
2951 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2952 */
2953 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2954 global $wgUser;
2955
2956 $errors = array();
2957 if ( !$nt ) {
2958 // Normally we'd add this to $errors, but we'll get
2959 // lots of syntax errors if $nt is not an object
2960 return array( array( 'badtitletext' ) );
2961 }
2962 if ( $this->equals( $nt ) ) {
2963 $errors[] = array( 'selfmove' );
2964 }
2965 if ( !$this->isMovable() ) {
2966 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2967 }
2968 if ( $nt->getInterwiki() != '' ) {
2969 $errors[] = array( 'immobile-target-namespace-iw' );
2970 }
2971 if ( !$nt->isMovable() ) {
2972 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2973 }
2974
2975 $oldid = $this->getArticleID();
2976 $newid = $nt->getArticleID();
2977
2978 if ( strlen( $nt->getDBkey() ) < 1 ) {
2979 $errors[] = array( 'articleexists' );
2980 }
2981 if ( ( $this->getDBkey() == '' ) ||
2982 ( !$oldid ) ||
2983 ( $nt->getDBkey() == '' ) ) {
2984 $errors[] = array( 'badarticleerror' );
2985 }
2986
2987 // Image-specific checks
2988 if ( $this->getNamespace() == NS_FILE ) {
2989 if ( $nt->getNamespace() != NS_FILE ) {
2990 $errors[] = array( 'imagenocrossnamespace' );
2991 }
2992 $file = wfLocalFile( $this );
2993 if ( $file->exists() ) {
2994 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2995 $errors[] = array( 'imageinvalidfilename' );
2996 }
2997 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2998 $errors[] = array( 'imagetypemismatch' );
2999 }
3000 }
3001 $destfile = wfLocalFile( $nt );
3002 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
3003 $errors[] = array( 'file-exists-sharedrepo' );
3004 }
3005 }
3006
3007 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3008 $errors[] = array( 'nonfile-cannot-move-to-file' );
3009 }
3010
3011 if ( $auth ) {
3012 $errors = wfMergeErrorArrays( $errors,
3013 $this->getUserPermissionsErrors( 'move', $wgUser ),
3014 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3015 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3016 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3017 }
3018
3019 $match = EditPage::matchSummarySpamRegex( $reason );
3020 if ( $match !== false ) {
3021 // This is kind of lame, won't display nice
3022 $errors[] = array( 'spamprotectiontext' );
3023 }
3024
3025 $err = null;
3026 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3027 $errors[] = array( 'hookaborted', $err );
3028 }
3029
3030 # The move is allowed only if (1) the target doesn't exist, or
3031 # (2) the target is a redirect to the source, and has no history
3032 # (so we can undo bad moves right after they're done).
3033
3034 if ( 0 != $newid ) { # Target exists; check for validity
3035 if ( !$this->isValidMoveTarget( $nt ) ) {
3036 $errors[] = array( 'articleexists' );
3037 }
3038 } else {
3039 $tp = $nt->getTitleProtection();
3040 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3041 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3042 $errors[] = array( 'cantmove-titleprotected' );
3043 }
3044 }
3045 if ( empty( $errors ) ) {
3046 return true;
3047 }
3048 return $errors;
3049 }
3050
3051 /**
3052 * Move a title to a new location
3053 *
3054 * @param $nt Title the new title
3055 * @param $auth Bool indicates whether $wgUser's permissions
3056 * should be checked
3057 * @param $reason String the reason for the move
3058 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3059 * Ignored if the user doesn't have the suppressredirect right.
3060 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3061 */
3062 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3063 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3064 if ( is_array( $err ) ) {
3065 return $err;
3066 }
3067
3068 // If it is a file, move it first. It is done before all other moving stuff is
3069 // done because it's hard to revert
3070 $dbw = wfGetDB( DB_MASTER );
3071 if ( $this->getNamespace() == NS_FILE ) {
3072 $file = wfLocalFile( $this );
3073 if ( $file->exists() ) {
3074 $status = $file->move( $nt );
3075 if ( !$status->isOk() ) {
3076 return $status->getErrorsArray();
3077 }
3078 }
3079 }
3080
3081 $pageid = $this->getArticleID();
3082 $protected = $this->isProtected();
3083 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3084
3085 // Do the actual move
3086 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3087 if ( is_array( $err ) ) {
3088 return $err;
3089 }
3090
3091 $redirid = $this->getArticleID();
3092
3093 // Refresh the sortkey for this row. Be careful to avoid resetting
3094 // cl_timestamp, which may disturb time-based lists on some sites.
3095 $prefix = $dbw->selectField(
3096 'categorylinks',
3097 'cl_sortkey_prefix',
3098 array( 'cl_from' => $pageid ),
3099 __METHOD__
3100 );
3101 $dbw->update( 'categorylinks',
3102 array(
3103 'cl_sortkey' => Collation::singleton()->getSortKey(
3104 $nt->getCategorySortkey( $prefix ) ),
3105 'cl_timestamp=cl_timestamp' ),
3106 array( 'cl_from' => $pageid ),
3107 __METHOD__ );
3108
3109 if ( $protected ) {
3110 # Protect the redirect title as the title used to be...
3111 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3112 array(
3113 'pr_page' => $redirid,
3114 'pr_type' => 'pr_type',
3115 'pr_level' => 'pr_level',
3116 'pr_cascade' => 'pr_cascade',
3117 'pr_user' => 'pr_user',
3118 'pr_expiry' => 'pr_expiry'
3119 ),
3120 array( 'pr_page' => $pageid ),
3121 __METHOD__,
3122 array( 'IGNORE' )
3123 );
3124 # Update the protection log
3125 $log = new LogPage( 'protect' );
3126 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3127 if ( $reason ) {
3128 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3129 }
3130 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3131 }
3132
3133 # Update watchlists
3134 $oldnamespace = $this->getNamespace() & ~1;
3135 $newnamespace = $nt->getNamespace() & ~1;
3136 $oldtitle = $this->getDBkey();
3137 $newtitle = $nt->getDBkey();
3138
3139 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3140 WatchedItem::duplicateEntries( $this, $nt );
3141 }
3142
3143 # Update search engine
3144 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3145 $u->doUpdate();
3146 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3147 $u->doUpdate();
3148
3149 # Update site_stats
3150 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3151 # No longer a content page
3152 # Not viewed, edited, removing
3153 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3154 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3155 # Now a content page
3156 # Not viewed, edited, adding
3157 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3158 } elseif ( $pageCountChange ) {
3159 # Redirect added
3160 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3161 } else {
3162 # Nothing special
3163 $u = false;
3164 }
3165 if ( $u ) {
3166 $u->doUpdate();
3167 }
3168 # Update message cache for interface messages
3169 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3170 # @bug 17860: old article can be deleted, if this the case,
3171 # delete it from message cache
3172 if ( $this->getArticleID() === 0 ) {
3173 MessageCache::singleton()->replace( $this->getDBkey(), false );
3174 } else {
3175 $oldarticle = new Article( $this );
3176 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3177 }
3178 }
3179 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3180 $newarticle = new Article( $nt );
3181 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3182 }
3183
3184 global $wgUser;
3185 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3186 return true;
3187 }
3188
3189 /**
3190 * Move page to a title which is either a redirect to the
3191 * source page or nonexistent
3192 *
3193 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3194 * @param $reason String The reason for the move
3195 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3196 * if the user doesn't have the suppressredirect right
3197 */
3198 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3199 global $wgUser, $wgContLang;
3200
3201 $moveOverRedirect = $nt->exists();
3202
3203 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3204 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3205
3206 if ( $reason ) {
3207 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3208 }
3209 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3210 $comment = $wgContLang->truncate( $comment, 250 );
3211
3212 $oldid = $this->getArticleID();
3213 $latest = $this->getLatestRevID();
3214
3215 $dbw = wfGetDB( DB_MASTER );
3216
3217 if ( $moveOverRedirect ) {
3218 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3219
3220 $newid = $nt->getArticleID();
3221 $newns = $nt->getNamespace();
3222 $newdbk = $nt->getDBkey();
3223
3224 # Delete the old redirect. We don't save it to history since
3225 # by definition if we've got here it's rather uninteresting.
3226 # We have to remove it so that the next step doesn't trigger
3227 # a conflict on the unique namespace+title index...
3228 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3229 if ( !$dbw->cascadingDeletes() ) {
3230 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3231 global $wgUseTrackbacks;
3232 if ( $wgUseTrackbacks ) {
3233 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3234 }
3235 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3236 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3237 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3238 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3239 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3240 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3241 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3242 }
3243 // If the target page was recently created, it may have an entry in recentchanges still
3244 $dbw->delete( 'recentchanges',
3245 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3246 __METHOD__
3247 );
3248 }
3249
3250 # Save a null revision in the page's history notifying of the move
3251 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3252 if ( !is_object( $nullRevision ) ) {
3253 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3254 }
3255 $nullRevId = $nullRevision->insertOn( $dbw );
3256
3257 $article = new Article( $this );
3258 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3259
3260 # Change the name of the target page:
3261 $dbw->update( 'page',
3262 /* SET */ array(
3263 'page_touched' => $dbw->timestamp(),
3264 'page_namespace' => $nt->getNamespace(),
3265 'page_title' => $nt->getDBkey(),
3266 'page_latest' => $nullRevId,
3267 ),
3268 /* WHERE */ array( 'page_id' => $oldid ),
3269 __METHOD__
3270 );
3271 $nt->resetArticleID( $oldid );
3272
3273 # Recreate the redirect, this time in the other direction.
3274 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3275 $mwRedir = MagicWord::get( 'redirect' );
3276 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3277 $redirectArticle = new Article( $this );
3278 $newid = $redirectArticle->insertOn( $dbw );
3279 $redirectRevision = new Revision( array(
3280 'page' => $newid,
3281 'comment' => $comment,
3282 'text' => $redirectText ) );
3283 $redirectRevision->insertOn( $dbw );
3284 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3285
3286 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3287
3288 # Now, we record the link from the redirect to the new title.
3289 # It should have no other outgoing links...
3290 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3291 $dbw->insert( 'pagelinks',
3292 array(
3293 'pl_from' => $newid,
3294 'pl_namespace' => $nt->getNamespace(),
3295 'pl_title' => $nt->getDBkey() ),
3296 __METHOD__ );
3297 $redirectSuppressed = false;
3298 } else {
3299 $this->resetArticleID( 0 );
3300 $redirectSuppressed = true;
3301 }
3302
3303 # Log the move
3304 $log = new LogPage( 'move' );
3305 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3306 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3307
3308 # Purge caches for old and new titles
3309 if ( $moveOverRedirect ) {
3310 # A simple purge is enough when moving over a redirect
3311 $nt->purgeSquid();
3312 } else {
3313 # Purge caches as per article creation, including any pages that link to this title
3314 Article::onArticleCreate( $nt );
3315 }
3316 $this->purgeSquid();
3317 }
3318
3319 /**
3320 * Move this page's subpages to be subpages of $nt
3321 *
3322 * @param $nt Title Move target
3323 * @param $auth bool Whether $wgUser's permissions should be checked
3324 * @param $reason string The reason for the move
3325 * @param $createRedirect bool Whether to create redirects from the old subpages to
3326 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3327 * @return mixed array with old page titles as keys, and strings (new page titles) or
3328 * arrays (errors) as values, or an error array with numeric indices if no pages
3329 * were moved
3330 */
3331 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3332 global $wgMaximumMovedPages;
3333 // Check permissions
3334 if ( !$this->userCan( 'move-subpages' ) ) {
3335 return array( 'cant-move-subpages' );
3336 }
3337 // Do the source and target namespaces support subpages?
3338 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3339 return array( 'namespace-nosubpages',
3340 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3341 }
3342 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3343 return array( 'namespace-nosubpages',
3344 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3345 }
3346
3347 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3348 $retval = array();
3349 $count = 0;
3350 foreach ( $subpages as $oldSubpage ) {
3351 $count++;
3352 if ( $count > $wgMaximumMovedPages ) {
3353 $retval[$oldSubpage->getPrefixedTitle()] =
3354 array( 'movepage-max-pages',
3355 $wgMaximumMovedPages );
3356 break;
3357 }
3358
3359 // We don't know whether this function was called before
3360 // or after moving the root page, so check both
3361 // $this and $nt
3362 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3363 $oldSubpage->getArticleID() == $nt->getArticleId() )
3364 {
3365 // When moving a page to a subpage of itself,
3366 // don't move it twice
3367 continue;
3368 }
3369 $newPageName = preg_replace(
3370 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3371 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3372 $oldSubpage->getDBkey() );
3373 if ( $oldSubpage->isTalkPage() ) {
3374 $newNs = $nt->getTalkPage()->getNamespace();
3375 } else {
3376 $newNs = $nt->getSubjectPage()->getNamespace();
3377 }
3378 # Bug 14385: we need makeTitleSafe because the new page names may
3379 # be longer than 255 characters.
3380 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3381
3382 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3383 if ( $success === true ) {
3384 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3385 } else {
3386 $retval[$oldSubpage->getPrefixedText()] = $success;
3387 }
3388 }
3389 return $retval;
3390 }
3391
3392 /**
3393 * Checks if this page is just a one-rev redirect.
3394 * Adds lock, so don't use just for light purposes.
3395 *
3396 * @return Bool
3397 */
3398 public function isSingleRevRedirect() {
3399 $dbw = wfGetDB( DB_MASTER );
3400 # Is it a redirect?
3401 $row = $dbw->selectRow( 'page',
3402 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3403 $this->pageCond(),
3404 __METHOD__,
3405 array( 'FOR UPDATE' )
3406 );
3407 # Cache some fields we may want
3408 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3409 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3410 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3411 if ( !$this->mRedirect ) {
3412 return false;
3413 }
3414 # Does the article have a history?
3415 $row = $dbw->selectField( array( 'page', 'revision' ),
3416 'rev_id',
3417 array( 'page_namespace' => $this->getNamespace(),
3418 'page_title' => $this->getDBkey(),
3419 'page_id=rev_page',
3420 'page_latest != rev_id'
3421 ),
3422 __METHOD__,
3423 array( 'FOR UPDATE' )
3424 );
3425 # Return true if there was no history
3426 return ( $row === false );
3427 }
3428
3429 /**
3430 * Checks if $this can be moved to a given Title
3431 * - Selects for update, so don't call it unless you mean business
3432 *
3433 * @param $nt Title the new title to check
3434 * @return Bool
3435 */
3436 public function isValidMoveTarget( $nt ) {
3437 # Is it an existing file?
3438 if ( $nt->getNamespace() == NS_FILE ) {
3439 $file = wfLocalFile( $nt );
3440 if ( $file->exists() ) {
3441 wfDebug( __METHOD__ . ": file exists\n" );
3442 return false;
3443 }
3444 }
3445 # Is it a redirect with no history?
3446 if ( !$nt->isSingleRevRedirect() ) {
3447 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3448 return false;
3449 }
3450 # Get the article text
3451 $rev = Revision::newFromTitle( $nt );
3452 $text = $rev->getText();
3453 # Does the redirect point to the source?
3454 # Or is it a broken self-redirect, usually caused by namespace collisions?
3455 $m = array();
3456 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3457 $redirTitle = Title::newFromText( $m[1] );
3458 if ( !is_object( $redirTitle ) ||
3459 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3460 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3461 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3462 return false;
3463 }
3464 } else {
3465 # Fail safe
3466 wfDebug( __METHOD__ . ": failsafe\n" );
3467 return false;
3468 }
3469 return true;
3470 }
3471
3472 /**
3473 * Can this title be added to a user's watchlist?
3474 *
3475 * @return Bool TRUE or FALSE
3476 */
3477 public function isWatchable() {
3478 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3479 }
3480
3481 /**
3482 * Get categories to which this Title belongs and return an array of
3483 * categories' names.
3484 *
3485 * @return Array of parents in the form:
3486 * $parent => $currentarticle
3487 */
3488 public function getParentCategories() {
3489 global $wgContLang;
3490
3491 $data = array();
3492
3493 $titleKey = $this->getArticleId();
3494
3495 if ( $titleKey === 0 ) {
3496 return $data;
3497 }
3498
3499 $dbr = wfGetDB( DB_SLAVE );
3500
3501 $res = $dbr->select( 'categorylinks', '*',
3502 array(
3503 'cl_from' => $titleKey,
3504 ),
3505 __METHOD__,
3506 array()
3507 );
3508
3509 if ( $dbr->numRows( $res ) > 0 ) {
3510 foreach ( $res as $row ) {
3511 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3512 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3513 }
3514 }
3515 return $data;
3516 }
3517
3518 /**
3519 * Get a tree of parent categories
3520 *
3521 * @param $children Array with the children in the keys, to check for circular refs
3522 * @return Array Tree of parent categories
3523 */
3524 public function getParentCategoryTree( $children = array() ) {
3525 $stack = array();
3526 $parents = $this->getParentCategories();
3527
3528 if ( $parents ) {
3529 foreach ( $parents as $parent => $current ) {
3530 if ( array_key_exists( $parent, $children ) ) {
3531 # Circular reference
3532 $stack[$parent] = array();
3533 } else {
3534 $nt = Title::newFromText( $parent );
3535 if ( $nt ) {
3536 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3537 }
3538 }
3539 }
3540 }
3541
3542 return $stack;
3543 }
3544
3545 /**
3546 * Get an associative array for selecting this title from
3547 * the "page" table
3548 *
3549 * @return Array suitable for the $where parameter of DB::select()
3550 */
3551 public function pageCond() {
3552 if ( $this->mArticleID > 0 ) {
3553 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3554 return array( 'page_id' => $this->mArticleID );
3555 } else {
3556 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3557 }
3558 }
3559
3560 /**
3561 * Get the revision ID of the previous revision
3562 *
3563 * @param $revId Int Revision ID. Get the revision that was before this one.
3564 * @param $flags Int Title::GAID_FOR_UPDATE
3565 * @return Int|Bool Old revision ID, or FALSE if none exists
3566 */
3567 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3568 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3569 return $db->selectField( 'revision', 'rev_id',
3570 array(
3571 'rev_page' => $this->getArticleId( $flags ),
3572 'rev_id < ' . intval( $revId )
3573 ),
3574 __METHOD__,
3575 array( 'ORDER BY' => 'rev_id DESC' )
3576 );
3577 }
3578
3579 /**
3580 * Get the revision ID of the next revision
3581 *
3582 * @param $revId Int Revision ID. Get the revision that was after this one.
3583 * @param $flags Int Title::GAID_FOR_UPDATE
3584 * @return Int|Bool Next revision ID, or FALSE if none exists
3585 */
3586 public function getNextRevisionID( $revId, $flags = 0 ) {
3587 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3588 return $db->selectField( 'revision', 'rev_id',
3589 array(
3590 'rev_page' => $this->getArticleId( $flags ),
3591 'rev_id > ' . intval( $revId )
3592 ),
3593 __METHOD__,
3594 array( 'ORDER BY' => 'rev_id' )
3595 );
3596 }
3597
3598 /**
3599 * Get the first revision of the page
3600 *
3601 * @param $flags Int Title::GAID_FOR_UPDATE
3602 * @return Revision|Null if page doesn't exist
3603 */
3604 public function getFirstRevision( $flags = 0 ) {
3605 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3606 $pageId = $this->getArticleId( $flags );
3607 if ( !$pageId ) {
3608 return null;
3609 }
3610 $row = $db->selectRow( 'revision', '*',
3611 array( 'rev_page' => $pageId ),
3612 __METHOD__,
3613 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3614 );
3615 if ( !$row ) {
3616 return null;
3617 } else {
3618 return new Revision( $row );
3619 }
3620 }
3621
3622 /**
3623 * Check if this is a new page
3624 *
3625 * @return bool
3626 */
3627 public function isNewPage() {
3628 $dbr = wfGetDB( DB_SLAVE );
3629 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3630 }
3631
3632 /**
3633 * Get the oldest revision timestamp of this page
3634 *
3635 * @return String: MW timestamp
3636 */
3637 public function getEarliestRevTime() {
3638 $dbr = wfGetDB( DB_SLAVE );
3639 if ( $this->exists() ) {
3640 $min = $dbr->selectField( 'revision',
3641 'MIN(rev_timestamp)',
3642 array( 'rev_page' => $this->getArticleId() ),
3643 __METHOD__ );
3644 return wfTimestampOrNull( TS_MW, $min );
3645 }
3646 return null;
3647 }
3648
3649 /**
3650 * Get the number of revisions between the given revision IDs.
3651 * Used for diffs and other things that really need it.
3652 *
3653 * @param $old Int Revision ID.
3654 * @param $new Int Revision ID.
3655 * @return Int Number of revisions between these IDs.
3656 */
3657 public function countRevisionsBetween( $old, $new ) {
3658 $dbr = wfGetDB( DB_SLAVE );
3659 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3660 'rev_page' => intval( $this->getArticleId() ),
3661 'rev_id > ' . intval( $old ),
3662 'rev_id < ' . intval( $new )
3663 ), __METHOD__
3664 );
3665 }
3666
3667 /**
3668 * Get the number of authors between the given revision IDs.
3669 * Used for diffs and other things that really need it.
3670 *
3671 * @param $fromRevId Int Revision ID (first before range)
3672 * @param $toRevId Int Revision ID (first after range)
3673 * @param $limit Int Maximum number of authors
3674 * @param $flags Int Title::GAID_FOR_UPDATE
3675 * @return Int
3676 */
3677 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3678 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3679 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3680 array(
3681 'rev_page' => $this->getArticleID(),
3682 'rev_id > ' . (int)$fromRevId,
3683 'rev_id < ' . (int)$toRevId
3684 ), __METHOD__,
3685 array( 'LIMIT' => $limit )
3686 );
3687 return (int)$db->numRows( $res );
3688 }
3689
3690 /**
3691 * Compare with another title.
3692 *
3693 * @param $title Title
3694 * @return Bool
3695 */
3696 public function equals( Title $title ) {
3697 // Note: === is necessary for proper matching of number-like titles.
3698 return $this->getInterwiki() === $title->getInterwiki()
3699 && $this->getNamespace() == $title->getNamespace()
3700 && $this->getDBkey() === $title->getDBkey();
3701 }
3702
3703 /**
3704 * Callback for usort() to do title sorts by (namespace, title)
3705 *
3706 * @return Integer: result of string comparison, or namespace comparison
3707 */
3708 public static function compare( $a, $b ) {
3709 if ( $a->getNamespace() == $b->getNamespace() ) {
3710 return strcmp( $a->getText(), $b->getText() );
3711 } else {
3712 return $a->getNamespace() - $b->getNamespace();
3713 }
3714 }
3715
3716 /**
3717 * Return a string representation of this title
3718 *
3719 * @return String representation of this title
3720 */
3721 public function __toString() {
3722 return $this->getPrefixedText();
3723 }
3724
3725 /**
3726 * Check if page exists. For historical reasons, this function simply
3727 * checks for the existence of the title in the page table, and will
3728 * thus return false for interwiki links, special pages and the like.
3729 * If you want to know if a title can be meaningfully viewed, you should
3730 * probably call the isKnown() method instead.
3731 *
3732 * @return Bool
3733 */
3734 public function exists() {
3735 return $this->getArticleId() != 0;
3736 }
3737
3738 /**
3739 * Should links to this title be shown as potentially viewable (i.e. as
3740 * "bluelinks"), even if there's no record by this title in the page
3741 * table?
3742 *
3743 * This function is semi-deprecated for public use, as well as somewhat
3744 * misleadingly named. You probably just want to call isKnown(), which
3745 * calls this function internally.
3746 *
3747 * (ISSUE: Most of these checks are cheap, but the file existence check
3748 * can potentially be quite expensive. Including it here fixes a lot of
3749 * existing code, but we might want to add an optional parameter to skip
3750 * it and any other expensive checks.)
3751 *
3752 * @return Bool
3753 */
3754 public function isAlwaysKnown() {
3755 if ( $this->mInterwiki != '' ) {
3756 return true; // any interwiki link might be viewable, for all we know
3757 }
3758 switch( $this->mNamespace ) {
3759 case NS_MEDIA:
3760 case NS_FILE:
3761 // file exists, possibly in a foreign repo
3762 return (bool)wfFindFile( $this );
3763 case NS_SPECIAL:
3764 // valid special page
3765 return SpecialPage::exists( $this->getDBkey() );
3766 case NS_MAIN:
3767 // selflink, possibly with fragment
3768 return $this->mDbkeyform == '';
3769 case NS_MEDIAWIKI:
3770 // known system message
3771 return $this->getDefaultMessageText() !== false;
3772 default:
3773 return false;
3774 }
3775 }
3776
3777 /**
3778 * Does this title refer to a page that can (or might) be meaningfully
3779 * viewed? In particular, this function may be used to determine if
3780 * links to the title should be rendered as "bluelinks" (as opposed to
3781 * "redlinks" to non-existent pages).
3782 *
3783 * @return Bool
3784 */
3785 public function isKnown() {
3786 return $this->isAlwaysKnown() || $this->exists();
3787 }
3788
3789 /**
3790 * Does this page have source text?
3791 *
3792 * @return Boolean
3793 */
3794 public function hasSourceText() {
3795 if ( $this->exists() ) {
3796 return true;
3797 }
3798
3799 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3800 // If the page doesn't exist but is a known system message, default
3801 // message content will be displayed, same for language subpages
3802 return $this->getDefaultMessageText() !== false;
3803 }
3804
3805 return false;
3806 }
3807
3808 /**
3809 * Get the default message text or false if the message doesn't exist
3810 *
3811 * @return String or false
3812 */
3813 public function getDefaultMessageText() {
3814 global $wgContLang;
3815
3816 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3817 return false;
3818 }
3819
3820 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3821 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3822
3823 if ( $message->exists() ) {
3824 return $message->plain();
3825 } else {
3826 return false;
3827 }
3828 }
3829
3830 /**
3831 * Is this in a namespace that allows actual pages?
3832 *
3833 * @return Bool
3834 * @internal note -- uses hardcoded namespace index instead of constants
3835 */
3836 public function canExist() {
3837 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3838 }
3839
3840 /**
3841 * Update page_touched timestamps and send squid purge messages for
3842 * pages linking to this title. May be sent to the job queue depending
3843 * on the number of links. Typically called on create and delete.
3844 */
3845 public function touchLinks() {
3846 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3847 $u->doUpdate();
3848
3849 if ( $this->getNamespace() == NS_CATEGORY ) {
3850 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3851 $u->doUpdate();
3852 }
3853 }
3854
3855 /**
3856 * Get the last touched timestamp
3857 *
3858 * @param $db DatabaseBase: optional db
3859 * @return String last-touched timestamp
3860 */
3861 public function getTouched( $db = null ) {
3862 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3863 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3864 return $touched;
3865 }
3866
3867 /**
3868 * Get the timestamp when this page was updated since the user last saw it.
3869 *
3870 * @param $user User
3871 * @return String|Null
3872 */
3873 public function getNotificationTimestamp( $user = null ) {
3874 global $wgUser, $wgShowUpdatedMarker;
3875 // Assume current user if none given
3876 if ( !$user ) {
3877 $user = $wgUser;
3878 }
3879 // Check cache first
3880 $uid = $user->getId();
3881 // avoid isset here, as it'll return false for null entries
3882 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3883 return $this->mNotificationTimestamp[$uid];
3884 }
3885 if ( !$uid || !$wgShowUpdatedMarker ) {
3886 return $this->mNotificationTimestamp[$uid] = false;
3887 }
3888 // Don't cache too much!
3889 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3890 $this->mNotificationTimestamp = array();
3891 }
3892 $dbr = wfGetDB( DB_SLAVE );
3893 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3894 'wl_notificationtimestamp',
3895 array( 'wl_namespace' => $this->getNamespace(),
3896 'wl_title' => $this->getDBkey(),
3897 'wl_user' => $user->getId()
3898 ),
3899 __METHOD__
3900 );
3901 return $this->mNotificationTimestamp[$uid];
3902 }
3903
3904 /**
3905 * Get the trackback URL for this page
3906 *
3907 * @return String Trackback URL
3908 */
3909 public function trackbackURL() {
3910 global $wgScriptPath, $wgServer, $wgScriptExtension;
3911
3912 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3913 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3914 }
3915
3916 /**
3917 * Get the trackback RDF for this page
3918 *
3919 * @return String Trackback RDF
3920 */
3921 public function trackbackRDF() {
3922 $url = htmlspecialchars( $this->getFullURL() );
3923 $title = htmlspecialchars( $this->getText() );
3924 $tburl = $this->trackbackURL();
3925
3926 // Autodiscovery RDF is placed in comments so HTML validator
3927 // won't barf. This is a rather icky workaround, but seems
3928 // frequently used by this kind of RDF thingy.
3929 //
3930 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3931 return "<!--
3932 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3933 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3934 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3935 <rdf:Description
3936 rdf:about=\"$url\"
3937 dc:identifier=\"$url\"
3938 dc:title=\"$title\"
3939 trackback:ping=\"$tburl\" />
3940 </rdf:RDF>
3941 -->";
3942 }
3943
3944 /**
3945 * Generate strings used for xml 'id' names in monobook tabs
3946 *
3947 * @param $prepend string defaults to 'nstab-'
3948 * @return String XML 'id' name
3949 */
3950 public function getNamespaceKey( $prepend = 'nstab-' ) {
3951 global $wgContLang;
3952 // Gets the subject namespace if this title
3953 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3954 // Checks if cononical namespace name exists for namespace
3955 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3956 // Uses canonical namespace name
3957 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3958 } else {
3959 // Uses text of namespace
3960 $namespaceKey = $this->getSubjectNsText();
3961 }
3962 // Makes namespace key lowercase
3963 $namespaceKey = $wgContLang->lc( $namespaceKey );
3964 // Uses main
3965 if ( $namespaceKey == '' ) {
3966 $namespaceKey = 'main';
3967 }
3968 // Changes file to image for backwards compatibility
3969 if ( $namespaceKey == 'file' ) {
3970 $namespaceKey = 'image';
3971 }
3972 return $prepend . $namespaceKey;
3973 }
3974
3975 /**
3976 * Returns true if this is a special page.
3977 *
3978 * @return boolean
3979 */
3980 public function isSpecialPage() {
3981 return $this->getNamespace() == NS_SPECIAL;
3982 }
3983
3984 /**
3985 * Returns true if this title resolves to the named special page
3986 *
3987 * @param $name String The special page name
3988 * @return boolean
3989 */
3990 public function isSpecial( $name ) {
3991 if ( $this->getNamespace() == NS_SPECIAL ) {
3992 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3993 if ( $name == $thisName ) {
3994 return true;
3995 }
3996 }
3997 return false;
3998 }
3999
4000 /**
4001 * If the Title refers to a special page alias which is not the local default, resolve
4002 * the alias, and localise the name as necessary. Otherwise, return $this
4003 *
4004 * @return Title
4005 */
4006 public function fixSpecialName() {
4007 if ( $this->getNamespace() == NS_SPECIAL ) {
4008 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4009 if ( $canonicalName ) {
4010 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4011 if ( $localName != $this->mDbkeyform ) {
4012 return Title::makeTitle( NS_SPECIAL, $localName );
4013 }
4014 }
4015 }
4016 return $this;
4017 }
4018
4019 /**
4020 * Is this Title in a namespace which contains content?
4021 * In other words, is this a content page, for the purposes of calculating
4022 * statistics, etc?
4023 *
4024 * @return Boolean
4025 */
4026 public function isContentPage() {
4027 return MWNamespace::isContent( $this->getNamespace() );
4028 }
4029
4030 /**
4031 * Get all extant redirects to this Title
4032 *
4033 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4034 * @return Array of Title redirects to this title
4035 */
4036 public function getRedirectsHere( $ns = null ) {
4037 $redirs = array();
4038
4039 $dbr = wfGetDB( DB_SLAVE );
4040 $where = array(
4041 'rd_namespace' => $this->getNamespace(),
4042 'rd_title' => $this->getDBkey(),
4043 'rd_from = page_id'
4044 );
4045 if ( !is_null( $ns ) ) {
4046 $where['page_namespace'] = $ns;
4047 }
4048
4049 $res = $dbr->select(
4050 array( 'redirect', 'page' ),
4051 array( 'page_namespace', 'page_title' ),
4052 $where,
4053 __METHOD__
4054 );
4055
4056 foreach ( $res as $row ) {
4057 $redirs[] = self::newFromRow( $row );
4058 }
4059 return $redirs;
4060 }
4061
4062 /**
4063 * Check if this Title is a valid redirect target
4064 *
4065 * @return Bool
4066 */
4067 public function isValidRedirectTarget() {
4068 global $wgInvalidRedirectTargets;
4069
4070 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4071 if ( $this->isSpecial( 'Userlogout' ) ) {
4072 return false;
4073 }
4074
4075 foreach ( $wgInvalidRedirectTargets as $target ) {
4076 if ( $this->isSpecial( $target ) ) {
4077 return false;
4078 }
4079 }
4080
4081 return true;
4082 }
4083
4084 /**
4085 * Get a backlink cache object
4086 *
4087 * @return object BacklinkCache
4088 */
4089 function getBacklinkCache() {
4090 if ( is_null( $this->mBacklinkCache ) ) {
4091 $this->mBacklinkCache = new BacklinkCache( $this );
4092 }
4093 return $this->mBacklinkCache;
4094 }
4095
4096 /**
4097 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4098 *
4099 * @return Boolean
4100 */
4101 public function canUseNoindex() {
4102 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4103
4104 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4105 ? $wgContentNamespaces
4106 : $wgExemptFromUserRobotsControl;
4107
4108 return !in_array( $this->mNamespace, $bannedNamespaces );
4109
4110 }
4111
4112 /**
4113 * Returns restriction types for the current Title
4114 *
4115 * @return array applicable restriction types
4116 */
4117 public function getRestrictionTypes() {
4118 global $wgRestrictionTypes;
4119
4120 $types = $this->exists() ? $wgRestrictionTypes : array( 'create' );
4121
4122 if ( $this->getNamespace() != NS_FILE ) {
4123 $types = array_diff( $types, array( 'upload' ) );
4124 }
4125
4126 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4127
4128 return $types;
4129 }
4130
4131 /**
4132 * Returns the raw sort key to be used for categories, with the specified
4133 * prefix. This will be fed to Collation::getSortKey() to get a
4134 * binary sortkey that can be used for actual sorting.
4135 *
4136 * @param $prefix string The prefix to be used, specified using
4137 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4138 * prefix.
4139 * @return string
4140 */
4141 public function getCategorySortkey( $prefix = '' ) {
4142 $unprefixed = $this->getText();
4143 if ( $prefix !== '' ) {
4144 # Separate with a line feed, so the unprefixed part is only used as
4145 # a tiebreaker when two pages have the exact same prefix.
4146 # In UCA, tab is the only character that can sort above LF
4147 # so we strip both of them from the original prefix.
4148 $prefix = strtr( $prefix, "\n\t", ' ' );
4149 return "$prefix\n$unprefixed";
4150 }
4151 return $unprefixed;
4152 }
4153 }