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