Merge "Pass phpcs-strict on includes/rcfeed/"
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
26 */
27 define( 'USER_TOKEN_LENGTH', 32 );
28
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
32 */
33 define( 'MW_USER_VERSION', 9 );
34
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
38 */
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
40
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
44 */
45 class PasswordError extends MWException {
46 // NOP
47 }
48
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
58 */
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
63 */
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
67
68 /**
69 * Maximum items in $mWatchedItems
70 */
71 const MAX_WATCHED_ITEMS_CACHE = 100;
72
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
78 */
79 static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
100 );
101
102 /**
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
107 */
108 static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-categorypages',
147 'move-rootuserpages',
148 'move-subpages',
149 'nominornewtalk',
150 'noratelimit',
151 'override-export-depth',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'writeapi',
178 );
179 /**
180 * String Cached results of getAllRights()
181 */
182 static $mAllRights = false;
183
184 /** @name Cache variables */
185 //@{
186 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
187 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
188 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
189 $mGroups, $mOptionOverrides;
190
191 protected $mPasswordExpires;
192 //@}
193
194 /**
195 * Bool Whether the cache variables have been loaded.
196 */
197 //@{
198 var $mOptionsLoaded;
199
200 /**
201 * Array with already loaded items or true if all items have been loaded.
202 */
203 private $mLoadedItems = array();
204 //@}
205
206 /**
207 * String Initialization data source if mLoadedItems!==true. May be one of:
208 * - 'defaults' anonymous user initialised from class defaults
209 * - 'name' initialise from mName
210 * - 'id' initialise from mId
211 * - 'session' log in from cookies or session if possible
212 *
213 * Use the User::newFrom*() family of functions to set this.
214 */
215 var $mFrom;
216
217 /**
218 * Lazy-initialized variables, invalidated with clearInstanceCache
219 */
220 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
221 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
222 $mLocked, $mHideName, $mOptions;
223
224 /**
225 * @var WebRequest
226 */
227 private $mRequest;
228
229 /**
230 * @var Block
231 */
232 var $mBlock;
233
234 /**
235 * @var bool
236 */
237 var $mAllowUsertalk;
238
239 /**
240 * @var Block
241 */
242 private $mBlockedFromCreateAccount = false;
243
244 /**
245 * @var array
246 */
247 private $mWatchedItems = array();
248
249 static $idCacheByName = array();
250
251 /**
252 * Lightweight constructor for an anonymous user.
253 * Use the User::newFrom* factory functions for other kinds of users.
254 *
255 * @see newFromName()
256 * @see newFromId()
257 * @see newFromConfirmationCode()
258 * @see newFromSession()
259 * @see newFromRow()
260 */
261 public function __construct() {
262 $this->clearInstanceCache( 'defaults' );
263 }
264
265 /**
266 * @return string
267 */
268 public function __toString() {
269 return $this->getName();
270 }
271
272 /**
273 * Load the user table data for this object from the source given by mFrom.
274 */
275 public function load() {
276 if ( $this->mLoadedItems === true ) {
277 return;
278 }
279 wfProfileIn( __METHOD__ );
280
281 // Set it now to avoid infinite recursion in accessors
282 $this->mLoadedItems = true;
283
284 switch ( $this->mFrom ) {
285 case 'defaults':
286 $this->loadDefaults();
287 break;
288 case 'name':
289 $this->mId = self::idFromName( $this->mName );
290 if ( !$this->mId ) {
291 // Nonexistent user placeholder object
292 $this->loadDefaults( $this->mName );
293 } else {
294 $this->loadFromId();
295 }
296 break;
297 case 'id':
298 $this->loadFromId();
299 break;
300 case 'session':
301 if ( !$this->loadFromSession() ) {
302 // Loading from session failed. Load defaults.
303 $this->loadDefaults();
304 }
305 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
306 break;
307 default:
308 wfProfileOut( __METHOD__ );
309 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
310 }
311 wfProfileOut( __METHOD__ );
312 }
313
314 /**
315 * Load user table data, given mId has already been set.
316 * @return bool false if the ID does not exist, true otherwise
317 */
318 public function loadFromId() {
319 global $wgMemc;
320 if ( $this->mId == 0 ) {
321 $this->loadDefaults();
322 return false;
323 }
324
325 // Try cache
326 $key = wfMemcKey( 'user', 'id', $this->mId );
327 $data = $wgMemc->get( $key );
328 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
329 // Object is expired, load from DB
330 $data = false;
331 }
332
333 if ( !$data ) {
334 wfDebug( "User: cache miss for user {$this->mId}\n" );
335 // Load from DB
336 if ( !$this->loadFromDatabase() ) {
337 // Can't load from ID, user is anonymous
338 return false;
339 }
340 $this->saveToCache();
341 } else {
342 wfDebug( "User: got user {$this->mId} from cache\n" );
343 // Restore from cache
344 foreach ( self::$mCacheVars as $name ) {
345 $this->$name = $data[$name];
346 }
347 }
348
349 $this->mLoadedItems = true;
350
351 return true;
352 }
353
354 /**
355 * Save user data to the shared cache
356 */
357 public function saveToCache() {
358 $this->load();
359 $this->loadGroups();
360 $this->loadOptions();
361 if ( $this->isAnon() ) {
362 // Anonymous users are uncached
363 return;
364 }
365 $data = array();
366 foreach ( self::$mCacheVars as $name ) {
367 $data[$name] = $this->$name;
368 }
369 $data['mVersion'] = MW_USER_VERSION;
370 $key = wfMemcKey( 'user', 'id', $this->mId );
371 global $wgMemc;
372 $wgMemc->set( $key, $data );
373 }
374
375 /** @name newFrom*() static factory methods */
376 //@{
377
378 /**
379 * Static factory method for creation from username.
380 *
381 * This is slightly less efficient than newFromId(), so use newFromId() if
382 * you have both an ID and a name handy.
383 *
384 * @param string $name Username, validated by Title::newFromText()
385 * @param string|bool $validate Validate username. Takes the same parameters as
386 * User::getCanonicalName(), except that true is accepted as an alias
387 * for 'valid', for BC.
388 *
389 * @return User|bool User object, or false if the username is invalid
390 * (e.g. if it contains illegal characters or is an IP address). If the
391 * username is not present in the database, the result will be a user object
392 * with a name, zero user ID and default settings.
393 */
394 public static function newFromName( $name, $validate = 'valid' ) {
395 if ( $validate === true ) {
396 $validate = 'valid';
397 }
398 $name = self::getCanonicalName( $name, $validate );
399 if ( $name === false ) {
400 return false;
401 } else {
402 // Create unloaded user object
403 $u = new User;
404 $u->mName = $name;
405 $u->mFrom = 'name';
406 $u->setItemLoaded( 'name' );
407 return $u;
408 }
409 }
410
411 /**
412 * Static factory method for creation from a given user ID.
413 *
414 * @param int $id Valid user ID
415 * @return User The corresponding User object
416 */
417 public static function newFromId( $id ) {
418 $u = new User;
419 $u->mId = $id;
420 $u->mFrom = 'id';
421 $u->setItemLoaded( 'id' );
422 return $u;
423 }
424
425 /**
426 * Factory method to fetch whichever user has a given email confirmation code.
427 * This code is generated when an account is created or its e-mail address
428 * has changed.
429 *
430 * If the code is invalid or has expired, returns NULL.
431 *
432 * @param string $code Confirmation code
433 * @return User|null
434 */
435 public static function newFromConfirmationCode( $code ) {
436 $dbr = wfGetDB( DB_SLAVE );
437 $id = $dbr->selectField( 'user', 'user_id', array(
438 'user_email_token' => md5( $code ),
439 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
440 ) );
441 if ( $id !== false ) {
442 return User::newFromId( $id );
443 } else {
444 return null;
445 }
446 }
447
448 /**
449 * Create a new user object using data from session or cookies. If the
450 * login credentials are invalid, the result is an anonymous user.
451 *
452 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
453 * @return User
454 */
455 public static function newFromSession( WebRequest $request = null ) {
456 $user = new User;
457 $user->mFrom = 'session';
458 $user->mRequest = $request;
459 return $user;
460 }
461
462 /**
463 * Create a new user object from a user row.
464 * The row should have the following fields from the user table in it:
465 * - either user_name or user_id to load further data if needed (or both)
466 * - user_real_name
467 * - all other fields (email, password, etc.)
468 * It is useless to provide the remaining fields if either user_id,
469 * user_name and user_real_name are not provided because the whole row
470 * will be loaded once more from the database when accessing them.
471 *
472 * @param stdClass $row A row from the user table
473 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
474 * @return User
475 */
476 public static function newFromRow( $row, $data = null ) {
477 $user = new User;
478 $user->loadFromRow( $row, $data );
479 return $user;
480 }
481
482 //@}
483
484 /**
485 * Get the username corresponding to a given user ID
486 * @param int $id User ID
487 * @return string|bool The corresponding username
488 */
489 public static function whoIs( $id ) {
490 return UserCache::singleton()->getProp( $id, 'name' );
491 }
492
493 /**
494 * Get the real name of a user given their user ID
495 *
496 * @param int $id User ID
497 * @return string|bool The corresponding user's real name
498 */
499 public static function whoIsReal( $id ) {
500 return UserCache::singleton()->getProp( $id, 'real_name' );
501 }
502
503 /**
504 * Get database id given a user name
505 * @param string $name Username
506 * @return int|null The corresponding user's ID, or null if user is nonexistent
507 */
508 public static function idFromName( $name ) {
509 $nt = Title::makeTitleSafe( NS_USER, $name );
510 if ( is_null( $nt ) ) {
511 // Illegal name
512 return null;
513 }
514
515 if ( isset( self::$idCacheByName[$name] ) ) {
516 return self::$idCacheByName[$name];
517 }
518
519 $dbr = wfGetDB( DB_SLAVE );
520 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
521
522 if ( $s === false ) {
523 $result = null;
524 } else {
525 $result = $s->user_id;
526 }
527
528 self::$idCacheByName[$name] = $result;
529
530 if ( count( self::$idCacheByName ) > 1000 ) {
531 self::$idCacheByName = array();
532 }
533
534 return $result;
535 }
536
537 /**
538 * Reset the cache used in idFromName(). For use in tests.
539 */
540 public static function resetIdByNameCache() {
541 self::$idCacheByName = array();
542 }
543
544 /**
545 * Does the string match an anonymous IPv4 address?
546 *
547 * This function exists for username validation, in order to reject
548 * usernames which are similar in form to IP addresses. Strings such
549 * as 300.300.300.300 will return true because it looks like an IP
550 * address, despite not being strictly valid.
551 *
552 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
553 * address because the usemod software would "cloak" anonymous IP
554 * addresses like this, if we allowed accounts like this to be created
555 * new users could get the old edits of these anonymous users.
556 *
557 * @param string $name Name to match
558 * @return bool
559 */
560 public static function isIP( $name ) {
561 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
562 }
563
564 /**
565 * Is the input a valid username?
566 *
567 * Checks if the input is a valid username, we don't want an empty string,
568 * an IP address, anything that contains slashes (would mess up subpages),
569 * is longer than the maximum allowed username size or doesn't begin with
570 * a capital letter.
571 *
572 * @param string $name Name to match
573 * @return bool
574 */
575 public static function isValidUserName( $name ) {
576 global $wgContLang, $wgMaxNameChars;
577
578 if ( $name == ''
579 || User::isIP( $name )
580 || strpos( $name, '/' ) !== false
581 || strlen( $name ) > $wgMaxNameChars
582 || $name != $wgContLang->ucfirst( $name ) ) {
583 wfDebugLog( 'username', __METHOD__ .
584 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
585 return false;
586 }
587
588 // Ensure that the name can't be misresolved as a different title,
589 // such as with extra namespace keys at the start.
590 $parsed = Title::newFromText( $name );
591 if ( is_null( $parsed )
592 || $parsed->getNamespace()
593 || strcmp( $name, $parsed->getPrefixedText() ) ) {
594 wfDebugLog( 'username', __METHOD__ .
595 ": '$name' invalid due to ambiguous prefixes" );
596 return false;
597 }
598
599 // Check an additional blacklist of troublemaker characters.
600 // Should these be merged into the title char list?
601 $unicodeBlacklist = '/[' .
602 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
603 '\x{00a0}' . # non-breaking space
604 '\x{2000}-\x{200f}' . # various whitespace
605 '\x{2028}-\x{202f}' . # breaks and control chars
606 '\x{3000}' . # ideographic space
607 '\x{e000}-\x{f8ff}' . # private use
608 ']/u';
609 if ( preg_match( $unicodeBlacklist, $name ) ) {
610 wfDebugLog( 'username', __METHOD__ .
611 ": '$name' invalid due to blacklisted characters" );
612 return false;
613 }
614
615 return true;
616 }
617
618 /**
619 * Usernames which fail to pass this function will be blocked
620 * from user login and new account registrations, but may be used
621 * internally by batch processes.
622 *
623 * If an account already exists in this form, login will be blocked
624 * by a failure to pass this function.
625 *
626 * @param string $name Name to match
627 * @return bool
628 */
629 public static function isUsableName( $name ) {
630 global $wgReservedUsernames;
631 // Must be a valid username, obviously ;)
632 if ( !self::isValidUserName( $name ) ) {
633 return false;
634 }
635
636 static $reservedUsernames = false;
637 if ( !$reservedUsernames ) {
638 $reservedUsernames = $wgReservedUsernames;
639 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
640 }
641
642 // Certain names may be reserved for batch processes.
643 foreach ( $reservedUsernames as $reserved ) {
644 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
645 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
646 }
647 if ( $reserved == $name ) {
648 return false;
649 }
650 }
651 return true;
652 }
653
654 /**
655 * Usernames which fail to pass this function will be blocked
656 * from new account registrations, but may be used internally
657 * either by batch processes or by user accounts which have
658 * already been created.
659 *
660 * Additional blacklisting may be added here rather than in
661 * isValidUserName() to avoid disrupting existing accounts.
662 *
663 * @param string $name String to match
664 * @return bool
665 */
666 public static function isCreatableName( $name ) {
667 global $wgInvalidUsernameCharacters;
668
669 // Ensure that the username isn't longer than 235 bytes, so that
670 // (at least for the builtin skins) user javascript and css files
671 // will work. (bug 23080)
672 if ( strlen( $name ) > 235 ) {
673 wfDebugLog( 'username', __METHOD__ .
674 ": '$name' invalid due to length" );
675 return false;
676 }
677
678 // Preg yells if you try to give it an empty string
679 if ( $wgInvalidUsernameCharacters !== '' ) {
680 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
681 wfDebugLog( 'username', __METHOD__ .
682 ": '$name' invalid due to wgInvalidUsernameCharacters" );
683 return false;
684 }
685 }
686
687 return self::isUsableName( $name );
688 }
689
690 /**
691 * Is the input a valid password for this user?
692 *
693 * @param string $password Desired password
694 * @return bool
695 */
696 public function isValidPassword( $password ) {
697 //simple boolean wrapper for getPasswordValidity
698 return $this->getPasswordValidity( $password ) === true;
699 }
700
701
702 /**
703 * Given unvalidated password input, return error message on failure.
704 *
705 * @param string $password Desired password
706 * @return bool|string|array true on success, string or array of error message on failure
707 */
708 public function getPasswordValidity( $password ) {
709 $result = $this->checkPasswordValidity( $password );
710 if ( $result->isGood() ) {
711 return true;
712 } else {
713 $messages = array();
714 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
715 $messages[] = $error['message'];
716 }
717 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
718 $messages[] = $warning['message'];
719 }
720 if ( count( $messages ) === 1 ) {
721 return $messages[0];
722 }
723 return $messages;
724 }
725 }
726
727 /**
728 * Check if this is a valid password for this user. Status will be good if
729 * the password is valid, or have an array of error messages if not.
730 *
731 * @param string $password Desired password
732 * @return Status
733 * @since 1.23
734 */
735 public function checkPasswordValidity( $password ) {
736 global $wgMinimalPasswordLength, $wgContLang;
737
738 static $blockedLogins = array(
739 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
740 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
741 );
742
743 $status = Status::newGood();
744
745 $result = false; //init $result to false for the internal checks
746
747 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
748 $status->error( $result );
749 return $status;
750 }
751
752 if ( $result === false ) {
753 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
754 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
755 return $status;
756 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
757 $status->error( 'password-name-match' );
758 return $status;
759 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
760 $status->error( 'password-login-forbidden' );
761 return $status;
762 } else {
763 //it seems weird returning a Good status here, but this is because of the
764 //initialization of $result to false above. If the hook is never run or it
765 //doesn't modify $result, then we will likely get down into this if with
766 //a valid password.
767 return $status;
768 }
769 } elseif ( $result === true ) {
770 return $status;
771 } else {
772 $status->error( $result );
773 return $status; //the isValidPassword hook set a string $result and returned true
774 }
775 }
776
777 /**
778 * Expire a user's password
779 * @since 1.23
780 * @param int $ts Optional timestamp to convert, default 0 for the current time
781 */
782 public function expirePassword( $ts = 0 ) {
783 $this->load();
784 $timestamp = wfTimestamp( TS_MW, $ts );
785 $this->mPasswordExpires = $timestamp;
786 $this->saveSettings();
787 }
788
789 /**
790 * Clear the password expiration for a user
791 * @since 1.23
792 * @param bool $load Ensure user object is loaded first
793 */
794 public function resetPasswordExpiration( $load = true ) {
795 global $wgPasswordExpirationDays;
796 if ( $load ) {
797 $this->load();
798 }
799 $newExpire = null;
800 if ( $wgPasswordExpirationDays ) {
801 $newExpire = wfTimestamp(
802 TS_MW,
803 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
804 );
805 }
806 // Give extensions a chance to force an expiration
807 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
808 $this->mPasswordExpires = $newExpire;
809 }
810
811 /**
812 * Check if the user's password is expired.
813 * TODO: Put this and password length into a PasswordPolicy object
814 * @since 1.23
815 * @return string|bool The expiration type, or false if not expired
816 * hard: A password change is required to login
817 * soft: Allow login, but encourage password change
818 * false: Password is not expired
819 */
820 public function getPasswordExpired() {
821 global $wgPasswordExpireGrace;
822 $expired = false;
823 $now = wfTimestamp();
824 $expiration = $this->getPasswordExpireDate();
825 $expUnix = wfTimestamp( TS_UNIX, $expiration );
826 if ( $expiration !== null && $expUnix < $now ) {
827 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
828 }
829 return $expired;
830 }
831
832 /**
833 * Get this user's password expiration date. Since this may be using
834 * the cached User object, we assume that whatever mechanism is setting
835 * the expiration date is also expiring the User cache.
836 * @since 1.23
837 * @return string|bool The datestamp of the expiration, or null if not set
838 */
839 public function getPasswordExpireDate() {
840 $this->load();
841 return $this->mPasswordExpires;
842 }
843
844 /**
845 * Does a string look like an e-mail address?
846 *
847 * This validates an email address using an HTML5 specification found at:
848 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
849 * Which as of 2011-01-24 says:
850 *
851 * A valid e-mail address is a string that matches the ABNF production
852 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
853 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
854 * 3.5.
855 *
856 * This function is an implementation of the specification as requested in
857 * bug 22449.
858 *
859 * Client-side forms will use the same standard validation rules via JS or
860 * HTML 5 validation; additional restrictions can be enforced server-side
861 * by extensions via the 'isValidEmailAddr' hook.
862 *
863 * Note that this validation doesn't 100% match RFC 2822, but is believed
864 * to be liberal enough for wide use. Some invalid addresses will still
865 * pass validation here.
866 *
867 * @param string $addr E-mail address
868 * @return bool
869 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
870 */
871 public static function isValidEmailAddr( $addr ) {
872 wfDeprecated( __METHOD__, '1.18' );
873 return Sanitizer::validateEmail( $addr );
874 }
875
876 /**
877 * Given unvalidated user input, return a canonical username, or false if
878 * the username is invalid.
879 * @param string $name User input
880 * @param string|bool $validate Type of validation to use:
881 * - false No validation
882 * - 'valid' Valid for batch processes
883 * - 'usable' Valid for batch processes and login
884 * - 'creatable' Valid for batch processes, login and account creation
885 *
886 * @throws MWException
887 * @return bool|string
888 */
889 public static function getCanonicalName( $name, $validate = 'valid' ) {
890 // Force usernames to capital
891 global $wgContLang;
892 $name = $wgContLang->ucfirst( $name );
893
894 # Reject names containing '#'; these will be cleaned up
895 # with title normalisation, but then it's too late to
896 # check elsewhere
897 if ( strpos( $name, '#' ) !== false ) {
898 return false;
899 }
900
901 // Clean up name according to title rules
902 $t = ( $validate === 'valid' ) ?
903 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
904 // Check for invalid titles
905 if ( is_null( $t ) ) {
906 return false;
907 }
908
909 // Reject various classes of invalid names
910 global $wgAuth;
911 $name = $wgAuth->getCanonicalName( $t->getText() );
912
913 switch ( $validate ) {
914 case false:
915 break;
916 case 'valid':
917 if ( !User::isValidUserName( $name ) ) {
918 $name = false;
919 }
920 break;
921 case 'usable':
922 if ( !User::isUsableName( $name ) ) {
923 $name = false;
924 }
925 break;
926 case 'creatable':
927 if ( !User::isCreatableName( $name ) ) {
928 $name = false;
929 }
930 break;
931 default:
932 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
933 }
934 return $name;
935 }
936
937 /**
938 * Count the number of edits of a user
939 *
940 * @param int $uid User ID to check
941 * @return int The user's edit count
942 *
943 * @deprecated since 1.21 in favour of User::getEditCount
944 */
945 public static function edits( $uid ) {
946 wfDeprecated( __METHOD__, '1.21' );
947 $user = self::newFromId( $uid );
948 return $user->getEditCount();
949 }
950
951 /**
952 * Return a random password.
953 *
954 * @return string New random password
955 */
956 public static function randomPassword() {
957 global $wgMinimalPasswordLength;
958 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
959 $length = max( 10, $wgMinimalPasswordLength );
960 // Multiply by 1.25 to get the number of hex characters we need
961 $length = $length * 1.25;
962 // Generate random hex chars
963 $hex = MWCryptRand::generateHex( $length );
964 // Convert from base 16 to base 32 to get a proper password like string
965 return wfBaseConvert( $hex, 16, 32 );
966 }
967
968 /**
969 * Set cached properties to default.
970 *
971 * @note This no longer clears uncached lazy-initialised properties;
972 * the constructor does that instead.
973 *
974 * @param string|bool $name
975 */
976 public function loadDefaults( $name = false ) {
977 wfProfileIn( __METHOD__ );
978
979 $this->mId = 0;
980 $this->mName = $name;
981 $this->mRealName = '';
982 $this->mPassword = $this->mNewpassword = '';
983 $this->mNewpassTime = null;
984 $this->mEmail = '';
985 $this->mOptionOverrides = null;
986 $this->mOptionsLoaded = false;
987
988 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
989 if ( $loggedOut !== null ) {
990 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
991 } else {
992 $this->mTouched = '1'; # Allow any pages to be cached
993 }
994
995 $this->mToken = null; // Don't run cryptographic functions till we need a token
996 $this->mEmailAuthenticated = null;
997 $this->mEmailToken = '';
998 $this->mEmailTokenExpires = null;
999 $this->mPasswordExpires = null;
1000 $this->resetPasswordExpiration( false );
1001 $this->mRegistration = wfTimestamp( TS_MW );
1002 $this->mGroups = array();
1003
1004 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1005
1006 wfProfileOut( __METHOD__ );
1007 }
1008
1009 /**
1010 * Return whether an item has been loaded.
1011 *
1012 * @param string $item Item to check. Current possibilities:
1013 * - id
1014 * - name
1015 * - realname
1016 * @param string $all 'all' to check if the whole object has been loaded
1017 * or any other string to check if only the item is available (e.g.
1018 * for optimisation)
1019 * @return bool
1020 */
1021 public function isItemLoaded( $item, $all = 'all' ) {
1022 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1023 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1024 }
1025
1026 /**
1027 * Set that an item has been loaded
1028 *
1029 * @param string $item
1030 */
1031 protected function setItemLoaded( $item ) {
1032 if ( is_array( $this->mLoadedItems ) ) {
1033 $this->mLoadedItems[$item] = true;
1034 }
1035 }
1036
1037 /**
1038 * Load user data from the session or login cookie.
1039 * @return bool True if the user is logged in, false otherwise.
1040 */
1041 private function loadFromSession() {
1042 $result = null;
1043 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1044 if ( $result !== null ) {
1045 return $result;
1046 }
1047
1048 $request = $this->getRequest();
1049
1050 $cookieId = $request->getCookie( 'UserID' );
1051 $sessId = $request->getSessionData( 'wsUserID' );
1052
1053 if ( $cookieId !== null ) {
1054 $sId = intval( $cookieId );
1055 if ( $sessId !== null && $cookieId != $sessId ) {
1056 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1057 cookie user ID ($sId) don't match!" );
1058 return false;
1059 }
1060 $request->setSessionData( 'wsUserID', $sId );
1061 } elseif ( $sessId !== null && $sessId != 0 ) {
1062 $sId = $sessId;
1063 } else {
1064 return false;
1065 }
1066
1067 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1068 $sName = $request->getSessionData( 'wsUserName' );
1069 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1070 $sName = $request->getCookie( 'UserName' );
1071 $request->setSessionData( 'wsUserName', $sName );
1072 } else {
1073 return false;
1074 }
1075
1076 $proposedUser = User::newFromId( $sId );
1077 if ( !$proposedUser->isLoggedIn() ) {
1078 // Not a valid ID
1079 return false;
1080 }
1081
1082 global $wgBlockDisablesLogin;
1083 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1084 // User blocked and we've disabled blocked user logins
1085 return false;
1086 }
1087
1088 if ( $request->getSessionData( 'wsToken' ) ) {
1089 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1090 $from = 'session';
1091 } elseif ( $request->getCookie( 'Token' ) ) {
1092 # Get the token from DB/cache and clean it up to remove garbage padding.
1093 # This deals with historical problems with bugs and the default column value.
1094 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1095 // Make comparison in constant time (bug 61346)
1096 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1097 $from = 'cookie';
1098 } else {
1099 // No session or persistent login cookie
1100 return false;
1101 }
1102
1103 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1104 $this->loadFromUserObject( $proposedUser );
1105 $request->setSessionData( 'wsToken', $this->mToken );
1106 wfDebug( "User: logged in from $from\n" );
1107 return true;
1108 } else {
1109 // Invalid credentials
1110 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1111 return false;
1112 }
1113 }
1114
1115 /**
1116 * A comparison of two strings, not vulnerable to timing attacks
1117 * @param string $answer The secret string that you are comparing against.
1118 * @param string $test Compare this string to the $answer.
1119 * @return bool True if the strings are the same, false otherwise
1120 */
1121 protected function compareSecrets( $answer, $test ) {
1122 if ( strlen( $answer ) !== strlen( $test ) ) {
1123 $passwordCorrect = false;
1124 } else {
1125 $result = 0;
1126 for ( $i = 0; $i < strlen( $answer ); $i++ ) {
1127 $result |= ord( $answer[$i] ) ^ ord( $test[$i] );
1128 }
1129 $passwordCorrect = ( $result == 0 );
1130 }
1131 return $passwordCorrect;
1132 }
1133
1134 /**
1135 * Load user and user_group data from the database.
1136 * $this->mId must be set, this is how the user is identified.
1137 *
1138 * @return bool True if the user exists, false if the user is anonymous
1139 */
1140 public function loadFromDatabase() {
1141 // Paranoia
1142 $this->mId = intval( $this->mId );
1143
1144 // Anonymous user
1145 if ( !$this->mId ) {
1146 $this->loadDefaults();
1147 return false;
1148 }
1149
1150 $dbr = wfGetDB( DB_MASTER );
1151 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1152
1153 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1154
1155 if ( $s !== false ) {
1156 // Initialise user table data
1157 $this->loadFromRow( $s );
1158 $this->mGroups = null; // deferred
1159 $this->getEditCount(); // revalidation for nulls
1160 return true;
1161 } else {
1162 // Invalid user_id
1163 $this->mId = 0;
1164 $this->loadDefaults();
1165 return false;
1166 }
1167 }
1168
1169 /**
1170 * Initialize this object from a row from the user table.
1171 *
1172 * @param stdClass $row Row from the user table to load.
1173 * @param array $data Further user data to load into the object
1174 *
1175 * user_groups Array with groups out of the user_groups table
1176 * user_properties Array with properties out of the user_properties table
1177 */
1178 public function loadFromRow( $row, $data = null ) {
1179 $all = true;
1180
1181 $this->mGroups = null; // deferred
1182
1183 if ( isset( $row->user_name ) ) {
1184 $this->mName = $row->user_name;
1185 $this->mFrom = 'name';
1186 $this->setItemLoaded( 'name' );
1187 } else {
1188 $all = false;
1189 }
1190
1191 if ( isset( $row->user_real_name ) ) {
1192 $this->mRealName = $row->user_real_name;
1193 $this->setItemLoaded( 'realname' );
1194 } else {
1195 $all = false;
1196 }
1197
1198 if ( isset( $row->user_id ) ) {
1199 $this->mId = intval( $row->user_id );
1200 $this->mFrom = 'id';
1201 $this->setItemLoaded( 'id' );
1202 } else {
1203 $all = false;
1204 }
1205
1206 if ( isset( $row->user_editcount ) ) {
1207 $this->mEditCount = $row->user_editcount;
1208 } else {
1209 $all = false;
1210 }
1211
1212 if ( isset( $row->user_password ) ) {
1213 $this->mPassword = $row->user_password;
1214 $this->mNewpassword = $row->user_newpassword;
1215 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1216 $this->mEmail = $row->user_email;
1217 if ( isset( $row->user_options ) ) {
1218 $this->decodeOptions( $row->user_options );
1219 }
1220 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1221 $this->mToken = $row->user_token;
1222 if ( $this->mToken == '' ) {
1223 $this->mToken = null;
1224 }
1225 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1226 $this->mEmailToken = $row->user_email_token;
1227 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1228 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1229 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1230 } else {
1231 $all = false;
1232 }
1233
1234 if ( $all ) {
1235 $this->mLoadedItems = true;
1236 }
1237
1238 if ( is_array( $data ) ) {
1239 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1240 $this->mGroups = $data['user_groups'];
1241 }
1242 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1243 $this->loadOptions( $data['user_properties'] );
1244 }
1245 }
1246 }
1247
1248 /**
1249 * Load the data for this user object from another user object.
1250 *
1251 * @param User $user
1252 */
1253 protected function loadFromUserObject( $user ) {
1254 $user->load();
1255 $user->loadGroups();
1256 $user->loadOptions();
1257 foreach ( self::$mCacheVars as $var ) {
1258 $this->$var = $user->$var;
1259 }
1260 }
1261
1262 /**
1263 * Load the groups from the database if they aren't already loaded.
1264 */
1265 private function loadGroups() {
1266 if ( is_null( $this->mGroups ) ) {
1267 $dbr = wfGetDB( DB_MASTER );
1268 $res = $dbr->select( 'user_groups',
1269 array( 'ug_group' ),
1270 array( 'ug_user' => $this->mId ),
1271 __METHOD__ );
1272 $this->mGroups = array();
1273 foreach ( $res as $row ) {
1274 $this->mGroups[] = $row->ug_group;
1275 }
1276 }
1277 }
1278
1279 /**
1280 * Add the user to the group if he/she meets given criteria.
1281 *
1282 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1283 * possible to remove manually via Special:UserRights. In such case it
1284 * will not be re-added automatically. The user will also not lose the
1285 * group if they no longer meet the criteria.
1286 *
1287 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1288 *
1289 * @return array Array of groups the user has been promoted to.
1290 *
1291 * @see $wgAutopromoteOnce
1292 */
1293 public function addAutopromoteOnceGroups( $event ) {
1294 global $wgAutopromoteOnceLogInRC, $wgAuth;
1295
1296 $toPromote = array();
1297 if ( $this->getId() ) {
1298 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1299 if ( count( $toPromote ) ) {
1300 $oldGroups = $this->getGroups(); // previous groups
1301
1302 foreach ( $toPromote as $group ) {
1303 $this->addGroup( $group );
1304 }
1305 // update groups in external authentication database
1306 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1307
1308 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1309
1310 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1311 $logEntry->setPerformer( $this );
1312 $logEntry->setTarget( $this->getUserPage() );
1313 $logEntry->setParameters( array(
1314 '4::oldgroups' => $oldGroups,
1315 '5::newgroups' => $newGroups,
1316 ) );
1317 $logid = $logEntry->insert();
1318 if ( $wgAutopromoteOnceLogInRC ) {
1319 $logEntry->publish( $logid );
1320 }
1321 }
1322 }
1323 return $toPromote;
1324 }
1325
1326 /**
1327 * Clear various cached data stored in this object. The cache of the user table
1328 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1329 *
1330 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1331 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1332 */
1333 public function clearInstanceCache( $reloadFrom = false ) {
1334 $this->mNewtalk = -1;
1335 $this->mDatePreference = null;
1336 $this->mBlockedby = -1; # Unset
1337 $this->mHash = false;
1338 $this->mRights = null;
1339 $this->mEffectiveGroups = null;
1340 $this->mImplicitGroups = null;
1341 $this->mGroups = null;
1342 $this->mOptions = null;
1343 $this->mOptionsLoaded = false;
1344 $this->mEditCount = null;
1345
1346 if ( $reloadFrom ) {
1347 $this->mLoadedItems = array();
1348 $this->mFrom = $reloadFrom;
1349 }
1350 }
1351
1352 /**
1353 * Combine the language default options with any site-specific options
1354 * and add the default language variants.
1355 *
1356 * @return array Array of String options
1357 */
1358 public static function getDefaultOptions() {
1359 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1360
1361 static $defOpt = null;
1362 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1363 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1364 // mid-request and see that change reflected in the return value of this function.
1365 // Which is insane and would never happen during normal MW operation
1366 return $defOpt;
1367 }
1368
1369 $defOpt = $wgDefaultUserOptions;
1370 // Default language setting
1371 $defOpt['language'] = $wgContLang->getCode();
1372 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1373 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1374 }
1375 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1376 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1377 }
1378 $defOpt['skin'] = $wgDefaultSkin;
1379
1380 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1381
1382 return $defOpt;
1383 }
1384
1385 /**
1386 * Get a given default option value.
1387 *
1388 * @param string $opt Name of option to retrieve
1389 * @return string Default option value
1390 */
1391 public static function getDefaultOption( $opt ) {
1392 $defOpts = self::getDefaultOptions();
1393 if ( isset( $defOpts[$opt] ) ) {
1394 return $defOpts[$opt];
1395 } else {
1396 return null;
1397 }
1398 }
1399
1400 /**
1401 * Get blocking information
1402 * @param bool $bFromSlave Whether to check the slave database first.
1403 * To improve performance, non-critical checks are done against slaves.
1404 * Check when actually saving should be done against master.
1405 */
1406 private function getBlockedStatus( $bFromSlave = true ) {
1407 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1408
1409 if ( -1 != $this->mBlockedby ) {
1410 return;
1411 }
1412
1413 wfProfileIn( __METHOD__ );
1414 wfDebug( __METHOD__ . ": checking...\n" );
1415
1416 // Initialize data...
1417 // Otherwise something ends up stomping on $this->mBlockedby when
1418 // things get lazy-loaded later, causing false positive block hits
1419 // due to -1 !== 0. Probably session-related... Nothing should be
1420 // overwriting mBlockedby, surely?
1421 $this->load();
1422
1423 # We only need to worry about passing the IP address to the Block generator if the
1424 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1425 # know which IP address they're actually coming from
1426 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1427 $ip = $this->getRequest()->getIP();
1428 } else {
1429 $ip = null;
1430 }
1431
1432 // User/IP blocking
1433 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1434
1435 // Proxy blocking
1436 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1437 && !in_array( $ip, $wgProxyWhitelist )
1438 ) {
1439 // Local list
1440 if ( self::isLocallyBlockedProxy( $ip ) ) {
1441 $block = new Block;
1442 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1443 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1444 $block->setTarget( $ip );
1445 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1446 $block = new Block;
1447 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1448 $block->mReason = wfMessage( 'sorbsreason' )->text();
1449 $block->setTarget( $ip );
1450 }
1451 }
1452
1453 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1454 if ( !$block instanceof Block
1455 && $wgApplyIpBlocksToXff
1456 && $ip !== null
1457 && !$this->isAllowed( 'proxyunbannable' )
1458 && !in_array( $ip, $wgProxyWhitelist )
1459 ) {
1460 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1461 $xff = array_map( 'trim', explode( ',', $xff ) );
1462 $xff = array_diff( $xff, array( $ip ) );
1463 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1464 $block = Block::chooseBlock( $xffblocks, $xff );
1465 if ( $block instanceof Block ) {
1466 # Mangle the reason to alert the user that the block
1467 # originated from matching the X-Forwarded-For header.
1468 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1469 }
1470 }
1471
1472 if ( $block instanceof Block ) {
1473 wfDebug( __METHOD__ . ": Found block.\n" );
1474 $this->mBlock = $block;
1475 $this->mBlockedby = $block->getByName();
1476 $this->mBlockreason = $block->mReason;
1477 $this->mHideName = $block->mHideName;
1478 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1479 } else {
1480 $this->mBlockedby = '';
1481 $this->mHideName = 0;
1482 $this->mAllowUsertalk = false;
1483 }
1484
1485 // Extensions
1486 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1487
1488 wfProfileOut( __METHOD__ );
1489 }
1490
1491 /**
1492 * Whether the given IP is in a DNS blacklist.
1493 *
1494 * @param string $ip IP to check
1495 * @param bool $checkWhitelist Whether to check the whitelist first
1496 * @return bool True if blacklisted.
1497 */
1498 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1499 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1500 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1501
1502 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1503 return false;
1504 }
1505
1506 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1507 return false;
1508 }
1509
1510 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1511 return $this->inDnsBlacklist( $ip, $urls );
1512 }
1513
1514 /**
1515 * Whether the given IP is in a given DNS blacklist.
1516 *
1517 * @param string $ip IP to check
1518 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1519 * @return bool True if blacklisted.
1520 */
1521 public function inDnsBlacklist( $ip, $bases ) {
1522 wfProfileIn( __METHOD__ );
1523
1524 $found = false;
1525 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1526 if ( IP::isIPv4( $ip ) ) {
1527 // Reverse IP, bug 21255
1528 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1529
1530 foreach ( (array)$bases as $base ) {
1531 // Make hostname
1532 // If we have an access key, use that too (ProjectHoneypot, etc.)
1533 if ( is_array( $base ) ) {
1534 if ( count( $base ) >= 2 ) {
1535 // Access key is 1, base URL is 0
1536 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1537 } else {
1538 $host = "$ipReversed.{$base[0]}";
1539 }
1540 } else {
1541 $host = "$ipReversed.$base";
1542 }
1543
1544 // Send query
1545 $ipList = gethostbynamel( $host );
1546
1547 if ( $ipList ) {
1548 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1549 $found = true;
1550 break;
1551 } else {
1552 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1553 }
1554 }
1555 }
1556
1557 wfProfileOut( __METHOD__ );
1558 return $found;
1559 }
1560
1561 /**
1562 * Check if an IP address is in the local proxy list
1563 *
1564 * @param string $ip
1565 *
1566 * @return bool
1567 */
1568 public static function isLocallyBlockedProxy( $ip ) {
1569 global $wgProxyList;
1570
1571 if ( !$wgProxyList ) {
1572 return false;
1573 }
1574 wfProfileIn( __METHOD__ );
1575
1576 if ( !is_array( $wgProxyList ) ) {
1577 // Load from the specified file
1578 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1579 }
1580
1581 if ( !is_array( $wgProxyList ) ) {
1582 $ret = false;
1583 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1584 $ret = true;
1585 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1586 // Old-style flipped proxy list
1587 $ret = true;
1588 } else {
1589 $ret = false;
1590 }
1591 wfProfileOut( __METHOD__ );
1592 return $ret;
1593 }
1594
1595 /**
1596 * Is this user subject to rate limiting?
1597 *
1598 * @return bool True if rate limited
1599 */
1600 public function isPingLimitable() {
1601 global $wgRateLimitsExcludedIPs;
1602 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1603 // No other good way currently to disable rate limits
1604 // for specific IPs. :P
1605 // But this is a crappy hack and should die.
1606 return false;
1607 }
1608 return !$this->isAllowed( 'noratelimit' );
1609 }
1610
1611 /**
1612 * Primitive rate limits: enforce maximum actions per time period
1613 * to put a brake on flooding.
1614 *
1615 * @note When using a shared cache like memcached, IP-address
1616 * last-hit counters will be shared across wikis.
1617 *
1618 * @param string $action Action to enforce; 'edit' if unspecified
1619 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1620 * @return bool True if a rate limiter was tripped
1621 */
1622 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1623 // Call the 'PingLimiter' hook
1624 $result = false;
1625 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1626 return $result;
1627 }
1628
1629 global $wgRateLimits;
1630 if ( !isset( $wgRateLimits[$action] ) ) {
1631 return false;
1632 }
1633
1634 // Some groups shouldn't trigger the ping limiter, ever
1635 if ( !$this->isPingLimitable() ) {
1636 return false;
1637 }
1638
1639 global $wgMemc;
1640 wfProfileIn( __METHOD__ );
1641
1642 $limits = $wgRateLimits[$action];
1643 $keys = array();
1644 $id = $this->getId();
1645 $userLimit = false;
1646
1647 if ( isset( $limits['anon'] ) && $id == 0 ) {
1648 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1649 }
1650
1651 if ( isset( $limits['user'] ) && $id != 0 ) {
1652 $userLimit = $limits['user'];
1653 }
1654 if ( $this->isNewbie() ) {
1655 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1656 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1657 }
1658 if ( isset( $limits['ip'] ) ) {
1659 $ip = $this->getRequest()->getIP();
1660 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1661 }
1662 if ( isset( $limits['subnet'] ) ) {
1663 $ip = $this->getRequest()->getIP();
1664 $matches = array();
1665 $subnet = false;
1666 if ( IP::isIPv6( $ip ) ) {
1667 $parts = IP::parseRange( "$ip/64" );
1668 $subnet = $parts[0];
1669 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1670 // IPv4
1671 $subnet = $matches[1];
1672 }
1673 if ( $subnet !== false ) {
1674 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1675 }
1676 }
1677 }
1678 // Check for group-specific permissions
1679 // If more than one group applies, use the group with the highest limit
1680 foreach ( $this->getGroups() as $group ) {
1681 if ( isset( $limits[$group] ) ) {
1682 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1683 $userLimit = $limits[$group];
1684 }
1685 }
1686 }
1687 // Set the user limit key
1688 if ( $userLimit !== false ) {
1689 list( $max, $period ) = $userLimit;
1690 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1691 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1692 }
1693
1694 $triggered = false;
1695 foreach ( $keys as $key => $limit ) {
1696 list( $max, $period ) = $limit;
1697 $summary = "(limit $max in {$period}s)";
1698 $count = $wgMemc->get( $key );
1699 // Already pinged?
1700 if ( $count ) {
1701 if ( $count >= $max ) {
1702 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1703 $triggered = true;
1704 } else {
1705 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1706 }
1707 } else {
1708 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1709 if ( $incrBy > 0 ) {
1710 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1711 }
1712 }
1713 if ( $incrBy > 0 ) {
1714 $wgMemc->incr( $key, $incrBy );
1715 }
1716 }
1717
1718 wfProfileOut( __METHOD__ );
1719 return $triggered;
1720 }
1721
1722 /**
1723 * Check if user is blocked
1724 *
1725 * @param bool $bFromSlave Whether to check the slave database instead of the master
1726 * @return bool True if blocked, false otherwise
1727 */
1728 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1729 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1730 }
1731
1732 /**
1733 * Get the block affecting the user, or null if the user is not blocked
1734 *
1735 * @param bool $bFromSlave Whether to check the slave database instead of the master
1736 * @return Block|null
1737 */
1738 public function getBlock( $bFromSlave = true ) {
1739 $this->getBlockedStatus( $bFromSlave );
1740 return $this->mBlock instanceof Block ? $this->mBlock : null;
1741 }
1742
1743 /**
1744 * Check if user is blocked from editing a particular article
1745 *
1746 * @param Title $title Title to check
1747 * @param bool $bFromSlave Whether to check the slave database instead of the master
1748 * @return bool
1749 */
1750 public function isBlockedFrom( $title, $bFromSlave = false ) {
1751 global $wgBlockAllowsUTEdit;
1752 wfProfileIn( __METHOD__ );
1753
1754 $blocked = $this->isBlocked( $bFromSlave );
1755 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1756 // If a user's name is suppressed, they cannot make edits anywhere
1757 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1758 && $title->getNamespace() == NS_USER_TALK ) {
1759 $blocked = false;
1760 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1761 }
1762
1763 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1764
1765 wfProfileOut( __METHOD__ );
1766 return $blocked;
1767 }
1768
1769 /**
1770 * If user is blocked, return the name of the user who placed the block
1771 * @return string Name of blocker
1772 */
1773 public function blockedBy() {
1774 $this->getBlockedStatus();
1775 return $this->mBlockedby;
1776 }
1777
1778 /**
1779 * If user is blocked, return the specified reason for the block
1780 * @return string Blocking reason
1781 */
1782 public function blockedFor() {
1783 $this->getBlockedStatus();
1784 return $this->mBlockreason;
1785 }
1786
1787 /**
1788 * If user is blocked, return the ID for the block
1789 * @return int Block ID
1790 */
1791 public function getBlockId() {
1792 $this->getBlockedStatus();
1793 return ( $this->mBlock ? $this->mBlock->getId() : false );
1794 }
1795
1796 /**
1797 * Check if user is blocked on all wikis.
1798 * Do not use for actual edit permission checks!
1799 * This is intended for quick UI checks.
1800 *
1801 * @param string $ip IP address, uses current client if none given
1802 * @return bool True if blocked, false otherwise
1803 */
1804 public function isBlockedGlobally( $ip = '' ) {
1805 if ( $this->mBlockedGlobally !== null ) {
1806 return $this->mBlockedGlobally;
1807 }
1808 // User is already an IP?
1809 if ( IP::isIPAddress( $this->getName() ) ) {
1810 $ip = $this->getName();
1811 } elseif ( !$ip ) {
1812 $ip = $this->getRequest()->getIP();
1813 }
1814 $blocked = false;
1815 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1816 $this->mBlockedGlobally = (bool)$blocked;
1817 return $this->mBlockedGlobally;
1818 }
1819
1820 /**
1821 * Check if user account is locked
1822 *
1823 * @return bool True if locked, false otherwise
1824 */
1825 public function isLocked() {
1826 if ( $this->mLocked !== null ) {
1827 return $this->mLocked;
1828 }
1829 global $wgAuth;
1830 StubObject::unstub( $wgAuth );
1831 $authUser = $wgAuth->getUserInstance( $this );
1832 $this->mLocked = (bool)$authUser->isLocked();
1833 return $this->mLocked;
1834 }
1835
1836 /**
1837 * Check if user account is hidden
1838 *
1839 * @return bool True if hidden, false otherwise
1840 */
1841 public function isHidden() {
1842 if ( $this->mHideName !== null ) {
1843 return $this->mHideName;
1844 }
1845 $this->getBlockedStatus();
1846 if ( !$this->mHideName ) {
1847 global $wgAuth;
1848 StubObject::unstub( $wgAuth );
1849 $authUser = $wgAuth->getUserInstance( $this );
1850 $this->mHideName = (bool)$authUser->isHidden();
1851 }
1852 return $this->mHideName;
1853 }
1854
1855 /**
1856 * Get the user's ID.
1857 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1858 */
1859 public function getId() {
1860 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1861 // Special case, we know the user is anonymous
1862 return 0;
1863 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1864 // Don't load if this was initialized from an ID
1865 $this->load();
1866 }
1867 return $this->mId;
1868 }
1869
1870 /**
1871 * Set the user and reload all fields according to a given ID
1872 * @param int $v User ID to reload
1873 */
1874 public function setId( $v ) {
1875 $this->mId = $v;
1876 $this->clearInstanceCache( 'id' );
1877 }
1878
1879 /**
1880 * Get the user name, or the IP of an anonymous user
1881 * @return string User's name or IP address
1882 */
1883 public function getName() {
1884 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1885 // Special case optimisation
1886 return $this->mName;
1887 } else {
1888 $this->load();
1889 if ( $this->mName === false ) {
1890 // Clean up IPs
1891 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1892 }
1893 return $this->mName;
1894 }
1895 }
1896
1897 /**
1898 * Set the user name.
1899 *
1900 * This does not reload fields from the database according to the given
1901 * name. Rather, it is used to create a temporary "nonexistent user" for
1902 * later addition to the database. It can also be used to set the IP
1903 * address for an anonymous user to something other than the current
1904 * remote IP.
1905 *
1906 * @note User::newFromName() has roughly the same function, when the named user
1907 * does not exist.
1908 * @param string $str New user name to set
1909 */
1910 public function setName( $str ) {
1911 $this->load();
1912 $this->mName = $str;
1913 }
1914
1915 /**
1916 * Get the user's name escaped by underscores.
1917 * @return string Username escaped by underscores.
1918 */
1919 public function getTitleKey() {
1920 return str_replace( ' ', '_', $this->getName() );
1921 }
1922
1923 /**
1924 * Check if the user has new messages.
1925 * @return bool True if the user has new messages
1926 */
1927 public function getNewtalk() {
1928 $this->load();
1929
1930 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1931 if ( $this->mNewtalk === -1 ) {
1932 $this->mNewtalk = false; # reset talk page status
1933
1934 // Check memcached separately for anons, who have no
1935 // entire User object stored in there.
1936 if ( !$this->mId ) {
1937 global $wgDisableAnonTalk;
1938 if ( $wgDisableAnonTalk ) {
1939 // Anon newtalk disabled by configuration.
1940 $this->mNewtalk = false;
1941 } else {
1942 global $wgMemc;
1943 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1944 $newtalk = $wgMemc->get( $key );
1945 if ( strval( $newtalk ) !== '' ) {
1946 $this->mNewtalk = (bool)$newtalk;
1947 } else {
1948 // Since we are caching this, make sure it is up to date by getting it
1949 // from the master
1950 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1951 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1952 }
1953 }
1954 } else {
1955 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1956 }
1957 }
1958
1959 return (bool)$this->mNewtalk;
1960 }
1961
1962 /**
1963 * Return the data needed to construct links for new talk page message
1964 * alerts. If there are new messages, this will return an associative array
1965 * with the following data:
1966 * wiki: The database name of the wiki
1967 * link: Root-relative link to the user's talk page
1968 * rev: The last talk page revision that the user has seen or null. This
1969 * is useful for building diff links.
1970 * If there are no new messages, it returns an empty array.
1971 * @note This function was designed to accomodate multiple talk pages, but
1972 * currently only returns a single link and revision.
1973 * @return array
1974 */
1975 public function getNewMessageLinks() {
1976 $talks = array();
1977 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1978 return $talks;
1979 } elseif ( !$this->getNewtalk() ) {
1980 return array();
1981 }
1982 $utp = $this->getTalkPage();
1983 $dbr = wfGetDB( DB_SLAVE );
1984 // Get the "last viewed rev" timestamp from the oldest message notification
1985 $timestamp = $dbr->selectField( 'user_newtalk',
1986 'MIN(user_last_timestamp)',
1987 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1988 __METHOD__ );
1989 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1990 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1991 }
1992
1993 /**
1994 * Get the revision ID for the last talk page revision viewed by the talk
1995 * page owner.
1996 * @return int|null Revision ID or null
1997 */
1998 public function getNewMessageRevisionId() {
1999 $newMessageRevisionId = null;
2000 $newMessageLinks = $this->getNewMessageLinks();
2001 if ( $newMessageLinks ) {
2002 // Note: getNewMessageLinks() never returns more than a single link
2003 // and it is always for the same wiki, but we double-check here in
2004 // case that changes some time in the future.
2005 if ( count( $newMessageLinks ) === 1
2006 && $newMessageLinks[0]['wiki'] === wfWikiID()
2007 && $newMessageLinks[0]['rev']
2008 ) {
2009 $newMessageRevision = $newMessageLinks[0]['rev'];
2010 $newMessageRevisionId = $newMessageRevision->getId();
2011 }
2012 }
2013 return $newMessageRevisionId;
2014 }
2015
2016 /**
2017 * Internal uncached check for new messages
2018 *
2019 * @see getNewtalk()
2020 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2021 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2022 * @param bool $fromMaster true to fetch from the master, false for a slave
2023 * @return bool True if the user has new messages
2024 */
2025 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2026 if ( $fromMaster ) {
2027 $db = wfGetDB( DB_MASTER );
2028 } else {
2029 $db = wfGetDB( DB_SLAVE );
2030 }
2031 $ok = $db->selectField( 'user_newtalk', $field,
2032 array( $field => $id ), __METHOD__ );
2033 return $ok !== false;
2034 }
2035
2036 /**
2037 * Add or update the new messages flag
2038 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2039 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2040 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2041 * @return bool True if successful, false otherwise
2042 */
2043 protected function updateNewtalk( $field, $id, $curRev = null ) {
2044 // Get timestamp of the talk page revision prior to the current one
2045 $prevRev = $curRev ? $curRev->getPrevious() : false;
2046 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2047 // Mark the user as having new messages since this revision
2048 $dbw = wfGetDB( DB_MASTER );
2049 $dbw->insert( 'user_newtalk',
2050 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2051 __METHOD__,
2052 'IGNORE' );
2053 if ( $dbw->affectedRows() ) {
2054 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2055 return true;
2056 } else {
2057 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2058 return false;
2059 }
2060 }
2061
2062 /**
2063 * Clear the new messages flag for the given user
2064 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2065 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2066 * @return bool True if successful, false otherwise
2067 */
2068 protected function deleteNewtalk( $field, $id ) {
2069 $dbw = wfGetDB( DB_MASTER );
2070 $dbw->delete( 'user_newtalk',
2071 array( $field => $id ),
2072 __METHOD__ );
2073 if ( $dbw->affectedRows() ) {
2074 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2075 return true;
2076 } else {
2077 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2078 return false;
2079 }
2080 }
2081
2082 /**
2083 * Update the 'You have new messages!' status.
2084 * @param bool $val Whether the user has new messages
2085 * @param Revision $curRev New, as yet unseen revision of the user talk page. Ignored if null or !$val.
2086 */
2087 public function setNewtalk( $val, $curRev = null ) {
2088 if ( wfReadOnly() ) {
2089 return;
2090 }
2091
2092 $this->load();
2093 $this->mNewtalk = $val;
2094
2095 if ( $this->isAnon() ) {
2096 $field = 'user_ip';
2097 $id = $this->getName();
2098 } else {
2099 $field = 'user_id';
2100 $id = $this->getId();
2101 }
2102 global $wgMemc;
2103
2104 if ( $val ) {
2105 $changed = $this->updateNewtalk( $field, $id, $curRev );
2106 } else {
2107 $changed = $this->deleteNewtalk( $field, $id );
2108 }
2109
2110 if ( $this->isAnon() ) {
2111 // Anons have a separate memcached space, since
2112 // user records aren't kept for them.
2113 $key = wfMemcKey( 'newtalk', 'ip', $id );
2114 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2115 }
2116 if ( $changed ) {
2117 $this->invalidateCache();
2118 }
2119 }
2120
2121 /**
2122 * Generate a current or new-future timestamp to be stored in the
2123 * user_touched field when we update things.
2124 * @return string Timestamp in TS_MW format
2125 */
2126 private static function newTouchedTimestamp() {
2127 global $wgClockSkewFudge;
2128 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2129 }
2130
2131 /**
2132 * Clear user data from memcached.
2133 * Use after applying fun updates to the database; caller's
2134 * responsibility to update user_touched if appropriate.
2135 *
2136 * Called implicitly from invalidateCache() and saveSettings().
2137 */
2138 private function clearSharedCache() {
2139 $this->load();
2140 if ( $this->mId ) {
2141 global $wgMemc;
2142 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2143 }
2144 }
2145
2146 /**
2147 * Immediately touch the user data cache for this account.
2148 * Updates user_touched field, and removes account data from memcached
2149 * for reload on the next hit.
2150 */
2151 public function invalidateCache() {
2152 if ( wfReadOnly() ) {
2153 return;
2154 }
2155 $this->load();
2156 if ( $this->mId ) {
2157 $this->mTouched = self::newTouchedTimestamp();
2158
2159 $dbw = wfGetDB( DB_MASTER );
2160 $userid = $this->mId;
2161 $touched = $this->mTouched;
2162 $method = __METHOD__;
2163 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2164 // Prevent contention slams by checking user_touched first
2165 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2166 $needsPurge = $dbw->selectField( 'user', '1',
2167 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2168 if ( $needsPurge ) {
2169 $dbw->update( 'user',
2170 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2171 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2172 $method
2173 );
2174 }
2175 } );
2176 $this->clearSharedCache();
2177 }
2178 }
2179
2180 /**
2181 * Validate the cache for this account.
2182 * @param string $timestamp A timestamp in TS_MW format
2183 * @return bool
2184 */
2185 public function validateCache( $timestamp ) {
2186 $this->load();
2187 return ( $timestamp >= $this->mTouched );
2188 }
2189
2190 /**
2191 * Get the user touched timestamp
2192 * @return string Timestamp
2193 */
2194 public function getTouched() {
2195 $this->load();
2196 return $this->mTouched;
2197 }
2198
2199 /**
2200 * Set the password and reset the random token.
2201 * Calls through to authentication plugin if necessary;
2202 * will have no effect if the auth plugin refuses to
2203 * pass the change through or if the legal password
2204 * checks fail.
2205 *
2206 * As a special case, setting the password to null
2207 * wipes it, so the account cannot be logged in until
2208 * a new password is set, for instance via e-mail.
2209 *
2210 * @param string $str New password to set
2211 * @throws PasswordError on failure
2212 *
2213 * @return bool
2214 */
2215 public function setPassword( $str ) {
2216 global $wgAuth;
2217
2218 if ( $str !== null ) {
2219 if ( !$wgAuth->allowPasswordChange() ) {
2220 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2221 }
2222
2223 if ( !$this->isValidPassword( $str ) ) {
2224 global $wgMinimalPasswordLength;
2225 $valid = $this->getPasswordValidity( $str );
2226 if ( is_array( $valid ) ) {
2227 $message = array_shift( $valid );
2228 $params = $valid;
2229 } else {
2230 $message = $valid;
2231 $params = array( $wgMinimalPasswordLength );
2232 }
2233 throw new PasswordError( wfMessage( $message, $params )->text() );
2234 }
2235 }
2236
2237 if ( !$wgAuth->setPassword( $this, $str ) ) {
2238 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2239 }
2240
2241 $this->setInternalPassword( $str );
2242
2243 return true;
2244 }
2245
2246 /**
2247 * Set the password and reset the random token unconditionally.
2248 *
2249 * @param string|null $str New password to set or null to set an invalid
2250 * password hash meaning that the user will not be able to log in
2251 * through the web interface.
2252 */
2253 public function setInternalPassword( $str ) {
2254 $this->load();
2255 $this->setToken();
2256
2257 if ( $str === null ) {
2258 // Save an invalid hash...
2259 $this->mPassword = '';
2260 } else {
2261 $this->mPassword = self::crypt( $str );
2262 }
2263 $this->mNewpassword = '';
2264 $this->mNewpassTime = null;
2265 }
2266
2267 /**
2268 * Get the user's current token.
2269 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2270 * @return string Token
2271 */
2272 public function getToken( $forceCreation = true ) {
2273 $this->load();
2274 if ( !$this->mToken && $forceCreation ) {
2275 $this->setToken();
2276 }
2277 return $this->mToken;
2278 }
2279
2280 /**
2281 * Set the random token (used for persistent authentication)
2282 * Called from loadDefaults() among other places.
2283 *
2284 * @param string|bool $token If specified, set the token to this value
2285 */
2286 public function setToken( $token = false ) {
2287 $this->load();
2288 if ( !$token ) {
2289 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2290 } else {
2291 $this->mToken = $token;
2292 }
2293 }
2294
2295 /**
2296 * Set the password for a password reminder or new account email
2297 *
2298 * @param string $str New password to set or null to set an invalid
2299 * password hash meaning that the user will not be able to use it
2300 * @param bool $throttle If true, reset the throttle timestamp to the present
2301 */
2302 public function setNewpassword( $str, $throttle = true ) {
2303 $this->load();
2304
2305 if ( $str === null ) {
2306 $this->mNewpassword = '';
2307 $this->mNewpassTime = null;
2308 } else {
2309 $this->mNewpassword = self::crypt( $str );
2310 if ( $throttle ) {
2311 $this->mNewpassTime = wfTimestampNow();
2312 }
2313 }
2314 }
2315
2316 /**
2317 * Has password reminder email been sent within the last
2318 * $wgPasswordReminderResendTime hours?
2319 * @return bool
2320 */
2321 public function isPasswordReminderThrottled() {
2322 global $wgPasswordReminderResendTime;
2323 $this->load();
2324 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2325 return false;
2326 }
2327 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2328 return time() < $expiry;
2329 }
2330
2331 /**
2332 * Get the user's e-mail address
2333 * @return string User's email address
2334 */
2335 public function getEmail() {
2336 $this->load();
2337 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2338 return $this->mEmail;
2339 }
2340
2341 /**
2342 * Get the timestamp of the user's e-mail authentication
2343 * @return string TS_MW timestamp
2344 */
2345 public function getEmailAuthenticationTimestamp() {
2346 $this->load();
2347 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2348 return $this->mEmailAuthenticated;
2349 }
2350
2351 /**
2352 * Set the user's e-mail address
2353 * @param string $str New e-mail address
2354 */
2355 public function setEmail( $str ) {
2356 $this->load();
2357 if ( $str == $this->mEmail ) {
2358 return;
2359 }
2360 $this->mEmail = $str;
2361 $this->invalidateEmail();
2362 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2363 }
2364
2365 /**
2366 * Set the user's e-mail address and a confirmation mail if needed.
2367 *
2368 * @since 1.20
2369 * @param string $str New e-mail address
2370 * @return Status
2371 */
2372 public function setEmailWithConfirmation( $str ) {
2373 global $wgEnableEmail, $wgEmailAuthentication;
2374
2375 if ( !$wgEnableEmail ) {
2376 return Status::newFatal( 'emaildisabled' );
2377 }
2378
2379 $oldaddr = $this->getEmail();
2380 if ( $str === $oldaddr ) {
2381 return Status::newGood( true );
2382 }
2383
2384 $this->setEmail( $str );
2385
2386 if ( $str !== '' && $wgEmailAuthentication ) {
2387 // Send a confirmation request to the new address if needed
2388 $type = $oldaddr != '' ? 'changed' : 'set';
2389 $result = $this->sendConfirmationMail( $type );
2390 if ( $result->isGood() ) {
2391 // Say the the caller that a confirmation mail has been sent
2392 $result->value = 'eauth';
2393 }
2394 } else {
2395 $result = Status::newGood( true );
2396 }
2397
2398 return $result;
2399 }
2400
2401 /**
2402 * Get the user's real name
2403 * @return string User's real name
2404 */
2405 public function getRealName() {
2406 if ( !$this->isItemLoaded( 'realname' ) ) {
2407 $this->load();
2408 }
2409
2410 return $this->mRealName;
2411 }
2412
2413 /**
2414 * Set the user's real name
2415 * @param string $str New real name
2416 */
2417 public function setRealName( $str ) {
2418 $this->load();
2419 $this->mRealName = $str;
2420 }
2421
2422 /**
2423 * Get the user's current setting for a given option.
2424 *
2425 * @param string $oname The option to check
2426 * @param string $defaultOverride A default value returned if the option does not exist
2427 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2428 * @return string User's current value for the option
2429 * @see getBoolOption()
2430 * @see getIntOption()
2431 */
2432 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2433 global $wgHiddenPrefs;
2434 $this->loadOptions();
2435
2436 # We want 'disabled' preferences to always behave as the default value for
2437 # users, even if they have set the option explicitly in their settings (ie they
2438 # set it, and then it was disabled removing their ability to change it). But
2439 # we don't want to erase the preferences in the database in case the preference
2440 # is re-enabled again. So don't touch $mOptions, just override the returned value
2441 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2442 return self::getDefaultOption( $oname );
2443 }
2444
2445 if ( array_key_exists( $oname, $this->mOptions ) ) {
2446 return $this->mOptions[$oname];
2447 } else {
2448 return $defaultOverride;
2449 }
2450 }
2451
2452 /**
2453 * Get all user's options
2454 *
2455 * @return array
2456 */
2457 public function getOptions() {
2458 global $wgHiddenPrefs;
2459 $this->loadOptions();
2460 $options = $this->mOptions;
2461
2462 # We want 'disabled' preferences to always behave as the default value for
2463 # users, even if they have set the option explicitly in their settings (ie they
2464 # set it, and then it was disabled removing their ability to change it). But
2465 # we don't want to erase the preferences in the database in case the preference
2466 # is re-enabled again. So don't touch $mOptions, just override the returned value
2467 foreach ( $wgHiddenPrefs as $pref ) {
2468 $default = self::getDefaultOption( $pref );
2469 if ( $default !== null ) {
2470 $options[$pref] = $default;
2471 }
2472 }
2473
2474 return $options;
2475 }
2476
2477 /**
2478 * Get the user's current setting for a given option, as a boolean value.
2479 *
2480 * @param string $oname The option to check
2481 * @return bool User's current value for the option
2482 * @see getOption()
2483 */
2484 public function getBoolOption( $oname ) {
2485 return (bool)$this->getOption( $oname );
2486 }
2487
2488 /**
2489 * Get the user's current setting for a given option, as an integer value.
2490 *
2491 * @param string $oname The option to check
2492 * @param int $defaultOverride A default value returned if the option does not exist
2493 * @return int User's current value for the option
2494 * @see getOption()
2495 */
2496 public function getIntOption( $oname, $defaultOverride = 0 ) {
2497 $val = $this->getOption( $oname );
2498 if ( $val == '' ) {
2499 $val = $defaultOverride;
2500 }
2501 return intval( $val );
2502 }
2503
2504 /**
2505 * Set the given option for a user.
2506 *
2507 * @param string $oname The option to set
2508 * @param mixed $val New value to set
2509 */
2510 public function setOption( $oname, $val ) {
2511 $this->loadOptions();
2512
2513 // Explicitly NULL values should refer to defaults
2514 if ( is_null( $val ) ) {
2515 $val = self::getDefaultOption( $oname );
2516 }
2517
2518 $this->mOptions[$oname] = $val;
2519 }
2520
2521 /**
2522 * Get a token stored in the preferences (like the watchlist one),
2523 * resetting it if it's empty (and saving changes).
2524 *
2525 * @param string $oname The option name to retrieve the token from
2526 * @return string|bool User's current value for the option, or false if this option is disabled.
2527 * @see resetTokenFromOption()
2528 * @see getOption()
2529 */
2530 public function getTokenFromOption( $oname ) {
2531 global $wgHiddenPrefs;
2532 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2533 return false;
2534 }
2535
2536 $token = $this->getOption( $oname );
2537 if ( !$token ) {
2538 $token = $this->resetTokenFromOption( $oname );
2539 $this->saveSettings();
2540 }
2541 return $token;
2542 }
2543
2544 /**
2545 * Reset a token stored in the preferences (like the watchlist one).
2546 * *Does not* save user's preferences (similarly to setOption()).
2547 *
2548 * @param string $oname The option name to reset the token in
2549 * @return string|bool New token value, or false if this option is disabled.
2550 * @see getTokenFromOption()
2551 * @see setOption()
2552 */
2553 public function resetTokenFromOption( $oname ) {
2554 global $wgHiddenPrefs;
2555 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2556 return false;
2557 }
2558
2559 $token = MWCryptRand::generateHex( 40 );
2560 $this->setOption( $oname, $token );
2561 return $token;
2562 }
2563
2564 /**
2565 * Return a list of the types of user options currently returned by
2566 * User::getOptionKinds().
2567 *
2568 * Currently, the option kinds are:
2569 * - 'registered' - preferences which are registered in core MediaWiki or
2570 * by extensions using the UserGetDefaultOptions hook.
2571 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2572 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2573 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2574 * be used by user scripts.
2575 * - 'special' - "preferences" that are not accessible via User::getOptions
2576 * or User::setOptions.
2577 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2578 * These are usually legacy options, removed in newer versions.
2579 *
2580 * The API (and possibly others) use this function to determine the possible
2581 * option types for validation purposes, so make sure to update this when a
2582 * new option kind is added.
2583 *
2584 * @see User::getOptionKinds
2585 * @return array Option kinds
2586 */
2587 public static function listOptionKinds() {
2588 return array(
2589 'registered',
2590 'registered-multiselect',
2591 'registered-checkmatrix',
2592 'userjs',
2593 'special',
2594 'unused'
2595 );
2596 }
2597
2598 /**
2599 * Return an associative array mapping preferences keys to the kind of a preference they're
2600 * used for. Different kinds are handled differently when setting or reading preferences.
2601 *
2602 * See User::listOptionKinds for the list of valid option types that can be provided.
2603 *
2604 * @see User::listOptionKinds
2605 * @param IContextSource $context
2606 * @param array $options Assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2607 * @return array the key => kind mapping data
2608 */
2609 public function getOptionKinds( IContextSource $context, $options = null ) {
2610 $this->loadOptions();
2611 if ( $options === null ) {
2612 $options = $this->mOptions;
2613 }
2614
2615 $prefs = Preferences::getPreferences( $this, $context );
2616 $mapping = array();
2617
2618 // Pull out the "special" options, so they don't get converted as
2619 // multiselect or checkmatrix.
2620 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2621 foreach ( $specialOptions as $name => $value ) {
2622 unset( $prefs[$name] );
2623 }
2624
2625 // Multiselect and checkmatrix options are stored in the database with
2626 // one key per option, each having a boolean value. Extract those keys.
2627 $multiselectOptions = array();
2628 foreach ( $prefs as $name => $info ) {
2629 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2630 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2631 $opts = HTMLFormField::flattenOptions( $info['options'] );
2632 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2633
2634 foreach ( $opts as $value ) {
2635 $multiselectOptions["$prefix$value"] = true;
2636 }
2637
2638 unset( $prefs[$name] );
2639 }
2640 }
2641 $checkmatrixOptions = array();
2642 foreach ( $prefs as $name => $info ) {
2643 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2644 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2645 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2646 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2647 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2648
2649 foreach ( $columns as $column ) {
2650 foreach ( $rows as $row ) {
2651 $checkmatrixOptions["$prefix-$column-$row"] = true;
2652 }
2653 }
2654
2655 unset( $prefs[$name] );
2656 }
2657 }
2658
2659 // $value is ignored
2660 foreach ( $options as $key => $value ) {
2661 if ( isset( $prefs[$key] ) ) {
2662 $mapping[$key] = 'registered';
2663 } elseif ( isset( $multiselectOptions[$key] ) ) {
2664 $mapping[$key] = 'registered-multiselect';
2665 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2666 $mapping[$key] = 'registered-checkmatrix';
2667 } elseif ( isset( $specialOptions[$key] ) ) {
2668 $mapping[$key] = 'special';
2669 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2670 $mapping[$key] = 'userjs';
2671 } else {
2672 $mapping[$key] = 'unused';
2673 }
2674 }
2675
2676 return $mapping;
2677 }
2678
2679 /**
2680 * Reset certain (or all) options to the site defaults
2681 *
2682 * The optional parameter determines which kinds of preferences will be reset.
2683 * Supported values are everything that can be reported by getOptionKinds()
2684 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2685 *
2686 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2687 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2688 * for backwards-compatibility.
2689 * @param IContextSource|null $context Context source used when $resetKinds
2690 * does not contain 'all', passed to getOptionKinds().
2691 * Defaults to RequestContext::getMain() when null.
2692 */
2693 public function resetOptions(
2694 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2695 IContextSource $context = null
2696 ) {
2697 $this->load();
2698 $defaultOptions = self::getDefaultOptions();
2699
2700 if ( !is_array( $resetKinds ) ) {
2701 $resetKinds = array( $resetKinds );
2702 }
2703
2704 if ( in_array( 'all', $resetKinds ) ) {
2705 $newOptions = $defaultOptions;
2706 } else {
2707 if ( $context === null ) {
2708 $context = RequestContext::getMain();
2709 }
2710
2711 $optionKinds = $this->getOptionKinds( $context );
2712 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2713 $newOptions = array();
2714
2715 // Use default values for the options that should be deleted, and
2716 // copy old values for the ones that shouldn't.
2717 foreach ( $this->mOptions as $key => $value ) {
2718 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2719 if ( array_key_exists( $key, $defaultOptions ) ) {
2720 $newOptions[$key] = $defaultOptions[$key];
2721 }
2722 } else {
2723 $newOptions[$key] = $value;
2724 }
2725 }
2726 }
2727
2728 $this->mOptions = $newOptions;
2729 $this->mOptionsLoaded = true;
2730 }
2731
2732 /**
2733 * Get the user's preferred date format.
2734 * @return string User's preferred date format
2735 */
2736 public function getDatePreference() {
2737 // Important migration for old data rows
2738 if ( is_null( $this->mDatePreference ) ) {
2739 global $wgLang;
2740 $value = $this->getOption( 'date' );
2741 $map = $wgLang->getDatePreferenceMigrationMap();
2742 if ( isset( $map[$value] ) ) {
2743 $value = $map[$value];
2744 }
2745 $this->mDatePreference = $value;
2746 }
2747 return $this->mDatePreference;
2748 }
2749
2750 /**
2751 * Determine based on the wiki configuration and the user's options,
2752 * whether this user must be over HTTPS no matter what.
2753 *
2754 * @return bool
2755 */
2756 public function requiresHTTPS() {
2757 global $wgSecureLogin;
2758 if ( !$wgSecureLogin ) {
2759 return false;
2760 } else {
2761 $https = $this->getBoolOption( 'prefershttps' );
2762 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2763 if ( $https ) {
2764 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2765 }
2766 return $https;
2767 }
2768 }
2769
2770 /**
2771 * Get the user preferred stub threshold
2772 *
2773 * @return int
2774 */
2775 public function getStubThreshold() {
2776 global $wgMaxArticleSize; # Maximum article size, in Kb
2777 $threshold = $this->getIntOption( 'stubthreshold' );
2778 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2779 // If they have set an impossible value, disable the preference
2780 // so we can use the parser cache again.
2781 $threshold = 0;
2782 }
2783 return $threshold;
2784 }
2785
2786 /**
2787 * Get the permissions this user has.
2788 * @return array Array of String permission names
2789 */
2790 public function getRights() {
2791 if ( is_null( $this->mRights ) ) {
2792 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2793 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2794 // Force reindexation of rights when a hook has unset one of them
2795 $this->mRights = array_values( array_unique( $this->mRights ) );
2796 }
2797 return $this->mRights;
2798 }
2799
2800 /**
2801 * Get the list of explicit group memberships this user has.
2802 * The implicit * and user groups are not included.
2803 * @return array Array of String internal group names
2804 */
2805 public function getGroups() {
2806 $this->load();
2807 $this->loadGroups();
2808 return $this->mGroups;
2809 }
2810
2811 /**
2812 * Get the list of implicit group memberships this user has.
2813 * This includes all explicit groups, plus 'user' if logged in,
2814 * '*' for all accounts, and autopromoted groups
2815 * @param bool $recache Whether to avoid the cache
2816 * @return array Array of String internal group names
2817 */
2818 public function getEffectiveGroups( $recache = false ) {
2819 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2820 wfProfileIn( __METHOD__ );
2821 $this->mEffectiveGroups = array_unique( array_merge(
2822 $this->getGroups(), // explicit groups
2823 $this->getAutomaticGroups( $recache ) // implicit groups
2824 ) );
2825 // Hook for additional groups
2826 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2827 // Force reindexation of groups when a hook has unset one of them
2828 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2829 wfProfileOut( __METHOD__ );
2830 }
2831 return $this->mEffectiveGroups;
2832 }
2833
2834 /**
2835 * Get the list of implicit group memberships this user has.
2836 * This includes 'user' if logged in, '*' for all accounts,
2837 * and autopromoted groups
2838 * @param bool $recache Whether to avoid the cache
2839 * @return array Array of String internal group names
2840 */
2841 public function getAutomaticGroups( $recache = false ) {
2842 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2843 wfProfileIn( __METHOD__ );
2844 $this->mImplicitGroups = array( '*' );
2845 if ( $this->getId() ) {
2846 $this->mImplicitGroups[] = 'user';
2847
2848 $this->mImplicitGroups = array_unique( array_merge(
2849 $this->mImplicitGroups,
2850 Autopromote::getAutopromoteGroups( $this )
2851 ) );
2852 }
2853 if ( $recache ) {
2854 // Assure data consistency with rights/groups,
2855 // as getEffectiveGroups() depends on this function
2856 $this->mEffectiveGroups = null;
2857 }
2858 wfProfileOut( __METHOD__ );
2859 }
2860 return $this->mImplicitGroups;
2861 }
2862
2863 /**
2864 * Returns the groups the user has belonged to.
2865 *
2866 * The user may still belong to the returned groups. Compare with getGroups().
2867 *
2868 * The function will not return groups the user had belonged to before MW 1.17
2869 *
2870 * @return array Names of the groups the user has belonged to.
2871 */
2872 public function getFormerGroups() {
2873 if ( is_null( $this->mFormerGroups ) ) {
2874 $dbr = wfGetDB( DB_MASTER );
2875 $res = $dbr->select( 'user_former_groups',
2876 array( 'ufg_group' ),
2877 array( 'ufg_user' => $this->mId ),
2878 __METHOD__ );
2879 $this->mFormerGroups = array();
2880 foreach ( $res as $row ) {
2881 $this->mFormerGroups[] = $row->ufg_group;
2882 }
2883 }
2884 return $this->mFormerGroups;
2885 }
2886
2887 /**
2888 * Get the user's edit count.
2889 * @return int|null null for anonymous users
2890 */
2891 public function getEditCount() {
2892 if ( !$this->getId() ) {
2893 return null;
2894 }
2895
2896 if ( !isset( $this->mEditCount ) ) {
2897 /* Populate the count, if it has not been populated yet */
2898 wfProfileIn( __METHOD__ );
2899 $dbr = wfGetDB( DB_SLAVE );
2900 // check if the user_editcount field has been initialized
2901 $count = $dbr->selectField(
2902 'user', 'user_editcount',
2903 array( 'user_id' => $this->mId ),
2904 __METHOD__
2905 );
2906
2907 if ( $count === null ) {
2908 // it has not been initialized. do so.
2909 $count = $this->initEditCount();
2910 }
2911 $this->mEditCount = $count;
2912 wfProfileOut( __METHOD__ );
2913 }
2914 return (int)$this->mEditCount;
2915 }
2916
2917 /**
2918 * Add the user to the given group.
2919 * This takes immediate effect.
2920 * @param string $group Name of the group to add
2921 */
2922 public function addGroup( $group ) {
2923 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2924 $dbw = wfGetDB( DB_MASTER );
2925 if ( $this->getId() ) {
2926 $dbw->insert( 'user_groups',
2927 array(
2928 'ug_user' => $this->getID(),
2929 'ug_group' => $group,
2930 ),
2931 __METHOD__,
2932 array( 'IGNORE' ) );
2933 }
2934 }
2935 $this->loadGroups();
2936 $this->mGroups[] = $group;
2937 // In case loadGroups was not called before, we now have the right twice.
2938 // Get rid of the duplicate.
2939 $this->mGroups = array_unique( $this->mGroups );
2940
2941 // Refresh the groups caches, and clear the rights cache so it will be
2942 // refreshed on the next call to $this->getRights().
2943 $this->getEffectiveGroups( true );
2944 $this->mRights = null;
2945
2946 $this->invalidateCache();
2947 }
2948
2949 /**
2950 * Remove the user from the given group.
2951 * This takes immediate effect.
2952 * @param string $group Name of the group to remove
2953 */
2954 public function removeGroup( $group ) {
2955 $this->load();
2956 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2957 $dbw = wfGetDB( DB_MASTER );
2958 $dbw->delete( 'user_groups',
2959 array(
2960 'ug_user' => $this->getID(),
2961 'ug_group' => $group,
2962 ), __METHOD__ );
2963 // Remember that the user was in this group
2964 $dbw->insert( 'user_former_groups',
2965 array(
2966 'ufg_user' => $this->getID(),
2967 'ufg_group' => $group,
2968 ),
2969 __METHOD__,
2970 array( 'IGNORE' ) );
2971 }
2972 $this->loadGroups();
2973 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2974
2975 // Refresh the groups caches, and clear the rights cache so it will be
2976 // refreshed on the next call to $this->getRights().
2977 $this->getEffectiveGroups( true );
2978 $this->mRights = null;
2979
2980 $this->invalidateCache();
2981 }
2982
2983 /**
2984 * Get whether the user is logged in
2985 * @return bool
2986 */
2987 public function isLoggedIn() {
2988 return $this->getID() != 0;
2989 }
2990
2991 /**
2992 * Get whether the user is anonymous
2993 * @return bool
2994 */
2995 public function isAnon() {
2996 return !$this->isLoggedIn();
2997 }
2998
2999 /**
3000 * Check if user is allowed to access a feature / make an action
3001 *
3002 * @internal param \String $varargs permissions to test
3003 * @return bool True if user is allowed to perform *any* of the given actions
3004 *
3005 * @return bool
3006 */
3007 public function isAllowedAny( /*...*/ ) {
3008 $permissions = func_get_args();
3009 foreach ( $permissions as $permission ) {
3010 if ( $this->isAllowed( $permission ) ) {
3011 return true;
3012 }
3013 }
3014 return false;
3015 }
3016
3017 /**
3018 *
3019 * @internal param $varargs string
3020 * @return bool True if the user is allowed to perform *all* of the given actions
3021 */
3022 public function isAllowedAll( /*...*/ ) {
3023 $permissions = func_get_args();
3024 foreach ( $permissions as $permission ) {
3025 if ( !$this->isAllowed( $permission ) ) {
3026 return false;
3027 }
3028 }
3029 return true;
3030 }
3031
3032 /**
3033 * Internal mechanics of testing a permission
3034 * @param string $action
3035 * @return bool
3036 */
3037 public function isAllowed( $action = '' ) {
3038 if ( $action === '' ) {
3039 return true; // In the spirit of DWIM
3040 }
3041 // Patrolling may not be enabled
3042 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3043 global $wgUseRCPatrol, $wgUseNPPatrol;
3044 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3045 return false;
3046 }
3047 }
3048 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3049 // by misconfiguration: 0 == 'foo'
3050 return in_array( $action, $this->getRights(), true );
3051 }
3052
3053 /**
3054 * Check whether to enable recent changes patrol features for this user
3055 * @return bool True or false
3056 */
3057 public function useRCPatrol() {
3058 global $wgUseRCPatrol;
3059 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3060 }
3061
3062 /**
3063 * Check whether to enable new pages patrol features for this user
3064 * @return bool True or false
3065 */
3066 public function useNPPatrol() {
3067 global $wgUseRCPatrol, $wgUseNPPatrol;
3068 return (
3069 ( $wgUseRCPatrol || $wgUseNPPatrol )
3070 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3071 );
3072 }
3073
3074 /**
3075 * Get the WebRequest object to use with this object
3076 *
3077 * @return WebRequest
3078 */
3079 public function getRequest() {
3080 if ( $this->mRequest ) {
3081 return $this->mRequest;
3082 } else {
3083 global $wgRequest;
3084 return $wgRequest;
3085 }
3086 }
3087
3088 /**
3089 * Get the current skin, loading it if required
3090 * @return Skin The current skin
3091 * @todo FIXME: Need to check the old failback system [AV]
3092 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3093 */
3094 public function getSkin() {
3095 wfDeprecated( __METHOD__, '1.18' );
3096 return RequestContext::getMain()->getSkin();
3097 }
3098
3099 /**
3100 * Get a WatchedItem for this user and $title.
3101 *
3102 * @since 1.22 $checkRights parameter added
3103 * @param Title $title
3104 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3105 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3106 * @return WatchedItem
3107 */
3108 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3109 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3110
3111 if ( isset( $this->mWatchedItems[$key] ) ) {
3112 return $this->mWatchedItems[$key];
3113 }
3114
3115 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3116 $this->mWatchedItems = array();
3117 }
3118
3119 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3120 return $this->mWatchedItems[$key];
3121 }
3122
3123 /**
3124 * Check the watched status of an article.
3125 * @since 1.22 $checkRights parameter added
3126 * @param Title $title Title of the article to look at
3127 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3128 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3129 * @return bool
3130 */
3131 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3132 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3133 }
3134
3135 /**
3136 * Watch an article.
3137 * @since 1.22 $checkRights parameter added
3138 * @param Title $title Title of the article to look at
3139 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3140 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3141 */
3142 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3143 $this->getWatchedItem( $title, $checkRights )->addWatch();
3144 $this->invalidateCache();
3145 }
3146
3147 /**
3148 * Stop watching an article.
3149 * @since 1.22 $checkRights parameter added
3150 * @param Title $title Title of the article to look at
3151 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3152 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3153 */
3154 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3155 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3156 $this->invalidateCache();
3157 }
3158
3159 /**
3160 * Clear the user's notification timestamp for the given title.
3161 * If e-notif e-mails are on, they will receive notification mails on
3162 * the next change of the page if it's watched etc.
3163 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3164 * @param Title $title Title of the article to look at
3165 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3166 */
3167 public function clearNotification( &$title, $oldid = 0 ) {
3168 global $wgUseEnotif, $wgShowUpdatedMarker;
3169
3170 // Do nothing if the database is locked to writes
3171 if ( wfReadOnly() ) {
3172 return;
3173 }
3174
3175 // Do nothing if not allowed to edit the watchlist
3176 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3177 return;
3178 }
3179
3180 // If we're working on user's talk page, we should update the talk page message indicator
3181 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3182 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3183 return;
3184 }
3185
3186 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3187
3188 if ( !$oldid || !$nextid ) {
3189 // If we're looking at the latest revision, we should definitely clear it
3190 $this->setNewtalk( false );
3191 } else {
3192 // Otherwise we should update its revision, if it's present
3193 if ( $this->getNewtalk() ) {
3194 // Naturally the other one won't clear by itself
3195 $this->setNewtalk( false );
3196 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3197 }
3198 }
3199 }
3200
3201 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3202 return;
3203 }
3204
3205 if ( $this->isAnon() ) {
3206 // Nothing else to do...
3207 return;
3208 }
3209
3210 // Only update the timestamp if the page is being watched.
3211 // The query to find out if it is watched is cached both in memcached and per-invocation,
3212 // and when it does have to be executed, it can be on a slave
3213 // If this is the user's newtalk page, we always update the timestamp
3214 $force = '';
3215 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3216 $force = 'force';
3217 }
3218
3219 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3220 }
3221
3222 /**
3223 * Resets all of the given user's page-change notification timestamps.
3224 * If e-notif e-mails are on, they will receive notification mails on
3225 * the next change of any watched page.
3226 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3227 */
3228 public function clearAllNotifications() {
3229 if ( wfReadOnly() ) {
3230 return;
3231 }
3232
3233 // Do nothing if not allowed to edit the watchlist
3234 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3235 return;
3236 }
3237
3238 global $wgUseEnotif, $wgShowUpdatedMarker;
3239 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3240 $this->setNewtalk( false );
3241 return;
3242 }
3243 $id = $this->getId();
3244 if ( $id != 0 ) {
3245 $dbw = wfGetDB( DB_MASTER );
3246 $dbw->update( 'watchlist',
3247 array( /* SET */ 'wl_notificationtimestamp' => null ),
3248 array( /* WHERE */ 'wl_user' => $id ),
3249 __METHOD__
3250 );
3251 // We also need to clear here the "you have new message" notification for the own user_talk page;
3252 // it's cleared one page view later in WikiPage::doViewUpdates().
3253 }
3254 }
3255
3256 /**
3257 * Set this user's options from an encoded string
3258 * @param string $str Encoded options to import
3259 *
3260 * @deprecated since 1.19 due to removal of user_options from the user table
3261 */
3262 private function decodeOptions( $str ) {
3263 wfDeprecated( __METHOD__, '1.19' );
3264 if ( !$str ) {
3265 return;
3266 }
3267
3268 $this->mOptionsLoaded = true;
3269 $this->mOptionOverrides = array();
3270
3271 // If an option is not set in $str, use the default value
3272 $this->mOptions = self::getDefaultOptions();
3273
3274 $a = explode( "\n", $str );
3275 foreach ( $a as $s ) {
3276 $m = array();
3277 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3278 $this->mOptions[$m[1]] = $m[2];
3279 $this->mOptionOverrides[$m[1]] = $m[2];
3280 }
3281 }
3282 }
3283
3284 /**
3285 * Set a cookie on the user's client. Wrapper for
3286 * WebResponse::setCookie
3287 * @param string $name Name of the cookie to set
3288 * @param string $value Value to set
3289 * @param int $exp Expiration time, as a UNIX time value;
3290 * if 0 or not specified, use the default $wgCookieExpiration
3291 * @param bool $secure
3292 * true: Force setting the secure attribute when setting the cookie
3293 * false: Force NOT setting the secure attribute when setting the cookie
3294 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3295 * @param array $params Array of options sent passed to WebResponse::setcookie()
3296 */
3297 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3298 $params['secure'] = $secure;
3299 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3300 }
3301
3302 /**
3303 * Clear a cookie on the user's client
3304 * @param string $name Name of the cookie to clear
3305 * @param bool $secure
3306 * true: Force setting the secure attribute when setting the cookie
3307 * false: Force NOT setting the secure attribute when setting the cookie
3308 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3309 * @param array $params Array of options sent passed to WebResponse::setcookie()
3310 */
3311 protected function clearCookie( $name, $secure = null, $params = array() ) {
3312 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3313 }
3314
3315 /**
3316 * Set the default cookies for this session on the user's client.
3317 *
3318 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3319 * is passed.
3320 * @param bool $secure Whether to force secure/insecure cookies or use default
3321 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3322 */
3323 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3324 if ( $request === null ) {
3325 $request = $this->getRequest();
3326 }
3327
3328 $this->load();
3329 if ( 0 == $this->mId ) {
3330 return;
3331 }
3332 if ( !$this->mToken ) {
3333 // When token is empty or NULL generate a new one and then save it to the database
3334 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3335 // Simply by setting every cell in the user_token column to NULL and letting them be
3336 // regenerated as users log back into the wiki.
3337 $this->setToken();
3338 $this->saveSettings();
3339 }
3340 $session = array(
3341 'wsUserID' => $this->mId,
3342 'wsToken' => $this->mToken,
3343 'wsUserName' => $this->getName()
3344 );
3345 $cookies = array(
3346 'UserID' => $this->mId,
3347 'UserName' => $this->getName(),
3348 );
3349 if ( $rememberMe ) {
3350 $cookies['Token'] = $this->mToken;
3351 } else {
3352 $cookies['Token'] = false;
3353 }
3354
3355 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3356
3357 foreach ( $session as $name => $value ) {
3358 $request->setSessionData( $name, $value );
3359 }
3360 foreach ( $cookies as $name => $value ) {
3361 if ( $value === false ) {
3362 $this->clearCookie( $name );
3363 } else {
3364 $this->setCookie( $name, $value, 0, $secure );
3365 }
3366 }
3367
3368 /**
3369 * If wpStickHTTPS was selected, also set an insecure cookie that
3370 * will cause the site to redirect the user to HTTPS, if they access
3371 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3372 * as the one set by centralauth (bug 53538). Also set it to session, or
3373 * standard time setting, based on if rememberme was set.
3374 */
3375 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3376 $this->setCookie(
3377 'forceHTTPS',
3378 'true',
3379 $rememberMe ? 0 : null,
3380 false,
3381 array( 'prefix' => '' ) // no prefix
3382 );
3383 }
3384 }
3385
3386 /**
3387 * Log this user out.
3388 */
3389 public function logout() {
3390 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3391 $this->doLogout();
3392 }
3393 }
3394
3395 /**
3396 * Clear the user's cookies and session, and reset the instance cache.
3397 * @see logout()
3398 */
3399 public function doLogout() {
3400 $this->clearInstanceCache( 'defaults' );
3401
3402 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3403
3404 $this->clearCookie( 'UserID' );
3405 $this->clearCookie( 'Token' );
3406 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3407
3408 // Remember when user logged out, to prevent seeing cached pages
3409 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3410 }
3411
3412 /**
3413 * Save this user's settings into the database.
3414 * @todo Only rarely do all these fields need to be set!
3415 */
3416 public function saveSettings() {
3417 global $wgAuth;
3418
3419 $this->load();
3420 if ( wfReadOnly() ) {
3421 return;
3422 }
3423 if ( 0 == $this->mId ) {
3424 return;
3425 }
3426
3427 $this->mTouched = self::newTouchedTimestamp();
3428 if ( !$wgAuth->allowSetLocalPassword() ) {
3429 $this->mPassword = '';
3430 }
3431
3432 $dbw = wfGetDB( DB_MASTER );
3433 $dbw->update( 'user',
3434 array( /* SET */
3435 'user_name' => $this->mName,
3436 'user_password' => $this->mPassword,
3437 'user_newpassword' => $this->mNewpassword,
3438 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3439 'user_real_name' => $this->mRealName,
3440 'user_email' => $this->mEmail,
3441 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3442 'user_touched' => $dbw->timestamp( $this->mTouched ),
3443 'user_token' => strval( $this->mToken ),
3444 'user_email_token' => $this->mEmailToken,
3445 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3446 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3447 ), array( /* WHERE */
3448 'user_id' => $this->mId
3449 ), __METHOD__
3450 );
3451
3452 $this->saveOptions();
3453
3454 wfRunHooks( 'UserSaveSettings', array( $this ) );
3455 $this->clearSharedCache();
3456 $this->getUserPage()->invalidateCache();
3457 }
3458
3459 /**
3460 * If only this user's username is known, and it exists, return the user ID.
3461 * @return int
3462 */
3463 public function idForName() {
3464 $s = trim( $this->getName() );
3465 if ( $s === '' ) {
3466 return 0;
3467 }
3468
3469 $dbr = wfGetDB( DB_SLAVE );
3470 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3471 if ( $id === false ) {
3472 $id = 0;
3473 }
3474 return $id;
3475 }
3476
3477 /**
3478 * Add a user to the database, return the user object
3479 *
3480 * @param string $name Username to add
3481 * @param array $params Array of Strings Non-default parameters to save to the database as user_* fields:
3482 * - password The user's password hash. Password logins will be disabled if this is omitted.
3483 * - newpassword Hash for a temporary password that has been mailed to the user
3484 * - email The user's email address
3485 * - email_authenticated The email authentication timestamp
3486 * - real_name The user's real name
3487 * - options An associative array of non-default options
3488 * - token Random authentication token. Do not set.
3489 * - registration Registration timestamp. Do not set.
3490 *
3491 * @return User|null User object, or null if the username already exists
3492 */
3493 public static function createNew( $name, $params = array() ) {
3494 $user = new User;
3495 $user->load();
3496 $user->setToken(); // init token
3497 if ( isset( $params['options'] ) ) {
3498 $user->mOptions = $params['options'] + (array)$user->mOptions;
3499 unset( $params['options'] );
3500 }
3501 $dbw = wfGetDB( DB_MASTER );
3502 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3503
3504 $fields = array(
3505 'user_id' => $seqVal,
3506 'user_name' => $name,
3507 'user_password' => $user->mPassword,
3508 'user_newpassword' => $user->mNewpassword,
3509 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3510 'user_email' => $user->mEmail,
3511 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3512 'user_real_name' => $user->mRealName,
3513 'user_token' => strval( $user->mToken ),
3514 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3515 'user_editcount' => 0,
3516 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3517 );
3518 foreach ( $params as $name => $value ) {
3519 $fields["user_$name"] = $value;
3520 }
3521 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3522 if ( $dbw->affectedRows() ) {
3523 $newUser = User::newFromId( $dbw->insertId() );
3524 } else {
3525 $newUser = null;
3526 }
3527 return $newUser;
3528 }
3529
3530 /**
3531 * Add this existing user object to the database. If the user already
3532 * exists, a fatal status object is returned, and the user object is
3533 * initialised with the data from the database.
3534 *
3535 * Previously, this function generated a DB error due to a key conflict
3536 * if the user already existed. Many extension callers use this function
3537 * in code along the lines of:
3538 *
3539 * $user = User::newFromName( $name );
3540 * if ( !$user->isLoggedIn() ) {
3541 * $user->addToDatabase();
3542 * }
3543 * // do something with $user...
3544 *
3545 * However, this was vulnerable to a race condition (bug 16020). By
3546 * initialising the user object if the user exists, we aim to support this
3547 * calling sequence as far as possible.
3548 *
3549 * Note that if the user exists, this function will acquire a write lock,
3550 * so it is still advisable to make the call conditional on isLoggedIn(),
3551 * and to commit the transaction after calling.
3552 *
3553 * @throws MWException
3554 * @return Status
3555 */
3556 public function addToDatabase() {
3557 $this->load();
3558 if ( !$this->mToken ) {
3559 $this->setToken(); // init token
3560 }
3561
3562 $this->mTouched = self::newTouchedTimestamp();
3563
3564 $dbw = wfGetDB( DB_MASTER );
3565 $inWrite = $dbw->writesOrCallbacksPending();
3566 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3567 $dbw->insert( 'user',
3568 array(
3569 'user_id' => $seqVal,
3570 'user_name' => $this->mName,
3571 'user_password' => $this->mPassword,
3572 'user_newpassword' => $this->mNewpassword,
3573 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3574 'user_email' => $this->mEmail,
3575 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3576 'user_real_name' => $this->mRealName,
3577 'user_token' => strval( $this->mToken ),
3578 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3579 'user_editcount' => 0,
3580 'user_touched' => $dbw->timestamp( $this->mTouched ),
3581 ), __METHOD__,
3582 array( 'IGNORE' )
3583 );
3584 if ( !$dbw->affectedRows() ) {
3585 if ( !$inWrite ) {
3586 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3587 // Often this case happens early in views before any writes.
3588 // This shows up at least with CentralAuth.
3589 $dbw->commit( __METHOD__, 'flush' );
3590 }
3591 $this->mId = $dbw->selectField( 'user', 'user_id',
3592 array( 'user_name' => $this->mName ), __METHOD__ );
3593 $loaded = false;
3594 if ( $this->mId ) {
3595 if ( $this->loadFromDatabase() ) {
3596 $loaded = true;
3597 }
3598 }
3599 if ( !$loaded ) {
3600 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3601 "to insert user '{$this->mName}' row, but it was not present in select!" );
3602 }
3603 return Status::newFatal( 'userexists' );
3604 }
3605 $this->mId = $dbw->insertId();
3606
3607 // Clear instance cache other than user table data, which is already accurate
3608 $this->clearInstanceCache();
3609
3610 $this->saveOptions();
3611 return Status::newGood();
3612 }
3613
3614 /**
3615 * If this user is logged-in and blocked,
3616 * block any IP address they've successfully logged in from.
3617 * @return bool A block was spread
3618 */
3619 public function spreadAnyEditBlock() {
3620 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3621 return $this->spreadBlock();
3622 }
3623 return false;
3624 }
3625
3626 /**
3627 * If this (non-anonymous) user is blocked,
3628 * block the IP address they've successfully logged in from.
3629 * @return bool A block was spread
3630 */
3631 protected function spreadBlock() {
3632 wfDebug( __METHOD__ . "()\n" );
3633 $this->load();
3634 if ( $this->mId == 0 ) {
3635 return false;
3636 }
3637
3638 $userblock = Block::newFromTarget( $this->getName() );
3639 if ( !$userblock ) {
3640 return false;
3641 }
3642
3643 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3644 }
3645
3646 /**
3647 * Get whether the user is explicitly blocked from account creation.
3648 * @return bool|Block
3649 */
3650 public function isBlockedFromCreateAccount() {
3651 $this->getBlockedStatus();
3652 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3653 return $this->mBlock;
3654 }
3655
3656 # bug 13611: if the IP address the user is trying to create an account from is
3657 # blocked with createaccount disabled, prevent new account creation there even
3658 # when the user is logged in
3659 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3660 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3661 }
3662 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3663 ? $this->mBlockedFromCreateAccount
3664 : false;
3665 }
3666
3667 /**
3668 * Get whether the user is blocked from using Special:Emailuser.
3669 * @return bool
3670 */
3671 public function isBlockedFromEmailuser() {
3672 $this->getBlockedStatus();
3673 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3674 }
3675
3676 /**
3677 * Get whether the user is allowed to create an account.
3678 * @return bool
3679 */
3680 public function isAllowedToCreateAccount() {
3681 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3682 }
3683
3684 /**
3685 * Get this user's personal page title.
3686 *
3687 * @return Title User's personal page title
3688 */
3689 public function getUserPage() {
3690 return Title::makeTitle( NS_USER, $this->getName() );
3691 }
3692
3693 /**
3694 * Get this user's talk page title.
3695 *
3696 * @return Title User's talk page title
3697 */
3698 public function getTalkPage() {
3699 $title = $this->getUserPage();
3700 return $title->getTalkPage();
3701 }
3702
3703 /**
3704 * Determine whether the user is a newbie. Newbies are either
3705 * anonymous IPs, or the most recently created accounts.
3706 * @return bool
3707 */
3708 public function isNewbie() {
3709 return !$this->isAllowed( 'autoconfirmed' );
3710 }
3711
3712 /**
3713 * Check to see if the given clear-text password is one of the accepted passwords
3714 * @param string $password user password.
3715 * @return bool True if the given password is correct, otherwise False.
3716 */
3717 public function checkPassword( $password ) {
3718 global $wgAuth, $wgLegacyEncoding;
3719 $this->load();
3720
3721 // Certain authentication plugins do NOT want to save
3722 // domain passwords in a mysql database, so we should
3723 // check this (in case $wgAuth->strict() is false).
3724
3725 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3726 return true;
3727 } elseif ( $wgAuth->strict() ) {
3728 // Auth plugin doesn't allow local authentication
3729 return false;
3730 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3731 // Auth plugin doesn't allow local authentication for this user name
3732 return false;
3733 }
3734 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3735 return true;
3736 } elseif ( $wgLegacyEncoding ) {
3737 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3738 // Check for this with iconv
3739 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3740 if ( $cp1252Password != $password
3741 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3742 ) {
3743 return true;
3744 }
3745 }
3746 return false;
3747 }
3748
3749 /**
3750 * Check if the given clear-text password matches the temporary password
3751 * sent by e-mail for password reset operations.
3752 *
3753 * @param string $plaintext
3754 *
3755 * @return bool True if matches, false otherwise
3756 */
3757 public function checkTemporaryPassword( $plaintext ) {
3758 global $wgNewPasswordExpiry;
3759
3760 $this->load();
3761 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3762 if ( is_null( $this->mNewpassTime ) ) {
3763 return true;
3764 }
3765 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3766 return ( time() < $expiry );
3767 } else {
3768 return false;
3769 }
3770 }
3771
3772 /**
3773 * Alias for getEditToken.
3774 * @deprecated since 1.19, use getEditToken instead.
3775 *
3776 * @param string|array $salt of Strings Optional function-specific data for hashing
3777 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3778 * @return string The new edit token
3779 */
3780 public function editToken( $salt = '', $request = null ) {
3781 wfDeprecated( __METHOD__, '1.19' );
3782 return $this->getEditToken( $salt, $request );
3783 }
3784
3785 /**
3786 * Initialize (if necessary) and return a session token value
3787 * which can be used in edit forms to show that the user's
3788 * login credentials aren't being hijacked with a foreign form
3789 * submission.
3790 *
3791 * @since 1.19
3792 *
3793 * @param string|array $salt of Strings Optional function-specific data for hashing
3794 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3795 * @return string The new edit token
3796 */
3797 public function getEditToken( $salt = '', $request = null ) {
3798 if ( $request == null ) {
3799 $request = $this->getRequest();
3800 }
3801
3802 if ( $this->isAnon() ) {
3803 return EDIT_TOKEN_SUFFIX;
3804 } else {
3805 $token = $request->getSessionData( 'wsEditToken' );
3806 if ( $token === null ) {
3807 $token = MWCryptRand::generateHex( 32 );
3808 $request->setSessionData( 'wsEditToken', $token );
3809 }
3810 if ( is_array( $salt ) ) {
3811 $salt = implode( '|', $salt );
3812 }
3813 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3814 }
3815 }
3816
3817 /**
3818 * Generate a looking random token for various uses.
3819 *
3820 * @return string The new random token
3821 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3822 */
3823 public static function generateToken() {
3824 return MWCryptRand::generateHex( 32 );
3825 }
3826
3827 /**
3828 * Check given value against the token value stored in the session.
3829 * A match should confirm that the form was submitted from the
3830 * user's own login session, not a form submission from a third-party
3831 * site.
3832 *
3833 * @param string $val Input value to compare
3834 * @param string $salt Optional function-specific data for hashing
3835 * @param WebRequest|null $request Object to use or null to use $wgRequest
3836 * @return bool Whether the token matches
3837 */
3838 public function matchEditToken( $val, $salt = '', $request = null ) {
3839 $sessionToken = $this->getEditToken( $salt, $request );
3840 if ( $val != $sessionToken ) {
3841 wfDebug( "User::matchEditToken: broken session data\n" );
3842 }
3843 return $val == $sessionToken;
3844 }
3845
3846 /**
3847 * Check given value against the token value stored in the session,
3848 * ignoring the suffix.
3849 *
3850 * @param string $val Input value to compare
3851 * @param string $salt Optional function-specific data for hashing
3852 * @param WebRequest|null $request object to use or null to use $wgRequest
3853 * @return bool Whether the token matches
3854 */
3855 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3856 $sessionToken = $this->getEditToken( $salt, $request );
3857 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3858 }
3859
3860 /**
3861 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3862 * mail to the user's given address.
3863 *
3864 * @param string $type Message to send, either "created", "changed" or "set"
3865 * @return Status
3866 */
3867 public function sendConfirmationMail( $type = 'created' ) {
3868 global $wgLang;
3869 $expiration = null; // gets passed-by-ref and defined in next line.
3870 $token = $this->confirmationToken( $expiration );
3871 $url = $this->confirmationTokenUrl( $token );
3872 $invalidateURL = $this->invalidationTokenUrl( $token );
3873 $this->saveSettings();
3874
3875 if ( $type == 'created' || $type === false ) {
3876 $message = 'confirmemail_body';
3877 } elseif ( $type === true ) {
3878 $message = 'confirmemail_body_changed';
3879 } else {
3880 // Messages: confirmemail_body_changed, confirmemail_body_set
3881 $message = 'confirmemail_body_' . $type;
3882 }
3883
3884 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3885 wfMessage( $message,
3886 $this->getRequest()->getIP(),
3887 $this->getName(),
3888 $url,
3889 $wgLang->timeanddate( $expiration, false ),
3890 $invalidateURL,
3891 $wgLang->date( $expiration, false ),
3892 $wgLang->time( $expiration, false ) )->text() );
3893 }
3894
3895 /**
3896 * Send an e-mail to this user's account. Does not check for
3897 * confirmed status or validity.
3898 *
3899 * @param string $subject Message subject
3900 * @param string $body Message body
3901 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3902 * @param string $replyto Reply-To address
3903 * @return Status
3904 */
3905 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3906 if ( is_null( $from ) ) {
3907 global $wgPasswordSender;
3908 $sender = new MailAddress( $wgPasswordSender,
3909 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3910 } else {
3911 $sender = new MailAddress( $from );
3912 }
3913
3914 $to = new MailAddress( $this );
3915 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3916 }
3917
3918 /**
3919 * Generate, store, and return a new e-mail confirmation code.
3920 * A hash (unsalted, since it's used as a key) is stored.
3921 *
3922 * @note Call saveSettings() after calling this function to commit
3923 * this change to the database.
3924 *
3925 * @param string &$expiration Accepts the expiration time
3926 * @return string New token
3927 */
3928 protected function confirmationToken( &$expiration ) {
3929 global $wgUserEmailConfirmationTokenExpiry;
3930 $now = time();
3931 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3932 $expiration = wfTimestamp( TS_MW, $expires );
3933 $this->load();
3934 $token = MWCryptRand::generateHex( 32 );
3935 $hash = md5( $token );
3936 $this->mEmailToken = $hash;
3937 $this->mEmailTokenExpires = $expiration;
3938 return $token;
3939 }
3940
3941 /**
3942 * Return a URL the user can use to confirm their email address.
3943 * @param string $token Accepts the email confirmation token
3944 * @return string New token URL
3945 */
3946 protected function confirmationTokenUrl( $token ) {
3947 return $this->getTokenUrl( 'ConfirmEmail', $token );
3948 }
3949
3950 /**
3951 * Return a URL the user can use to invalidate their email address.
3952 * @param string $token Accepts the email confirmation token
3953 * @return string New token URL
3954 */
3955 protected function invalidationTokenUrl( $token ) {
3956 return $this->getTokenUrl( 'InvalidateEmail', $token );
3957 }
3958
3959 /**
3960 * Internal function to format the e-mail validation/invalidation URLs.
3961 * This uses a quickie hack to use the
3962 * hardcoded English names of the Special: pages, for ASCII safety.
3963 *
3964 * @note Since these URLs get dropped directly into emails, using the
3965 * short English names avoids insanely long URL-encoded links, which
3966 * also sometimes can get corrupted in some browsers/mailers
3967 * (bug 6957 with Gmail and Internet Explorer).
3968 *
3969 * @param string $page Special page
3970 * @param string $token Token
3971 * @return string Formatted URL
3972 */
3973 protected function getTokenUrl( $page, $token ) {
3974 // Hack to bypass localization of 'Special:'
3975 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3976 return $title->getCanonicalURL();
3977 }
3978
3979 /**
3980 * Mark the e-mail address confirmed.
3981 *
3982 * @note Call saveSettings() after calling this function to commit the change.
3983 *
3984 * @return bool
3985 */
3986 public function confirmEmail() {
3987 // Check if it's already confirmed, so we don't touch the database
3988 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3989 if ( !$this->isEmailConfirmed() ) {
3990 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3991 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3992 }
3993 return true;
3994 }
3995
3996 /**
3997 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3998 * address if it was already confirmed.
3999 *
4000 * @note Call saveSettings() after calling this function to commit the change.
4001 * @return bool Returns true
4002 */
4003 public function invalidateEmail() {
4004 $this->load();
4005 $this->mEmailToken = null;
4006 $this->mEmailTokenExpires = null;
4007 $this->setEmailAuthenticationTimestamp( null );
4008 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4009 return true;
4010 }
4011
4012 /**
4013 * Set the e-mail authentication timestamp.
4014 * @param string $timestamp TS_MW timestamp
4015 */
4016 public function setEmailAuthenticationTimestamp( $timestamp ) {
4017 $this->load();
4018 $this->mEmailAuthenticated = $timestamp;
4019 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4020 }
4021
4022 /**
4023 * Is this user allowed to send e-mails within limits of current
4024 * site configuration?
4025 * @return bool
4026 */
4027 public function canSendEmail() {
4028 global $wgEnableEmail, $wgEnableUserEmail;
4029 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4030 return false;
4031 }
4032 $canSend = $this->isEmailConfirmed();
4033 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4034 return $canSend;
4035 }
4036
4037 /**
4038 * Is this user allowed to receive e-mails within limits of current
4039 * site configuration?
4040 * @return bool
4041 */
4042 public function canReceiveEmail() {
4043 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4044 }
4045
4046 /**
4047 * Is this user's e-mail address valid-looking and confirmed within
4048 * limits of the current site configuration?
4049 *
4050 * @note If $wgEmailAuthentication is on, this may require the user to have
4051 * confirmed their address by returning a code or using a password
4052 * sent to the address from the wiki.
4053 *
4054 * @return bool
4055 */
4056 public function isEmailConfirmed() {
4057 global $wgEmailAuthentication;
4058 $this->load();
4059 $confirmed = true;
4060 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4061 if ( $this->isAnon() ) {
4062 return false;
4063 }
4064 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4065 return false;
4066 }
4067 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4068 return false;
4069 }
4070 return true;
4071 } else {
4072 return $confirmed;
4073 }
4074 }
4075
4076 /**
4077 * Check whether there is an outstanding request for e-mail confirmation.
4078 * @return bool
4079 */
4080 public function isEmailConfirmationPending() {
4081 global $wgEmailAuthentication;
4082 return $wgEmailAuthentication &&
4083 !$this->isEmailConfirmed() &&
4084 $this->mEmailToken &&
4085 $this->mEmailTokenExpires > wfTimestamp();
4086 }
4087
4088 /**
4089 * Get the timestamp of account creation.
4090 *
4091 * @return string|bool|null Timestamp of account creation, false for
4092 * non-existent/anonymous user accounts, or null if existing account
4093 * but information is not in database.
4094 */
4095 public function getRegistration() {
4096 if ( $this->isAnon() ) {
4097 return false;
4098 }
4099 $this->load();
4100 return $this->mRegistration;
4101 }
4102
4103 /**
4104 * Get the timestamp of the first edit
4105 *
4106 * @return string|bool Timestamp of first edit, or false for
4107 * non-existent/anonymous user accounts.
4108 */
4109 public function getFirstEditTimestamp() {
4110 if ( $this->getId() == 0 ) {
4111 return false; // anons
4112 }
4113 $dbr = wfGetDB( DB_SLAVE );
4114 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4115 array( 'rev_user' => $this->getId() ),
4116 __METHOD__,
4117 array( 'ORDER BY' => 'rev_timestamp ASC' )
4118 );
4119 if ( !$time ) {
4120 return false; // no edits
4121 }
4122 return wfTimestamp( TS_MW, $time );
4123 }
4124
4125 /**
4126 * Get the permissions associated with a given list of groups
4127 *
4128 * @param array $groups Array of Strings List of internal group names
4129 * @return array Array of Strings List of permission key names for given groups combined
4130 */
4131 public static function getGroupPermissions( $groups ) {
4132 global $wgGroupPermissions, $wgRevokePermissions;
4133 $rights = array();
4134 // grant every granted permission first
4135 foreach ( $groups as $group ) {
4136 if ( isset( $wgGroupPermissions[$group] ) ) {
4137 $rights = array_merge( $rights,
4138 // array_filter removes empty items
4139 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4140 }
4141 }
4142 // now revoke the revoked permissions
4143 foreach ( $groups as $group ) {
4144 if ( isset( $wgRevokePermissions[$group] ) ) {
4145 $rights = array_diff( $rights,
4146 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4147 }
4148 }
4149 return array_unique( $rights );
4150 }
4151
4152 /**
4153 * Get all the groups who have a given permission
4154 *
4155 * @param string $role Role to check
4156 * @return array Array of Strings List of internal group names with the given permission
4157 */
4158 public static function getGroupsWithPermission( $role ) {
4159 global $wgGroupPermissions;
4160 $allowedGroups = array();
4161 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4162 if ( self::groupHasPermission( $group, $role ) ) {
4163 $allowedGroups[] = $group;
4164 }
4165 }
4166 return $allowedGroups;
4167 }
4168
4169 /**
4170 * Check, if the given group has the given permission
4171 *
4172 * If you're wanting to check whether all users have a permission, use
4173 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4174 * from anyone.
4175 *
4176 * @since 1.21
4177 * @param string $group Group to check
4178 * @param string $role Role to check
4179 * @return bool
4180 */
4181 public static function groupHasPermission( $group, $role ) {
4182 global $wgGroupPermissions, $wgRevokePermissions;
4183 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4184 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4185 }
4186
4187 /**
4188 * Check if all users have the given permission
4189 *
4190 * @since 1.22
4191 * @param string $right Right to check
4192 * @return bool
4193 */
4194 public static function isEveryoneAllowed( $right ) {
4195 global $wgGroupPermissions, $wgRevokePermissions;
4196 static $cache = array();
4197
4198 // Use the cached results, except in unit tests which rely on
4199 // being able change the permission mid-request
4200 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4201 return $cache[$right];
4202 }
4203
4204 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4205 $cache[$right] = false;
4206 return false;
4207 }
4208
4209 // If it's revoked anywhere, then everyone doesn't have it
4210 foreach ( $wgRevokePermissions as $rights ) {
4211 if ( isset( $rights[$right] ) && $rights[$right] ) {
4212 $cache[$right] = false;
4213 return false;
4214 }
4215 }
4216
4217 // Allow extensions (e.g. OAuth) to say false
4218 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4219 $cache[$right] = false;
4220 return false;
4221 }
4222
4223 $cache[$right] = true;
4224 return true;
4225 }
4226
4227 /**
4228 * Get the localized descriptive name for a group, if it exists
4229 *
4230 * @param string $group Internal group name
4231 * @return string Localized descriptive group name
4232 */
4233 public static function getGroupName( $group ) {
4234 $msg = wfMessage( "group-$group" );
4235 return $msg->isBlank() ? $group : $msg->text();
4236 }
4237
4238 /**
4239 * Get the localized descriptive name for a member of a group, if it exists
4240 *
4241 * @param string $group Internal group name
4242 * @param string $username Username for gender (since 1.19)
4243 * @return string Localized name for group member
4244 */
4245 public static function getGroupMember( $group, $username = '#' ) {
4246 $msg = wfMessage( "group-$group-member", $username );
4247 return $msg->isBlank() ? $group : $msg->text();
4248 }
4249
4250 /**
4251 * Return the set of defined explicit groups.
4252 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4253 * are not included, as they are defined automatically, not in the database.
4254 * @return array Array of internal group names
4255 */
4256 public static function getAllGroups() {
4257 global $wgGroupPermissions, $wgRevokePermissions;
4258 return array_diff(
4259 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4260 self::getImplicitGroups()
4261 );
4262 }
4263
4264 /**
4265 * Get a list of all available permissions.
4266 * @return array Array of permission names
4267 */
4268 public static function getAllRights() {
4269 if ( self::$mAllRights === false ) {
4270 global $wgAvailableRights;
4271 if ( count( $wgAvailableRights ) ) {
4272 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4273 } else {
4274 self::$mAllRights = self::$mCoreRights;
4275 }
4276 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4277 }
4278 return self::$mAllRights;
4279 }
4280
4281 /**
4282 * Get a list of implicit groups
4283 * @return array Array of Strings Array of internal group names
4284 */
4285 public static function getImplicitGroups() {
4286 global $wgImplicitGroups;
4287 $groups = $wgImplicitGroups;
4288 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4289 return $groups;
4290 }
4291
4292 /**
4293 * Get the title of a page describing a particular group
4294 *
4295 * @param string $group Internal group name
4296 * @return Title|bool Title of the page if it exists, false otherwise
4297 */
4298 public static function getGroupPage( $group ) {
4299 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4300 if ( $msg->exists() ) {
4301 $title = Title::newFromText( $msg->text() );
4302 if ( is_object( $title ) ) {
4303 return $title;
4304 }
4305 }
4306 return false;
4307 }
4308
4309 /**
4310 * Create a link to the group in HTML, if available;
4311 * else return the group name.
4312 *
4313 * @param string $group Internal name of the group
4314 * @param string $text The text of the link
4315 * @return string HTML link to the group
4316 */
4317 public static function makeGroupLinkHTML( $group, $text = '' ) {
4318 if ( $text == '' ) {
4319 $text = self::getGroupName( $group );
4320 }
4321 $title = self::getGroupPage( $group );
4322 if ( $title ) {
4323 return Linker::link( $title, htmlspecialchars( $text ) );
4324 } else {
4325 return $text;
4326 }
4327 }
4328
4329 /**
4330 * Create a link to the group in Wikitext, if available;
4331 * else return the group name.
4332 *
4333 * @param string $group Internal name of the group
4334 * @param string $text The text of the link
4335 * @return string Wikilink to the group
4336 */
4337 public static function makeGroupLinkWiki( $group, $text = '' ) {
4338 if ( $text == '' ) {
4339 $text = self::getGroupName( $group );
4340 }
4341 $title = self::getGroupPage( $group );
4342 if ( $title ) {
4343 $page = $title->getPrefixedText();
4344 return "[[$page|$text]]";
4345 } else {
4346 return $text;
4347 }
4348 }
4349
4350 /**
4351 * Returns an array of the groups that a particular group can add/remove.
4352 *
4353 * @param string $group The group to check for whether it can add/remove
4354 * @return array array( 'add' => array( addablegroups ),
4355 * 'remove' => array( removablegroups ),
4356 * 'add-self' => array( addablegroups to self),
4357 * 'remove-self' => array( removable groups from self) )
4358 */
4359 public static function changeableByGroup( $group ) {
4360 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4361
4362 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4363 if ( empty( $wgAddGroups[$group] ) ) {
4364 // Don't add anything to $groups
4365 } elseif ( $wgAddGroups[$group] === true ) {
4366 // You get everything
4367 $groups['add'] = self::getAllGroups();
4368 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4369 $groups['add'] = $wgAddGroups[$group];
4370 }
4371
4372 // Same thing for remove
4373 if ( empty( $wgRemoveGroups[$group] ) ) {
4374 } elseif ( $wgRemoveGroups[$group] === true ) {
4375 $groups['remove'] = self::getAllGroups();
4376 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4377 $groups['remove'] = $wgRemoveGroups[$group];
4378 }
4379
4380 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4381 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4382 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4383 if ( is_int( $key ) ) {
4384 $wgGroupsAddToSelf['user'][] = $value;
4385 }
4386 }
4387 }
4388
4389 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4390 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4391 if ( is_int( $key ) ) {
4392 $wgGroupsRemoveFromSelf['user'][] = $value;
4393 }
4394 }
4395 }
4396
4397 // Now figure out what groups the user can add to him/herself
4398 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4399 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4400 // No idea WHY this would be used, but it's there
4401 $groups['add-self'] = User::getAllGroups();
4402 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4403 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4404 }
4405
4406 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4407 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4408 $groups['remove-self'] = User::getAllGroups();
4409 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4410 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4411 }
4412
4413 return $groups;
4414 }
4415
4416 /**
4417 * Returns an array of groups that this user can add and remove
4418 * @return array array( 'add' => array( addablegroups ),
4419 * 'remove' => array( removablegroups ),
4420 * 'add-self' => array( addablegroups to self),
4421 * 'remove-self' => array( removable groups from self) )
4422 */
4423 public function changeableGroups() {
4424 if ( $this->isAllowed( 'userrights' ) ) {
4425 // This group gives the right to modify everything (reverse-
4426 // compatibility with old "userrights lets you change
4427 // everything")
4428 // Using array_merge to make the groups reindexed
4429 $all = array_merge( User::getAllGroups() );
4430 return array(
4431 'add' => $all,
4432 'remove' => $all,
4433 'add-self' => array(),
4434 'remove-self' => array()
4435 );
4436 }
4437
4438 // Okay, it's not so simple, we will have to go through the arrays
4439 $groups = array(
4440 'add' => array(),
4441 'remove' => array(),
4442 'add-self' => array(),
4443 'remove-self' => array()
4444 );
4445 $addergroups = $this->getEffectiveGroups();
4446
4447 foreach ( $addergroups as $addergroup ) {
4448 $groups = array_merge_recursive(
4449 $groups, $this->changeableByGroup( $addergroup )
4450 );
4451 $groups['add'] = array_unique( $groups['add'] );
4452 $groups['remove'] = array_unique( $groups['remove'] );
4453 $groups['add-self'] = array_unique( $groups['add-self'] );
4454 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4455 }
4456 return $groups;
4457 }
4458
4459 /**
4460 * Increment the user's edit-count field.
4461 * Will have no effect for anonymous users.
4462 */
4463 public function incEditCount() {
4464 if ( !$this->isAnon() ) {
4465 $dbw = wfGetDB( DB_MASTER );
4466 $dbw->update(
4467 'user',
4468 array( 'user_editcount=user_editcount+1' ),
4469 array( 'user_id' => $this->getId() ),
4470 __METHOD__
4471 );
4472
4473 // Lazy initialization check...
4474 if ( $dbw->affectedRows() == 0 ) {
4475 // Now here's a goddamn hack...
4476 $dbr = wfGetDB( DB_SLAVE );
4477 if ( $dbr !== $dbw ) {
4478 // If we actually have a slave server, the count is
4479 // at least one behind because the current transaction
4480 // has not been committed and replicated.
4481 $this->initEditCount( 1 );
4482 } else {
4483 // But if DB_SLAVE is selecting the master, then the
4484 // count we just read includes the revision that was
4485 // just added in the working transaction.
4486 $this->initEditCount();
4487 }
4488 }
4489 }
4490 // edit count in user cache too
4491 $this->invalidateCache();
4492 }
4493
4494 /**
4495 * Initialize user_editcount from data out of the revision table
4496 *
4497 * @param int $add Edits to add to the count from the revision table
4498 * @return int Number of edits
4499 */
4500 protected function initEditCount( $add = 0 ) {
4501 // Pull from a slave to be less cruel to servers
4502 // Accuracy isn't the point anyway here
4503 $dbr = wfGetDB( DB_SLAVE );
4504 $count = (int)$dbr->selectField(
4505 'revision',
4506 'COUNT(rev_user)',
4507 array( 'rev_user' => $this->getId() ),
4508 __METHOD__
4509 );
4510 $count = $count + $add;
4511
4512 $dbw = wfGetDB( DB_MASTER );
4513 $dbw->update(
4514 'user',
4515 array( 'user_editcount' => $count ),
4516 array( 'user_id' => $this->getId() ),
4517 __METHOD__
4518 );
4519
4520 return $count;
4521 }
4522
4523 /**
4524 * Get the description of a given right
4525 *
4526 * @param string $right Right to query
4527 * @return string Localized description of the right
4528 */
4529 public static function getRightDescription( $right ) {
4530 $key = "right-$right";
4531 $msg = wfMessage( $key );
4532 return $msg->isBlank() ? $right : $msg->text();
4533 }
4534
4535 /**
4536 * Make an old-style password hash
4537 *
4538 * @param string $password Plain-text password
4539 * @param string $userId User ID
4540 * @return string Password hash
4541 */
4542 public static function oldCrypt( $password, $userId ) {
4543 global $wgPasswordSalt;
4544 if ( $wgPasswordSalt ) {
4545 return md5( $userId . '-' . md5( $password ) );
4546 } else {
4547 return md5( $password );
4548 }
4549 }
4550
4551 /**
4552 * Make a new-style password hash
4553 *
4554 * @param string $password Plain-text password
4555 * @param bool|string $salt Optional salt, may be random or the user ID.
4556 * If unspecified or false, will generate one automatically
4557 * @return string Password hash
4558 */
4559 public static function crypt( $password, $salt = false ) {
4560 global $wgPasswordSalt;
4561
4562 $hash = '';
4563 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4564 return $hash;
4565 }
4566
4567 if ( $wgPasswordSalt ) {
4568 if ( $salt === false ) {
4569 $salt = MWCryptRand::generateHex( 8 );
4570 }
4571 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4572 } else {
4573 return ':A:' . md5( $password );
4574 }
4575 }
4576
4577 /**
4578 * Compare a password hash with a plain-text password. Requires the user
4579 * ID if there's a chance that the hash is an old-style hash.
4580 *
4581 * @param string $hash Password hash
4582 * @param string $password Plain-text password to compare
4583 * @param string|bool $userId User ID for old-style password salt
4584 *
4585 * @return bool
4586 */
4587 public static function comparePasswords( $hash, $password, $userId = false ) {
4588 $type = substr( $hash, 0, 3 );
4589
4590 $result = false;
4591 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4592 return $result;
4593 }
4594
4595 if ( $type == ':A:' ) {
4596 // Unsalted
4597 return md5( $password ) === substr( $hash, 3 );
4598 } elseif ( $type == ':B:' ) {
4599 // Salted
4600 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4601 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4602 } else {
4603 // Old-style
4604 return self::oldCrypt( $password, $userId ) === $hash;
4605 }
4606 }
4607
4608 /**
4609 * Add a newuser log entry for this user.
4610 * Before 1.19 the return value was always true.
4611 *
4612 * @param string|bool $action Account creation type.
4613 * - String, one of the following values:
4614 * - 'create' for an anonymous user creating an account for himself.
4615 * This will force the action's performer to be the created user itself,
4616 * no matter the value of $wgUser
4617 * - 'create2' for a logged in user creating an account for someone else
4618 * - 'byemail' when the created user will receive its password by e-mail
4619 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4620 * - Boolean means whether the account was created by e-mail (deprecated):
4621 * - true will be converted to 'byemail'
4622 * - false will be converted to 'create' if this object is the same as
4623 * $wgUser and to 'create2' otherwise
4624 *
4625 * @param string $reason User supplied reason
4626 *
4627 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4628 */
4629 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4630 global $wgUser, $wgNewUserLog;
4631 if ( empty( $wgNewUserLog ) ) {
4632 return true; // disabled
4633 }
4634
4635 if ( $action === true ) {
4636 $action = 'byemail';
4637 } elseif ( $action === false ) {
4638 if ( $this->getName() == $wgUser->getName() ) {
4639 $action = 'create';
4640 } else {
4641 $action = 'create2';
4642 }
4643 }
4644
4645 if ( $action === 'create' || $action === 'autocreate' ) {
4646 $performer = $this;
4647 } else {
4648 $performer = $wgUser;
4649 }
4650
4651 $logEntry = new ManualLogEntry( 'newusers', $action );
4652 $logEntry->setPerformer( $performer );
4653 $logEntry->setTarget( $this->getUserPage() );
4654 $logEntry->setComment( $reason );
4655 $logEntry->setParameters( array(
4656 '4::userid' => $this->getId(),
4657 ) );
4658 $logid = $logEntry->insert();
4659
4660 if ( $action !== 'autocreate' ) {
4661 $logEntry->publish( $logid );
4662 }
4663
4664 return (int)$logid;
4665 }
4666
4667 /**
4668 * Add an autocreate newuser log entry for this user
4669 * Used by things like CentralAuth and perhaps other authplugins.
4670 * Consider calling addNewUserLogEntry() directly instead.
4671 *
4672 * @return bool
4673 */
4674 public function addNewUserLogEntryAutoCreate() {
4675 $this->addNewUserLogEntry( 'autocreate' );
4676
4677 return true;
4678 }
4679
4680 /**
4681 * Load the user options either from cache, the database or an array
4682 *
4683 * @param array $data Rows for the current user out of the user_properties table
4684 */
4685 protected function loadOptions( $data = null ) {
4686 global $wgContLang;
4687
4688 $this->load();
4689
4690 if ( $this->mOptionsLoaded ) {
4691 return;
4692 }
4693
4694 $this->mOptions = self::getDefaultOptions();
4695
4696 if ( !$this->getId() ) {
4697 // For unlogged-in users, load language/variant options from request.
4698 // There's no need to do it for logged-in users: they can set preferences,
4699 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4700 // so don't override user's choice (especially when the user chooses site default).
4701 $variant = $wgContLang->getDefaultVariant();
4702 $this->mOptions['variant'] = $variant;
4703 $this->mOptions['language'] = $variant;
4704 $this->mOptionsLoaded = true;
4705 return;
4706 }
4707
4708 // Maybe load from the object
4709 if ( !is_null( $this->mOptionOverrides ) ) {
4710 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4711 foreach ( $this->mOptionOverrides as $key => $value ) {
4712 $this->mOptions[$key] = $value;
4713 }
4714 } else {
4715 if ( !is_array( $data ) ) {
4716 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4717 // Load from database
4718 $dbr = wfGetDB( DB_SLAVE );
4719
4720 $res = $dbr->select(
4721 'user_properties',
4722 array( 'up_property', 'up_value' ),
4723 array( 'up_user' => $this->getId() ),
4724 __METHOD__
4725 );
4726
4727 $this->mOptionOverrides = array();
4728 $data = array();
4729 foreach ( $res as $row ) {
4730 $data[$row->up_property] = $row->up_value;
4731 }
4732 }
4733 foreach ( $data as $property => $value ) {
4734 $this->mOptionOverrides[$property] = $value;
4735 $this->mOptions[$property] = $value;
4736 }
4737 }
4738
4739 $this->mOptionsLoaded = true;
4740
4741 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4742 }
4743
4744 /**
4745 * @todo document
4746 */
4747 protected function saveOptions() {
4748 $this->loadOptions();
4749
4750 // Not using getOptions(), to keep hidden preferences in database
4751 $saveOptions = $this->mOptions;
4752
4753 // Allow hooks to abort, for instance to save to a global profile.
4754 // Reset options to default state before saving.
4755 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4756 return;
4757 }
4758
4759 $userId = $this->getId();
4760 $insert_rows = array();
4761 foreach ( $saveOptions as $key => $value ) {
4762 // Don't bother storing default values
4763 $defaultOption = self::getDefaultOption( $key );
4764 if ( ( is_null( $defaultOption ) &&
4765 !( $value === false || is_null( $value ) ) ) ||
4766 $value != $defaultOption
4767 ) {
4768 $insert_rows[] = array(
4769 'up_user' => $userId,
4770 'up_property' => $key,
4771 'up_value' => $value,
4772 );
4773 }
4774 }
4775
4776 $dbw = wfGetDB( DB_MASTER );
4777 // Find and delete any prior preference rows...
4778 $res = $dbw->select( 'user_properties',
4779 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4780 $priorKeys = array();
4781 foreach ( $res as $row ) {
4782 $priorKeys[] = $row->up_property;
4783 }
4784 if ( count( $priorKeys ) ) {
4785 // Do the DELETE by PRIMARY KEY for prior rows.
4786 // In the past a very large portion of calls to this function are for setting
4787 // 'rememberpassword' for new accounts (a preference that has since been removed).
4788 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4789 // caused gap locks on [max user ID,+infinity) which caused high contention since
4790 // updates would pile up on each other as they are for higher (newer) user IDs.
4791 // It might not be necessary these days, but it shouldn't hurt either.
4792 $dbw->delete( 'user_properties',
4793 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4794 }
4795 // Insert the new preference rows
4796 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4797 }
4798
4799 /**
4800 * Provide an array of HTML5 attributes to put on an input element
4801 * intended for the user to enter a new password. This may include
4802 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4803 *
4804 * Do *not* use this when asking the user to enter his current password!
4805 * Regardless of configuration, users may have invalid passwords for whatever
4806 * reason (e.g., they were set before requirements were tightened up).
4807 * Only use it when asking for a new password, like on account creation or
4808 * ResetPass.
4809 *
4810 * Obviously, you still need to do server-side checking.
4811 *
4812 * NOTE: A combination of bugs in various browsers means that this function
4813 * actually just returns array() unconditionally at the moment. May as
4814 * well keep it around for when the browser bugs get fixed, though.
4815 *
4816 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4817 *
4818 * @return array Array of HTML attributes suitable for feeding to
4819 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4820 * That will get confused by the boolean attribute syntax used.)
4821 */
4822 public static function passwordChangeInputAttribs() {
4823 global $wgMinimalPasswordLength;
4824
4825 if ( $wgMinimalPasswordLength == 0 ) {
4826 return array();
4827 }
4828
4829 # Note that the pattern requirement will always be satisfied if the
4830 # input is empty, so we need required in all cases.
4831 #
4832 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4833 # if e-mail confirmation is being used. Since HTML5 input validation
4834 # is b0rked anyway in some browsers, just return nothing. When it's
4835 # re-enabled, fix this code to not output required for e-mail
4836 # registration.
4837 #$ret = array( 'required' );
4838 $ret = array();
4839
4840 # We can't actually do this right now, because Opera 9.6 will print out
4841 # the entered password visibly in its error message! When other
4842 # browsers add support for this attribute, or Opera fixes its support,
4843 # we can add support with a version check to avoid doing this on Opera
4844 # versions where it will be a problem. Reported to Opera as
4845 # DSK-262266, but they don't have a public bug tracker for us to follow.
4846 /*
4847 if ( $wgMinimalPasswordLength > 1 ) {
4848 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4849 $ret['title'] = wfMessage( 'passwordtooshort' )
4850 ->numParams( $wgMinimalPasswordLength )->text();
4851 }
4852 */
4853
4854 return $ret;
4855 }
4856
4857 /**
4858 * Return the list of user fields that should be selected to create
4859 * a new user object.
4860 * @return array
4861 */
4862 public static function selectFields() {
4863 return array(
4864 'user_id',
4865 'user_name',
4866 'user_real_name',
4867 'user_password',
4868 'user_newpassword',
4869 'user_newpass_time',
4870 'user_email',
4871 'user_touched',
4872 'user_token',
4873 'user_email_authenticated',
4874 'user_email_token',
4875 'user_email_token_expires',
4876 'user_password_expires',
4877 'user_registration',
4878 'user_editcount',
4879 );
4880 }
4881
4882 /**
4883 * Factory function for fatal permission-denied errors
4884 *
4885 * @since 1.22
4886 * @param string $permission User right required
4887 * @return Status
4888 */
4889 static function newFatalPermissionDeniedStatus( $permission ) {
4890 global $wgLang;
4891
4892 $groups = array_map(
4893 array( 'User', 'makeGroupLinkWiki' ),
4894 User::getGroupsWithPermission( $permission )
4895 );
4896
4897 if ( $groups ) {
4898 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4899 } else {
4900 return Status::newFatal( 'badaccess-group0' );
4901 }
4902 }
4903 }