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