w/s fixups
[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
2507 if ( 0 != $this->mNamespace ) {
2508 $p .= $this->getNsText() . ':';
2509 }
2510 return $p . $name;
2511 }
2512
2513 /**
2514 * Returns a simple regex that will match on characters and sequences invalid in titles.
2515 * Note that this doesn't pick up many things that could be wrong with titles, but that
2516 * replacing this regex with something valid will make many titles valid.
2517 *
2518 * @return String regex string
2519 */
2520 static function getTitleInvalidRegex() {
2521 static $rxTc = false;
2522 if ( !$rxTc ) {
2523 # Matching titles will be held as illegal.
2524 $rxTc = '/' .
2525 # Any character not allowed is forbidden...
2526 '[^' . Title::legalChars() . ']' .
2527 # URL percent encoding sequences interfere with the ability
2528 # to round-trip titles -- you can't link to them consistently.
2529 '|%[0-9A-Fa-f]{2}' .
2530 # XML/HTML character references produce similar issues.
2531 '|&[A-Za-z0-9\x80-\xff]+;' .
2532 '|&#[0-9]+;' .
2533 '|&#x[0-9A-Fa-f]+;' .
2534 '/S';
2535 }
2536
2537 return $rxTc;
2538 }
2539
2540 /**
2541 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2542 *
2543 * @param $text String containing title to capitalize
2544 * @param $ns int namespace index, defaults to NS_MAIN
2545 * @return String containing capitalized title
2546 */
2547 public static function capitalize( $text, $ns = NS_MAIN ) {
2548 global $wgContLang;
2549
2550 if ( MWNamespace::isCapitalized( $ns ) ) {
2551 return $wgContLang->ucfirst( $text );
2552 } else {
2553 return $text;
2554 }
2555 }
2556
2557 /**
2558 * Secure and split - main initialisation function for this object
2559 *
2560 * Assumes that mDbkeyform has been set, and is urldecoded
2561 * and uses underscores, but not otherwise munged. This function
2562 * removes illegal characters, splits off the interwiki and
2563 * namespace prefixes, sets the other forms, and canonicalizes
2564 * everything.
2565 *
2566 * @return Bool true on success
2567 */
2568 private function secureAndSplit() {
2569 global $wgContLang, $wgLocalInterwiki;
2570
2571 # Initialisation
2572 $rxTc = self::getTitleInvalidRegex();
2573
2574 $this->mInterwiki = $this->mFragment = '';
2575 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2576
2577 $dbkey = $this->mDbkeyform;
2578
2579 # Strip Unicode bidi override characters.
2580 # Sometimes they slip into cut-n-pasted page titles, where the
2581 # override chars get included in list displays.
2582 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2583
2584 # Clean up whitespace
2585 # Note: use of the /u option on preg_replace here will cause
2586 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2587 # conveniently disabling them.
2588 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2589 $dbkey = trim( $dbkey, '_' );
2590
2591 if ( $dbkey == '' ) {
2592 return false;
2593 }
2594
2595 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2596 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2597 return false;
2598 }
2599
2600 $this->mDbkeyform = $dbkey;
2601
2602 # Initial colon indicates main namespace rather than specified default
2603 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2604 if ( ':' == $dbkey { 0 } ) {
2605 $this->mNamespace = NS_MAIN;
2606 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2607 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2608 }
2609
2610 # Namespace or interwiki prefix
2611 $firstPass = true;
2612 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2613 do {
2614 $m = array();
2615 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2616 $p = $m[1];
2617 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2618 # Ordinary namespace
2619 $dbkey = $m[2];
2620 $this->mNamespace = $ns;
2621 # For Talk:X pages, check if X has a "namespace" prefix
2622 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2623 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2624 # Disallow Talk:File:x type titles...
2625 return false;
2626 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2627 # Disallow Talk:Interwiki:x type titles...
2628 return false;
2629 }
2630 }
2631 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2632 if ( !$firstPass ) {
2633 # Can't make a local interwiki link to an interwiki link.
2634 # That's just crazy!
2635 return false;
2636 }
2637
2638 # Interwiki link
2639 $dbkey = $m[2];
2640 $this->mInterwiki = $wgContLang->lc( $p );
2641
2642 # Redundant interwiki prefix to the local wiki
2643 if ( $wgLocalInterwiki !== false
2644 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2645 {
2646 if ( $dbkey == '' ) {
2647 # Can't have an empty self-link
2648 return false;
2649 }
2650 $this->mInterwiki = '';
2651 $firstPass = false;
2652 # Do another namespace split...
2653 continue;
2654 }
2655
2656 # If there's an initial colon after the interwiki, that also
2657 # resets the default namespace
2658 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2659 $this->mNamespace = NS_MAIN;
2660 $dbkey = substr( $dbkey, 1 );
2661 }
2662 }
2663 # If there's no recognized interwiki or namespace,
2664 # then let the colon expression be part of the title.
2665 }
2666 break;
2667 } while ( true );
2668
2669 # We already know that some pages won't be in the database!
2670 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2671 $this->mArticleID = 0;
2672 }
2673 $fragment = strstr( $dbkey, '#' );
2674 if ( false !== $fragment ) {
2675 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2676 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2677 # remove whitespace again: prevents "Foo_bar_#"
2678 # becoming "Foo_bar_"
2679 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2680 }
2681
2682 # Reject illegal characters.
2683 if ( preg_match( $rxTc, $dbkey ) ) {
2684 return false;
2685 }
2686
2687 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2688 # reachable due to the way web browsers deal with 'relative' URLs.
2689 # Also, they conflict with subpage syntax. Forbid them explicitly.
2690 if ( strpos( $dbkey, '.' ) !== false &&
2691 ( $dbkey === '.' || $dbkey === '..' ||
2692 strpos( $dbkey, './' ) === 0 ||
2693 strpos( $dbkey, '../' ) === 0 ||
2694 strpos( $dbkey, '/./' ) !== false ||
2695 strpos( $dbkey, '/../' ) !== false ||
2696 substr( $dbkey, -2 ) == '/.' ||
2697 substr( $dbkey, -3 ) == '/..' ) )
2698 {
2699 return false;
2700 }
2701
2702 # Magic tilde sequences? Nu-uh!
2703 if ( strpos( $dbkey, '~~~' ) !== false ) {
2704 return false;
2705 }
2706
2707 # Limit the size of titles to 255 bytes. This is typically the size of the
2708 # underlying database field. We make an exception for special pages, which
2709 # don't need to be stored in the database, and may edge over 255 bytes due
2710 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2711 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2712 strlen( $dbkey ) > 512 )
2713 {
2714 return false;
2715 }
2716
2717 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2718 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2719 # other site might be case-sensitive.
2720 $this->mUserCaseDBKey = $dbkey;
2721 if ( $this->mInterwiki == '' ) {
2722 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2723 }
2724
2725 # Can't make a link to a namespace alone... "empty" local links can only be
2726 # self-links with a fragment identifier.
2727 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2728 return false;
2729 }
2730
2731 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2732 // IP names are not allowed for accounts, and can only be referring to
2733 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2734 // there are numerous ways to present the same IP. Having sp:contribs scan
2735 // them all is silly and having some show the edits and others not is
2736 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2737 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2738 ? IP::sanitizeIP( $dbkey )
2739 : $dbkey;
2740
2741 // Any remaining initial :s are illegal.
2742 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2743 return false;
2744 }
2745
2746 # Fill fields
2747 $this->mDbkeyform = $dbkey;
2748 $this->mUrlform = wfUrlencode( $dbkey );
2749
2750 $this->mTextform = str_replace( '_', ' ', $dbkey );
2751
2752 return true;
2753 }
2754
2755 /**
2756 * Set the fragment for this title. Removes the first character from the
2757 * specified fragment before setting, so it assumes you're passing it with
2758 * an initial "#".
2759 *
2760 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2761 * Still in active use privately.
2762 *
2763 * @param $fragment String text
2764 */
2765 public function setFragment( $fragment ) {
2766 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2767 }
2768
2769 /**
2770 * Get a Title object associated with the talk page of this article
2771 *
2772 * @return Title the object for the talk page
2773 */
2774 public function getTalkPage() {
2775 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2776 }
2777
2778 /**
2779 * Get a title object associated with the subject page of this
2780 * talk page
2781 *
2782 * @return Title the object for the subject page
2783 */
2784 public function getSubjectPage() {
2785 // Is this the same title?
2786 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2787 if ( $this->getNamespace() == $subjectNS ) {
2788 return $this;
2789 }
2790 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2791 }
2792
2793 /**
2794 * Get an array of Title objects linking to this Title
2795 * Also stores the IDs in the link cache.
2796 *
2797 * WARNING: do not use this function on arbitrary user-supplied titles!
2798 * On heavily-used templates it will max out the memory.
2799 *
2800 * @param $options Array: may be FOR UPDATE
2801 * @param $table String: table name
2802 * @param $prefix String: fields prefix
2803 * @return Array of Title objects linking here
2804 */
2805 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2806 $linkCache = LinkCache::singleton();
2807
2808 if ( count( $options ) > 0 ) {
2809 $db = wfGetDB( DB_MASTER );
2810 } else {
2811 $db = wfGetDB( DB_SLAVE );
2812 }
2813
2814 $res = $db->select(
2815 array( 'page', $table ),
2816 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2817 array(
2818 "{$prefix}_from=page_id",
2819 "{$prefix}_namespace" => $this->getNamespace(),
2820 "{$prefix}_title" => $this->getDBkey() ),
2821 __METHOD__,
2822 $options
2823 );
2824
2825 $retVal = array();
2826 if ( $db->numRows( $res ) ) {
2827 foreach ( $res as $row ) {
2828 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2829 if ( $titleObj ) {
2830 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2831 $retVal[] = $titleObj;
2832 }
2833 }
2834 }
2835 return $retVal;
2836 }
2837
2838 /**
2839 * Get an array of Title objects using this Title as a template
2840 * Also stores the IDs in the link cache.
2841 *
2842 * WARNING: do not use this function on arbitrary user-supplied titles!
2843 * On heavily-used templates it will max out the memory.
2844 *
2845 * @param $options Array: may be FOR UPDATE
2846 * @return Array of Title the Title objects linking here
2847 */
2848 public function getTemplateLinksTo( $options = array() ) {
2849 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2850 }
2851
2852 /**
2853 * Get an array of Title objects referring to non-existent articles linked from this page
2854 *
2855 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2856 * @return Array of Title the Title objects
2857 */
2858 public function getBrokenLinksFrom() {
2859 if ( $this->getArticleId() == 0 ) {
2860 # All links from article ID 0 are false positives
2861 return array();
2862 }
2863
2864 $dbr = wfGetDB( DB_SLAVE );
2865 $res = $dbr->select(
2866 array( 'page', 'pagelinks' ),
2867 array( 'pl_namespace', 'pl_title' ),
2868 array(
2869 'pl_from' => $this->getArticleId(),
2870 'page_namespace IS NULL'
2871 ),
2872 __METHOD__, array(),
2873 array(
2874 'page' => array(
2875 'LEFT JOIN',
2876 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2877 )
2878 )
2879 );
2880
2881 $retVal = array();
2882 foreach ( $res as $row ) {
2883 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2884 }
2885 return $retVal;
2886 }
2887
2888
2889 /**
2890 * Get a list of URLs to purge from the Squid cache when this
2891 * page changes
2892 *
2893 * @return Array of String the URLs
2894 */
2895 public function getSquidURLs() {
2896 global $wgContLang;
2897
2898 $urls = array(
2899 $this->getInternalURL(),
2900 $this->getInternalURL( 'action=history' )
2901 );
2902
2903 // purge variant urls as well
2904 if ( $wgContLang->hasVariants() ) {
2905 $variants = $wgContLang->getVariants();
2906 foreach ( $variants as $vCode ) {
2907 $urls[] = $this->getInternalURL( '', $vCode );
2908 }
2909 }
2910
2911 return $urls;
2912 }
2913
2914 /**
2915 * Purge all applicable Squid URLs
2916 */
2917 public function purgeSquid() {
2918 global $wgUseSquid;
2919 if ( $wgUseSquid ) {
2920 $urls = $this->getSquidURLs();
2921 $u = new SquidUpdate( $urls );
2922 $u->doUpdate();
2923 }
2924 }
2925
2926 /**
2927 * Move this page without authentication
2928 *
2929 * @param $nt Title the new page Title
2930 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2931 */
2932 public function moveNoAuth( &$nt ) {
2933 return $this->moveTo( $nt, false );
2934 }
2935
2936 /**
2937 * Check whether a given move operation would be valid.
2938 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2939 *
2940 * @param $nt Title the new title
2941 * @param $auth Bool indicates whether $wgUser's permissions
2942 * should be checked
2943 * @param $reason String is the log summary of the move, used for spam checking
2944 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2945 */
2946 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2947 global $wgUser;
2948
2949 $errors = array();
2950 if ( !$nt ) {
2951 // Normally we'd add this to $errors, but we'll get
2952 // lots of syntax errors if $nt is not an object
2953 return array( array( 'badtitletext' ) );
2954 }
2955 if ( $this->equals( $nt ) ) {
2956 $errors[] = array( 'selfmove' );
2957 }
2958 if ( !$this->isMovable() ) {
2959 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2960 }
2961 if ( $nt->getInterwiki() != '' ) {
2962 $errors[] = array( 'immobile-target-namespace-iw' );
2963 }
2964 if ( !$nt->isMovable() ) {
2965 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2966 }
2967
2968 $oldid = $this->getArticleID();
2969 $newid = $nt->getArticleID();
2970
2971 if ( strlen( $nt->getDBkey() ) < 1 ) {
2972 $errors[] = array( 'articleexists' );
2973 }
2974 if ( ( $this->getDBkey() == '' ) ||
2975 ( !$oldid ) ||
2976 ( $nt->getDBkey() == '' ) ) {
2977 $errors[] = array( 'badarticleerror' );
2978 }
2979
2980 // Image-specific checks
2981 if ( $this->getNamespace() == NS_FILE ) {
2982 if ( $nt->getNamespace() != NS_FILE ) {
2983 $errors[] = array( 'imagenocrossnamespace' );
2984 }
2985 $file = wfLocalFile( $this );
2986 if ( $file->exists() ) {
2987 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2988 $errors[] = array( 'imageinvalidfilename' );
2989 }
2990 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2991 $errors[] = array( 'imagetypemismatch' );
2992 }
2993 }
2994 $destfile = wfLocalFile( $nt );
2995 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2996 $errors[] = array( 'file-exists-sharedrepo' );
2997 }
2998 }
2999
3000 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3001 $errors[] = array( 'nonfile-cannot-move-to-file' );
3002 }
3003
3004 if ( $auth ) {
3005 $errors = wfMergeErrorArrays( $errors,
3006 $this->getUserPermissionsErrors( 'move', $wgUser ),
3007 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3008 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3009 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3010 }
3011
3012 $match = EditPage::matchSummarySpamRegex( $reason );
3013 if ( $match !== false ) {
3014 // This is kind of lame, won't display nice
3015 $errors[] = array( 'spamprotectiontext' );
3016 }
3017
3018 $err = null;
3019 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3020 $errors[] = array( 'hookaborted', $err );
3021 }
3022
3023 # The move is allowed only if (1) the target doesn't exist, or
3024 # (2) the target is a redirect to the source, and has no history
3025 # (so we can undo bad moves right after they're done).
3026
3027 if ( 0 != $newid ) { # Target exists; check for validity
3028 if ( !$this->isValidMoveTarget( $nt ) ) {
3029 $errors[] = array( 'articleexists' );
3030 }
3031 } else {
3032 $tp = $nt->getTitleProtection();
3033 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3034 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3035 $errors[] = array( 'cantmove-titleprotected' );
3036 }
3037 }
3038 if ( empty( $errors ) ) {
3039 return true;
3040 }
3041 return $errors;
3042 }
3043
3044 /**
3045 * Move a title to a new location
3046 *
3047 * @param $nt Title the new title
3048 * @param $auth Bool indicates whether $wgUser's permissions
3049 * should be checked
3050 * @param $reason String the reason for the move
3051 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3052 * Ignored if the user doesn't have the suppressredirect right.
3053 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3054 */
3055 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3056 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3057 if ( is_array( $err ) ) {
3058 return $err;
3059 }
3060
3061 // If it is a file, move it first. It is done before all other moving stuff is
3062 // done because it's hard to revert
3063 $dbw = wfGetDB( DB_MASTER );
3064 if ( $this->getNamespace() == NS_FILE ) {
3065 $file = wfLocalFile( $this );
3066 if ( $file->exists() ) {
3067 $status = $file->move( $nt );
3068 if ( !$status->isOk() ) {
3069 return $status->getErrorsArray();
3070 }
3071 }
3072 }
3073
3074 $pageid = $this->getArticleID();
3075 $protected = $this->isProtected();
3076 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3077
3078 // Do the actual move
3079 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3080 if ( is_array( $err ) ) {
3081 return $err;
3082 }
3083
3084 $redirid = $this->getArticleID();
3085
3086 // Refresh the sortkey for this row. Be careful to avoid resetting
3087 // cl_timestamp, which may disturb time-based lists on some sites.
3088 $prefix = $dbw->selectField(
3089 'categorylinks',
3090 'cl_sortkey_prefix',
3091 array( 'cl_from' => $pageid ),
3092 __METHOD__
3093 );
3094 $dbw->update( 'categorylinks',
3095 array(
3096 'cl_sortkey' => Collation::singleton()->getSortKey(
3097 $nt->getCategorySortkey( $prefix ) ),
3098 'cl_timestamp=cl_timestamp' ),
3099 array( 'cl_from' => $pageid ),
3100 __METHOD__ );
3101
3102 if ( $protected ) {
3103 # Protect the redirect title as the title used to be...
3104 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3105 array(
3106 'pr_page' => $redirid,
3107 'pr_type' => 'pr_type',
3108 'pr_level' => 'pr_level',
3109 'pr_cascade' => 'pr_cascade',
3110 'pr_user' => 'pr_user',
3111 'pr_expiry' => 'pr_expiry'
3112 ),
3113 array( 'pr_page' => $pageid ),
3114 __METHOD__,
3115 array( 'IGNORE' )
3116 );
3117 # Update the protection log
3118 $log = new LogPage( 'protect' );
3119 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3120 if ( $reason ) {
3121 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3122 }
3123 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3124 }
3125
3126 # Update watchlists
3127 $oldnamespace = $this->getNamespace() & ~1;
3128 $newnamespace = $nt->getNamespace() & ~1;
3129 $oldtitle = $this->getDBkey();
3130 $newtitle = $nt->getDBkey();
3131
3132 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3133 WatchedItem::duplicateEntries( $this, $nt );
3134 }
3135
3136 # Update search engine
3137 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3138 $u->doUpdate();
3139 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3140 $u->doUpdate();
3141
3142 # Update site_stats
3143 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3144 # No longer a content page
3145 # Not viewed, edited, removing
3146 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3147 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3148 # Now a content page
3149 # Not viewed, edited, adding
3150 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3151 } elseif ( $pageCountChange ) {
3152 # Redirect added
3153 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3154 } else {
3155 # Nothing special
3156 $u = false;
3157 }
3158 if ( $u ) {
3159 $u->doUpdate();
3160 }
3161 # Update message cache for interface messages
3162 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3163 # @bug 17860: old article can be deleted, if this the case,
3164 # delete it from message cache
3165 if ( $this->getArticleID() === 0 ) {
3166 MessageCache::singleton()->replace( $this->getDBkey(), false );
3167 } else {
3168 $oldarticle = new Article( $this );
3169 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3170 }
3171 }
3172 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3173 $newarticle = new Article( $nt );
3174 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3175 }
3176
3177 global $wgUser;
3178 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3179 return true;
3180 }
3181
3182 /**
3183 * Move page to a title which is either a redirect to the
3184 * source page or nonexistent
3185 *
3186 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3187 * @param $reason String The reason for the move
3188 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3189 * if the user doesn't have the suppressredirect right
3190 */
3191 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3192 global $wgUser, $wgContLang;
3193
3194 $moveOverRedirect = $nt->exists();
3195
3196 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3197 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3198
3199 if ( $reason ) {
3200 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3201 }
3202 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3203 $comment = $wgContLang->truncate( $comment, 250 );
3204
3205 $oldid = $this->getArticleID();
3206 $latest = $this->getLatestRevID();
3207
3208 $dbw = wfGetDB( DB_MASTER );
3209
3210 if ( $moveOverRedirect ) {
3211 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3212
3213 $newid = $nt->getArticleID();
3214 $newns = $nt->getNamespace();
3215 $newdbk = $nt->getDBkey();
3216
3217 # Delete the old redirect. We don't save it to history since
3218 # by definition if we've got here it's rather uninteresting.
3219 # We have to remove it so that the next step doesn't trigger
3220 # a conflict on the unique namespace+title index...
3221 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3222 if ( !$dbw->cascadingDeletes() ) {
3223 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3224 global $wgUseTrackbacks;
3225 if ( $wgUseTrackbacks ) {
3226 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3227 }
3228 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3229 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3230 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3231 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3232 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3233 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3234 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3235 }
3236 // If the target page was recently created, it may have an entry in recentchanges still
3237 $dbw->delete( 'recentchanges',
3238 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3239 __METHOD__
3240 );
3241 }
3242
3243 # Save a null revision in the page's history notifying of the move
3244 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3245 if ( !is_object( $nullRevision ) ) {
3246 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3247 }
3248 $nullRevId = $nullRevision->insertOn( $dbw );
3249
3250 $article = new Article( $this );
3251 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3252
3253 # Change the name of the target page:
3254 $dbw->update( 'page',
3255 /* SET */ array(
3256 'page_touched' => $dbw->timestamp(),
3257 'page_namespace' => $nt->getNamespace(),
3258 'page_title' => $nt->getDBkey(),
3259 'page_latest' => $nullRevId,
3260 ),
3261 /* WHERE */ array( 'page_id' => $oldid ),
3262 __METHOD__
3263 );
3264 $nt->resetArticleID( $oldid );
3265
3266 # Recreate the redirect, this time in the other direction.
3267 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3268 $mwRedir = MagicWord::get( 'redirect' );
3269 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3270 $redirectArticle = new Article( $this );
3271 $newid = $redirectArticle->insertOn( $dbw );
3272 $redirectRevision = new Revision( array(
3273 'page' => $newid,
3274 'comment' => $comment,
3275 'text' => $redirectText ) );
3276 $redirectRevision->insertOn( $dbw );
3277 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3278
3279 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3280
3281 # Now, we record the link from the redirect to the new title.
3282 # It should have no other outgoing links...
3283 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3284 $dbw->insert( 'pagelinks',
3285 array(
3286 'pl_from' => $newid,
3287 'pl_namespace' => $nt->getNamespace(),
3288 'pl_title' => $nt->getDBkey() ),
3289 __METHOD__ );
3290 $redirectSuppressed = false;
3291 } else {
3292 $this->resetArticleID( 0 );
3293 $redirectSuppressed = true;
3294 }
3295
3296 # Log the move
3297 $log = new LogPage( 'move' );
3298 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3299 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3300
3301 # Purge caches for old and new titles
3302 if ( $moveOverRedirect ) {
3303 # A simple purge is enough when moving over a redirect
3304 $nt->purgeSquid();
3305 } else {
3306 # Purge caches as per article creation, including any pages that link to this title
3307 Article::onArticleCreate( $nt );
3308 }
3309 $this->purgeSquid();
3310 }
3311
3312 /**
3313 * Move this page's subpages to be subpages of $nt
3314 *
3315 * @param $nt Title Move target
3316 * @param $auth bool Whether $wgUser's permissions should be checked
3317 * @param $reason string The reason for the move
3318 * @param $createRedirect bool Whether to create redirects from the old subpages to
3319 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3320 * @return mixed array with old page titles as keys, and strings (new page titles) or
3321 * arrays (errors) as values, or an error array with numeric indices if no pages
3322 * were moved
3323 */
3324 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3325 global $wgMaximumMovedPages;
3326 // Check permissions
3327 if ( !$this->userCan( 'move-subpages' ) ) {
3328 return array( 'cant-move-subpages' );
3329 }
3330 // Do the source and target namespaces support subpages?
3331 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3332 return array( 'namespace-nosubpages',
3333 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3334 }
3335 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3336 return array( 'namespace-nosubpages',
3337 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3338 }
3339
3340 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3341 $retval = array();
3342 $count = 0;
3343 foreach ( $subpages as $oldSubpage ) {
3344 $count++;
3345 if ( $count > $wgMaximumMovedPages ) {
3346 $retval[$oldSubpage->getPrefixedTitle()] =
3347 array( 'movepage-max-pages',
3348 $wgMaximumMovedPages );
3349 break;
3350 }
3351
3352 // We don't know whether this function was called before
3353 // or after moving the root page, so check both
3354 // $this and $nt
3355 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3356 $oldSubpage->getArticleID() == $nt->getArticleId() )
3357 {
3358 // When moving a page to a subpage of itself,
3359 // don't move it twice
3360 continue;
3361 }
3362 $newPageName = preg_replace(
3363 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3364 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3365 $oldSubpage->getDBkey() );
3366 if ( $oldSubpage->isTalkPage() ) {
3367 $newNs = $nt->getTalkPage()->getNamespace();
3368 } else {
3369 $newNs = $nt->getSubjectPage()->getNamespace();
3370 }
3371 # Bug 14385: we need makeTitleSafe because the new page names may
3372 # be longer than 255 characters.
3373 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3374
3375 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3376 if ( $success === true ) {
3377 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3378 } else {
3379 $retval[$oldSubpage->getPrefixedText()] = $success;
3380 }
3381 }
3382 return $retval;
3383 }
3384
3385 /**
3386 * Checks if this page is just a one-rev redirect.
3387 * Adds lock, so don't use just for light purposes.
3388 *
3389 * @return Bool
3390 */
3391 public function isSingleRevRedirect() {
3392 $dbw = wfGetDB( DB_MASTER );
3393 # Is it a redirect?
3394 $row = $dbw->selectRow( 'page',
3395 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3396 $this->pageCond(),
3397 __METHOD__,
3398 array( 'FOR UPDATE' )
3399 );
3400 # Cache some fields we may want
3401 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3402 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3403 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3404 if ( !$this->mRedirect ) {
3405 return false;
3406 }
3407 # Does the article have a history?
3408 $row = $dbw->selectField( array( 'page', 'revision' ),
3409 'rev_id',
3410 array( 'page_namespace' => $this->getNamespace(),
3411 'page_title' => $this->getDBkey(),
3412 'page_id=rev_page',
3413 'page_latest != rev_id'
3414 ),
3415 __METHOD__,
3416 array( 'FOR UPDATE' )
3417 );
3418 # Return true if there was no history
3419 return ( $row === false );
3420 }
3421
3422 /**
3423 * Checks if $this can be moved to a given Title
3424 * - Selects for update, so don't call it unless you mean business
3425 *
3426 * @param $nt Title the new title to check
3427 * @return Bool
3428 */
3429 public function isValidMoveTarget( $nt ) {
3430 # Is it an existing file?
3431 if ( $nt->getNamespace() == NS_FILE ) {
3432 $file = wfLocalFile( $nt );
3433 if ( $file->exists() ) {
3434 wfDebug( __METHOD__ . ": file exists\n" );
3435 return false;
3436 }
3437 }
3438 # Is it a redirect with no history?
3439 if ( !$nt->isSingleRevRedirect() ) {
3440 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3441 return false;
3442 }
3443 # Get the article text
3444 $rev = Revision::newFromTitle( $nt );
3445 $text = $rev->getText();
3446 # Does the redirect point to the source?
3447 # Or is it a broken self-redirect, usually caused by namespace collisions?
3448 $m = array();
3449 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3450 $redirTitle = Title::newFromText( $m[1] );
3451 if ( !is_object( $redirTitle ) ||
3452 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3453 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3454 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3455 return false;
3456 }
3457 } else {
3458 # Fail safe
3459 wfDebug( __METHOD__ . ": failsafe\n" );
3460 return false;
3461 }
3462 return true;
3463 }
3464
3465 /**
3466 * Can this title be added to a user's watchlist?
3467 *
3468 * @return Bool TRUE or FALSE
3469 */
3470 public function isWatchable() {
3471 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3472 }
3473
3474 /**
3475 * Get categories to which this Title belongs and return an array of
3476 * categories' names.
3477 *
3478 * @return Array of parents in the form:
3479 * $parent => $currentarticle
3480 */
3481 public function getParentCategories() {
3482 global $wgContLang;
3483
3484 $data = array();
3485
3486 $titleKey = $this->getArticleId();
3487
3488 if ( $titleKey === 0 ) {
3489 return $data;
3490 }
3491
3492 $dbr = wfGetDB( DB_SLAVE );
3493
3494 $res = $dbr->select( 'categorylinks', '*',
3495 array(
3496 'cl_from' => $titleKey,
3497 ),
3498 __METHOD__,
3499 array()
3500 );
3501
3502 if ( $dbr->numRows( $res ) > 0 ) {
3503 foreach ( $res as $row ) {
3504 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3505 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3506 }
3507 }
3508 return $data;
3509 }
3510
3511 /**
3512 * Get a tree of parent categories
3513 *
3514 * @param $children Array with the children in the keys, to check for circular refs
3515 * @return Array Tree of parent categories
3516 */
3517 public function getParentCategoryTree( $children = array() ) {
3518 $stack = array();
3519 $parents = $this->getParentCategories();
3520
3521 if ( $parents ) {
3522 foreach ( $parents as $parent => $current ) {
3523 if ( array_key_exists( $parent, $children ) ) {
3524 # Circular reference
3525 $stack[$parent] = array();
3526 } else {
3527 $nt = Title::newFromText( $parent );
3528 if ( $nt ) {
3529 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3530 }
3531 }
3532 }
3533 }
3534
3535 return $stack;
3536 }
3537
3538 /**
3539 * Get an associative array for selecting this title from
3540 * the "page" table
3541 *
3542 * @return Array suitable for the $where parameter of DB::select()
3543 */
3544 public function pageCond() {
3545 if ( $this->mArticleID > 0 ) {
3546 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3547 return array( 'page_id' => $this->mArticleID );
3548 } else {
3549 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3550 }
3551 }
3552
3553 /**
3554 * Get the revision ID of the previous revision
3555 *
3556 * @param $revId Int Revision ID. Get the revision that was before this one.
3557 * @param $flags Int Title::GAID_FOR_UPDATE
3558 * @return Int|Bool Old revision ID, or FALSE if none exists
3559 */
3560 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3561 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3562 return $db->selectField( 'revision', 'rev_id',
3563 array(
3564 'rev_page' => $this->getArticleId( $flags ),
3565 'rev_id < ' . intval( $revId )
3566 ),
3567 __METHOD__,
3568 array( 'ORDER BY' => 'rev_id DESC' )
3569 );
3570 }
3571
3572 /**
3573 * Get the revision ID of the next revision
3574 *
3575 * @param $revId Int Revision ID. Get the revision that was after this one.
3576 * @param $flags Int Title::GAID_FOR_UPDATE
3577 * @return Int|Bool Next revision ID, or FALSE if none exists
3578 */
3579 public function getNextRevisionID( $revId, $flags = 0 ) {
3580 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3581 return $db->selectField( 'revision', 'rev_id',
3582 array(
3583 'rev_page' => $this->getArticleId( $flags ),
3584 'rev_id > ' . intval( $revId )
3585 ),
3586 __METHOD__,
3587 array( 'ORDER BY' => 'rev_id' )
3588 );
3589 }
3590
3591 /**
3592 * Get the first revision of the page
3593 *
3594 * @param $flags Int Title::GAID_FOR_UPDATE
3595 * @return Revision|Null if page doesn't exist
3596 */
3597 public function getFirstRevision( $flags = 0 ) {
3598 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3599 $pageId = $this->getArticleId( $flags );
3600 if ( !$pageId ) {
3601 return null;
3602 }
3603 $row = $db->selectRow( 'revision', '*',
3604 array( 'rev_page' => $pageId ),
3605 __METHOD__,
3606 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3607 );
3608 if ( !$row ) {
3609 return null;
3610 } else {
3611 return new Revision( $row );
3612 }
3613 }
3614
3615 /**
3616 * Check if this is a new page
3617 *
3618 * @return bool
3619 */
3620 public function isNewPage() {
3621 $dbr = wfGetDB( DB_SLAVE );
3622 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3623 }
3624
3625 /**
3626 * Get the oldest revision timestamp of this page
3627 *
3628 * @return String: MW timestamp
3629 */
3630 public function getEarliestRevTime() {
3631 $dbr = wfGetDB( DB_SLAVE );
3632 if ( $this->exists() ) {
3633 $min = $dbr->selectField( 'revision',
3634 'MIN(rev_timestamp)',
3635 array( 'rev_page' => $this->getArticleId() ),
3636 __METHOD__ );
3637 return wfTimestampOrNull( TS_MW, $min );
3638 }
3639 return null;
3640 }
3641
3642 /**
3643 * Get the number of revisions between the given revision IDs.
3644 * Used for diffs and other things that really need it.
3645 *
3646 * @param $old Int Revision ID.
3647 * @param $new Int Revision ID.
3648 * @return Int Number of revisions between these IDs.
3649 */
3650 public function countRevisionsBetween( $old, $new ) {
3651 $dbr = wfGetDB( DB_SLAVE );
3652 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3653 'rev_page' => intval( $this->getArticleId() ),
3654 'rev_id > ' . intval( $old ),
3655 'rev_id < ' . intval( $new )
3656 ), __METHOD__
3657 );
3658 }
3659
3660 /**
3661 * Get the number of authors between the given revision IDs.
3662 * Used for diffs and other things that really need it.
3663 *
3664 * @param $fromRevId Int Revision ID (first before range)
3665 * @param $toRevId Int Revision ID (first after range)
3666 * @param $limit Int Maximum number of authors
3667 * @param $flags Int Title::GAID_FOR_UPDATE
3668 * @return Int
3669 */
3670 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3671 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3672 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3673 array(
3674 'rev_page' => $this->getArticleID(),
3675 'rev_id > ' . (int)$fromRevId,
3676 'rev_id < ' . (int)$toRevId
3677 ), __METHOD__,
3678 array( 'LIMIT' => $limit )
3679 );
3680 return (int)$db->numRows( $res );
3681 }
3682
3683 /**
3684 * Compare with another title.
3685 *
3686 * @param $title Title
3687 * @return Bool
3688 */
3689 public function equals( Title $title ) {
3690 // Note: === is necessary for proper matching of number-like titles.
3691 return $this->getInterwiki() === $title->getInterwiki()
3692 && $this->getNamespace() == $title->getNamespace()
3693 && $this->getDBkey() === $title->getDBkey();
3694 }
3695
3696 /**
3697 * Callback for usort() to do title sorts by (namespace, title)
3698 *
3699 * @return Integer: result of string comparison, or namespace comparison
3700 */
3701 public static function compare( $a, $b ) {
3702 if ( $a->getNamespace() == $b->getNamespace() ) {
3703 return strcmp( $a->getText(), $b->getText() );
3704 } else {
3705 return $a->getNamespace() - $b->getNamespace();
3706 }
3707 }
3708
3709 /**
3710 * Return a string representation of this title
3711 *
3712 * @return String representation of this title
3713 */
3714 public function __toString() {
3715 return $this->getPrefixedText();
3716 }
3717
3718 /**
3719 * Check if page exists. For historical reasons, this function simply
3720 * checks for the existence of the title in the page table, and will
3721 * thus return false for interwiki links, special pages and the like.
3722 * If you want to know if a title can be meaningfully viewed, you should
3723 * probably call the isKnown() method instead.
3724 *
3725 * @return Bool
3726 */
3727 public function exists() {
3728 return $this->getArticleId() != 0;
3729 }
3730
3731 /**
3732 * Should links to this title be shown as potentially viewable (i.e. as
3733 * "bluelinks"), even if there's no record by this title in the page
3734 * table?
3735 *
3736 * This function is semi-deprecated for public use, as well as somewhat
3737 * misleadingly named. You probably just want to call isKnown(), which
3738 * calls this function internally.
3739 *
3740 * (ISSUE: Most of these checks are cheap, but the file existence check
3741 * can potentially be quite expensive. Including it here fixes a lot of
3742 * existing code, but we might want to add an optional parameter to skip
3743 * it and any other expensive checks.)
3744 *
3745 * @return Bool
3746 */
3747 public function isAlwaysKnown() {
3748 if ( $this->mInterwiki != '' ) {
3749 return true; // any interwiki link might be viewable, for all we know
3750 }
3751 switch( $this->mNamespace ) {
3752 case NS_MEDIA:
3753 case NS_FILE:
3754 // file exists, possibly in a foreign repo
3755 return (bool)wfFindFile( $this );
3756 case NS_SPECIAL:
3757 // valid special page
3758 return SpecialPage::exists( $this->getDBkey() );
3759 case NS_MAIN:
3760 // selflink, possibly with fragment
3761 return $this->mDbkeyform == '';
3762 case NS_MEDIAWIKI:
3763 // known system message
3764 return $this->getDefaultMessageText() !== false;
3765 default:
3766 return false;
3767 }
3768 }
3769
3770 /**
3771 * Does this title refer to a page that can (or might) be meaningfully
3772 * viewed? In particular, this function may be used to determine if
3773 * links to the title should be rendered as "bluelinks" (as opposed to
3774 * "redlinks" to non-existent pages).
3775 *
3776 * @return Bool
3777 */
3778 public function isKnown() {
3779 return $this->isAlwaysKnown() || $this->exists();
3780 }
3781
3782 /**
3783 * Does this page have source text?
3784 *
3785 * @return Boolean
3786 */
3787 public function hasSourceText() {
3788 if ( $this->exists() ) {
3789 return true;
3790 }
3791
3792 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3793 // If the page doesn't exist but is a known system message, default
3794 // message content will be displayed, same for language subpages
3795 return $this->getDefaultMessageText() !== false;
3796 }
3797
3798 return false;
3799 }
3800
3801 /**
3802 * Get the default message text or false if the message doesn't exist
3803 *
3804 * @return String or false
3805 */
3806 public function getDefaultMessageText() {
3807 global $wgContLang;
3808
3809 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3810 return false;
3811 }
3812
3813 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3814 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3815
3816 if ( $message->exists() ) {
3817 return $message->plain();
3818 } else {
3819 return false;
3820 }
3821 }
3822
3823 /**
3824 * Is this in a namespace that allows actual pages?
3825 *
3826 * @return Bool
3827 * @internal note -- uses hardcoded namespace index instead of constants
3828 */
3829 public function canExist() {
3830 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3831 }
3832
3833 /**
3834 * Update page_touched timestamps and send squid purge messages for
3835 * pages linking to this title. May be sent to the job queue depending
3836 * on the number of links. Typically called on create and delete.
3837 */
3838 public function touchLinks() {
3839 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3840 $u->doUpdate();
3841
3842 if ( $this->getNamespace() == NS_CATEGORY ) {
3843 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3844 $u->doUpdate();
3845 }
3846 }
3847
3848 /**
3849 * Get the last touched timestamp
3850 *
3851 * @param $db DatabaseBase: optional db
3852 * @return String last-touched timestamp
3853 */
3854 public function getTouched( $db = null ) {
3855 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3856 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3857 return $touched;
3858 }
3859
3860 /**
3861 * Get the timestamp when this page was updated since the user last saw it.
3862 *
3863 * @param $user User
3864 * @return String|Null
3865 */
3866 public function getNotificationTimestamp( $user = null ) {
3867 global $wgUser, $wgShowUpdatedMarker;
3868 // Assume current user if none given
3869 if ( !$user ) {
3870 $user = $wgUser;
3871 }
3872 // Check cache first
3873 $uid = $user->getId();
3874 // avoid isset here, as it'll return false for null entries
3875 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3876 return $this->mNotificationTimestamp[$uid];
3877 }
3878 if ( !$uid || !$wgShowUpdatedMarker ) {
3879 return $this->mNotificationTimestamp[$uid] = false;
3880 }
3881 // Don't cache too much!
3882 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3883 $this->mNotificationTimestamp = array();
3884 }
3885 $dbr = wfGetDB( DB_SLAVE );
3886 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3887 'wl_notificationtimestamp',
3888 array( 'wl_namespace' => $this->getNamespace(),
3889 'wl_title' => $this->getDBkey(),
3890 'wl_user' => $user->getId()
3891 ),
3892 __METHOD__
3893 );
3894 return $this->mNotificationTimestamp[$uid];
3895 }
3896
3897 /**
3898 * Get the trackback URL for this page
3899 *
3900 * @return String Trackback URL
3901 */
3902 public function trackbackURL() {
3903 global $wgScriptPath, $wgServer, $wgScriptExtension;
3904
3905 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3906 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3907 }
3908
3909 /**
3910 * Get the trackback RDF for this page
3911 *
3912 * @return String Trackback RDF
3913 */
3914 public function trackbackRDF() {
3915 $url = htmlspecialchars( $this->getFullURL() );
3916 $title = htmlspecialchars( $this->getText() );
3917 $tburl = $this->trackbackURL();
3918
3919 // Autodiscovery RDF is placed in comments so HTML validator
3920 // won't barf. This is a rather icky workaround, but seems
3921 // frequently used by this kind of RDF thingy.
3922 //
3923 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3924 return "<!--
3925 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3926 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3927 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3928 <rdf:Description
3929 rdf:about=\"$url\"
3930 dc:identifier=\"$url\"
3931 dc:title=\"$title\"
3932 trackback:ping=\"$tburl\" />
3933 </rdf:RDF>
3934 -->";
3935 }
3936
3937 /**
3938 * Generate strings used for xml 'id' names in monobook tabs
3939 *
3940 * @param $prepend string defaults to 'nstab-'
3941 * @return String XML 'id' name
3942 */
3943 public function getNamespaceKey( $prepend = 'nstab-' ) {
3944 global $wgContLang;
3945 // Gets the subject namespace if this title
3946 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3947 // Checks if cononical namespace name exists for namespace
3948 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3949 // Uses canonical namespace name
3950 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3951 } else {
3952 // Uses text of namespace
3953 $namespaceKey = $this->getSubjectNsText();
3954 }
3955 // Makes namespace key lowercase
3956 $namespaceKey = $wgContLang->lc( $namespaceKey );
3957 // Uses main
3958 if ( $namespaceKey == '' ) {
3959 $namespaceKey = 'main';
3960 }
3961 // Changes file to image for backwards compatibility
3962 if ( $namespaceKey == 'file' ) {
3963 $namespaceKey = 'image';
3964 }
3965 return $prepend . $namespaceKey;
3966 }
3967
3968 /**
3969 * Returns true if this is a special page.
3970 *
3971 * @return boolean
3972 */
3973 public function isSpecialPage() {
3974 return $this->getNamespace() == NS_SPECIAL;
3975 }
3976
3977 /**
3978 * Returns true if this title resolves to the named special page
3979 *
3980 * @param $name String The special page name
3981 * @return boolean
3982 */
3983 public function isSpecial( $name ) {
3984 if ( $this->getNamespace() == NS_SPECIAL ) {
3985 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
3986 if ( $name == $thisName ) {
3987 return true;
3988 }
3989 }
3990 return false;
3991 }
3992
3993 /**
3994 * If the Title refers to a special page alias which is not the local default, resolve
3995 * the alias, and localise the name as necessary. Otherwise, return $this
3996 *
3997 * @return Title
3998 */
3999 public function fixSpecialName() {
4000 if ( $this->getNamespace() == NS_SPECIAL ) {
4001 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4002 if ( $canonicalName ) {
4003 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4004 if ( $localName != $this->mDbkeyform ) {
4005 return Title::makeTitle( NS_SPECIAL, $localName );
4006 }
4007 }
4008 }
4009 return $this;
4010 }
4011
4012 /**
4013 * Is this Title in a namespace which contains content?
4014 * In other words, is this a content page, for the purposes of calculating
4015 * statistics, etc?
4016 *
4017 * @return Boolean
4018 */
4019 public function isContentPage() {
4020 return MWNamespace::isContent( $this->getNamespace() );
4021 }
4022
4023 /**
4024 * Get all extant redirects to this Title
4025 *
4026 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4027 * @return Array of Title redirects to this title
4028 */
4029 public function getRedirectsHere( $ns = null ) {
4030 $redirs = array();
4031
4032 $dbr = wfGetDB( DB_SLAVE );
4033 $where = array(
4034 'rd_namespace' => $this->getNamespace(),
4035 'rd_title' => $this->getDBkey(),
4036 'rd_from = page_id'
4037 );
4038 if ( !is_null( $ns ) ) {
4039 $where['page_namespace'] = $ns;
4040 }
4041
4042 $res = $dbr->select(
4043 array( 'redirect', 'page' ),
4044 array( 'page_namespace', 'page_title' ),
4045 $where,
4046 __METHOD__
4047 );
4048
4049 foreach ( $res as $row ) {
4050 $redirs[] = self::newFromRow( $row );
4051 }
4052 return $redirs;
4053 }
4054
4055 /**
4056 * Check if this Title is a valid redirect target
4057 *
4058 * @return Bool
4059 */
4060 public function isValidRedirectTarget() {
4061 global $wgInvalidRedirectTargets;
4062
4063 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4064 if ( $this->isSpecial( 'Userlogout' ) ) {
4065 return false;
4066 }
4067
4068 foreach ( $wgInvalidRedirectTargets as $target ) {
4069 if ( $this->isSpecial( $target ) ) {
4070 return false;
4071 }
4072 }
4073
4074 return true;
4075 }
4076
4077 /**
4078 * Get a backlink cache object
4079 *
4080 * @return object BacklinkCache
4081 */
4082 function getBacklinkCache() {
4083 if ( is_null( $this->mBacklinkCache ) ) {
4084 $this->mBacklinkCache = new BacklinkCache( $this );
4085 }
4086 return $this->mBacklinkCache;
4087 }
4088
4089 /**
4090 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4091 *
4092 * @return Boolean
4093 */
4094 public function canUseNoindex() {
4095 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4096
4097 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4098 ? $wgContentNamespaces
4099 : $wgExemptFromUserRobotsControl;
4100
4101 return !in_array( $this->mNamespace, $bannedNamespaces );
4102
4103 }
4104
4105 /**
4106 * Returns restriction types for the current Title
4107 *
4108 * @return array applicable restriction types
4109 */
4110 public function getRestrictionTypes() {
4111 global $wgRestrictionTypes;
4112
4113 $types = $this->exists() ? $wgRestrictionTypes : array( 'create' );
4114
4115 if ( $this->getNamespace() != NS_FILE ) {
4116 $types = array_diff( $types, array( 'upload' ) );
4117 }
4118
4119 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4120
4121 return $types;
4122 }
4123
4124 /**
4125 * Returns the raw sort key to be used for categories, with the specified
4126 * prefix. This will be fed to Collation::getSortKey() to get a
4127 * binary sortkey that can be used for actual sorting.
4128 *
4129 * @param $prefix string The prefix to be used, specified using
4130 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4131 * prefix.
4132 * @return string
4133 */
4134 public function getCategorySortkey( $prefix = '' ) {
4135 $unprefixed = $this->getText();
4136 if ( $prefix !== '' ) {
4137 # Separate with a line feed, so the unprefixed part is only used as
4138 # a tiebreaker when two pages have the exact same prefix.
4139 # In UCA, tab is the only character that can sort above LF
4140 # so we strip both of them from the original prefix.
4141 $prefix = strtr( $prefix, "\n\t", ' ' );
4142 return "$prefix\n$unprefixed";
4143 }
4144 return $unprefixed;
4145 }
4146 }