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