3 * Implements the User class for the %MediaWiki software.
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.
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.
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
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
39 class User
implements IDBAccessObject
{
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH
= 32;
46 * Global constant made accessible as class constants so that autoloader
49 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
52 * @const int Serialized record version.
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE
= 100;
62 * Exclude user options that are set to their default value.
65 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
78 protected static $mCacheVars = array(
86 'mEmailAuthenticated',
93 // user_properties table
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
103 protected static $mCoreRights = array(
130 'editusercssjs', #deprecated
142 'move-categorypages',
143 'move-rootuserpages',
147 'override-export-depth',
171 'userrights-interwiki',
179 * String Cached results of getAllRights()
181 protected static $mAllRights = false;
183 /** @name Cache variables */
192 * @todo Make this actually private
198 * @todo Make this actually private
201 public $mNewpassword;
203 public $mNewpassTime;
211 public $mEmailAuthenticated;
213 protected $mEmailToken;
215 protected $mEmailTokenExpires;
217 protected $mRegistration;
219 protected $mEditCount;
223 protected $mOptionOverrides;
225 protected $mPasswordExpires;
229 * Bool Whether the cache variables have been loaded.
232 public $mOptionsLoaded;
235 * Array with already loaded items or true if all items have been loaded.
237 protected $mLoadedItems = array();
241 * String Initialization data source if mLoadedItems!==true. May be one of:
242 * - 'defaults' anonymous user initialised from class defaults
243 * - 'name' initialise from mName
244 * - 'id' initialise from mId
245 * - 'session' log in from cookies or session if possible
247 * Use the User::newFrom*() family of functions to set this.
252 * Lazy-initialized variables, invalidated with clearInstanceCache
256 protected $mDatePreference;
264 protected $mBlockreason;
266 protected $mEffectiveGroups;
268 protected $mImplicitGroups;
270 protected $mFormerGroups;
272 protected $mBlockedGlobally;
289 protected $mAllowUsertalk;
292 private $mBlockedFromCreateAccount = false;
295 private $mWatchedItems = array();
297 public static $idCacheByName = array();
300 * Lightweight constructor for an anonymous user.
301 * Use the User::newFrom* factory functions for other kinds of users.
305 * @see newFromConfirmationCode()
306 * @see newFromSession()
309 public function __construct() {
310 $this->clearInstanceCache( 'defaults' );
316 public function __toString() {
317 return $this->getName();
321 * Load the user table data for this object from the source given by mFrom.
323 public function load() {
324 if ( $this->mLoadedItems
=== true ) {
328 // Set it now to avoid infinite recursion in accessors
329 $this->mLoadedItems
= true;
331 switch ( $this->mFrom
) {
333 $this->loadDefaults();
336 $this->mId
= self
::idFromName( $this->mName
);
338 // Nonexistent user placeholder object
339 $this->loadDefaults( $this->mName
);
348 if ( !$this->loadFromSession() ) {
349 // Loading from session failed. Load defaults.
350 $this->loadDefaults();
352 Hooks
::run( 'UserLoadAfterLoadFromSession', array( $this ) );
355 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
360 * Load user table data, given mId has already been set.
361 * @return bool False if the ID does not exist, true otherwise
363 public function loadFromId() {
364 if ( $this->mId
== 0 ) {
365 $this->loadDefaults();
370 $cache = $this->loadFromCache();
372 wfDebug( "User: cache miss for user {$this->mId}\n" );
374 if ( !$this->loadFromDatabase() ) {
375 // Can't load from ID, user is anonymous
378 $this->saveToCache();
381 $this->mLoadedItems
= true;
387 * Load user data from shared cache, given mId has already been set.
389 * @return bool false if the ID does not exist or data is invalid, true otherwise
392 public function loadFromCache() {
395 if ( $this->mId
== 0 ) {
396 $this->loadDefaults();
400 $key = wfMemcKey( 'user', 'id', $this->mId
);
401 $data = $wgMemc->get( $key );
402 if ( !is_array( $data ) ||
$data['mVersion'] < self
::VERSION
) {
407 wfDebug( "User: got user {$this->mId} from cache\n" );
409 // Restore from cache
410 foreach ( self
::$mCacheVars as $name ) {
411 $this->$name = $data[$name];
418 * Save user data to the shared cache
420 public function saveToCache() {
423 $this->loadOptions();
424 if ( $this->isAnon() ) {
425 // Anonymous users are uncached
429 foreach ( self
::$mCacheVars as $name ) {
430 $data[$name] = $this->$name;
432 $data['mVersion'] = self
::VERSION
;
433 $key = wfMemcKey( 'user', 'id', $this->mId
);
435 $wgMemc->set( $key, $data );
438 /** @name newFrom*() static factory methods */
442 * Static factory method for creation from username.
444 * This is slightly less efficient than newFromId(), so use newFromId() if
445 * you have both an ID and a name handy.
447 * @param string $name Username, validated by Title::newFromText()
448 * @param string|bool $validate Validate username. Takes the same parameters as
449 * User::getCanonicalName(), except that true is accepted as an alias
450 * for 'valid', for BC.
452 * @return User|bool User object, or false if the username is invalid
453 * (e.g. if it contains illegal characters or is an IP address). If the
454 * username is not present in the database, the result will be a user object
455 * with a name, zero user ID and default settings.
457 public static function newFromName( $name, $validate = 'valid' ) {
458 if ( $validate === true ) {
461 $name = self
::getCanonicalName( $name, $validate );
462 if ( $name === false ) {
465 // Create unloaded user object
469 $u->setItemLoaded( 'name' );
475 * Static factory method for creation from a given user ID.
477 * @param int $id Valid user ID
478 * @return User The corresponding User object
480 public static function newFromId( $id ) {
484 $u->setItemLoaded( 'id' );
489 * Factory method to fetch whichever user has a given email confirmation code.
490 * This code is generated when an account is created or its e-mail address
493 * If the code is invalid or has expired, returns NULL.
495 * @param string $code Confirmation code
498 public static function newFromConfirmationCode( $code ) {
499 $dbr = wfGetDB( DB_SLAVE
);
500 $id = $dbr->selectField( 'user', 'user_id', array(
501 'user_email_token' => md5( $code ),
502 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
504 if ( $id !== false ) {
505 return User
::newFromId( $id );
512 * Create a new user object using data from session or cookies. If the
513 * login credentials are invalid, the result is an anonymous user.
515 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
518 public static function newFromSession( WebRequest
$request = null ) {
520 $user->mFrom
= 'session';
521 $user->mRequest
= $request;
526 * Create a new user object from a user row.
527 * The row should have the following fields from the user table in it:
528 * - either user_name or user_id to load further data if needed (or both)
530 * - all other fields (email, password, etc.)
531 * It is useless to provide the remaining fields if either user_id,
532 * user_name and user_real_name are not provided because the whole row
533 * will be loaded once more from the database when accessing them.
535 * @param stdClass $row A row from the user table
536 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
539 public static function newFromRow( $row, $data = null ) {
541 $user->loadFromRow( $row, $data );
548 * Get the username corresponding to a given user ID
549 * @param int $id User ID
550 * @return string|bool The corresponding username
552 public static function whoIs( $id ) {
553 return UserCache
::singleton()->getProp( $id, 'name' );
557 * Get the real name of a user given their user ID
559 * @param int $id User ID
560 * @return string|bool The corresponding user's real name
562 public static function whoIsReal( $id ) {
563 return UserCache
::singleton()->getProp( $id, 'real_name' );
567 * Get database id given a user name
568 * @param string $name Username
569 * @return int|null The corresponding user's ID, or null if user is nonexistent
571 public static function idFromName( $name ) {
572 $nt = Title
::makeTitleSafe( NS_USER
, $name );
573 if ( is_null( $nt ) ) {
578 if ( isset( self
::$idCacheByName[$name] ) ) {
579 return self
::$idCacheByName[$name];
582 $dbr = wfGetDB( DB_SLAVE
);
583 $s = $dbr->selectRow(
586 array( 'user_name' => $nt->getText() ),
590 if ( $s === false ) {
593 $result = $s->user_id
;
596 self
::$idCacheByName[$name] = $result;
598 if ( count( self
::$idCacheByName ) > 1000 ) {
599 self
::$idCacheByName = array();
606 * Reset the cache used in idFromName(). For use in tests.
608 public static function resetIdByNameCache() {
609 self
::$idCacheByName = array();
613 * Does the string match an anonymous IPv4 address?
615 * This function exists for username validation, in order to reject
616 * usernames which are similar in form to IP addresses. Strings such
617 * as 300.300.300.300 will return true because it looks like an IP
618 * address, despite not being strictly valid.
620 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
621 * address because the usemod software would "cloak" anonymous IP
622 * addresses like this, if we allowed accounts like this to be created
623 * new users could get the old edits of these anonymous users.
625 * @param string $name Name to match
628 public static function isIP( $name ) {
629 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
630 || IP
::isIPv6( $name );
634 * Is the input a valid username?
636 * Checks if the input is a valid username, we don't want an empty string,
637 * an IP address, anything that contains slashes (would mess up subpages),
638 * is longer than the maximum allowed username size or doesn't begin with
641 * @param string $name Name to match
644 public static function isValidUserName( $name ) {
645 global $wgContLang, $wgMaxNameChars;
648 || User
::isIP( $name )
649 ||
strpos( $name, '/' ) !== false
650 ||
strlen( $name ) > $wgMaxNameChars
651 ||
$name != $wgContLang->ucfirst( $name )
653 wfDebugLog( 'username', __METHOD__
.
654 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
658 // Ensure that the name can't be misresolved as a different title,
659 // such as with extra namespace keys at the start.
660 $parsed = Title
::newFromText( $name );
661 if ( is_null( $parsed )
662 ||
$parsed->getNamespace()
663 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
664 wfDebugLog( 'username', __METHOD__
.
665 ": '$name' invalid due to ambiguous prefixes" );
669 // Check an additional blacklist of troublemaker characters.
670 // Should these be merged into the title char list?
671 $unicodeBlacklist = '/[' .
672 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
673 '\x{00a0}' . # non-breaking space
674 '\x{2000}-\x{200f}' . # various whitespace
675 '\x{2028}-\x{202f}' . # breaks and control chars
676 '\x{3000}' . # ideographic space
677 '\x{e000}-\x{f8ff}' . # private use
679 if ( preg_match( $unicodeBlacklist, $name ) ) {
680 wfDebugLog( 'username', __METHOD__
.
681 ": '$name' invalid due to blacklisted characters" );
689 * Usernames which fail to pass this function will be blocked
690 * from user login and new account registrations, but may be used
691 * internally by batch processes.
693 * If an account already exists in this form, login will be blocked
694 * by a failure to pass this function.
696 * @param string $name Name to match
699 public static function isUsableName( $name ) {
700 global $wgReservedUsernames;
701 // Must be a valid username, obviously ;)
702 if ( !self
::isValidUserName( $name ) ) {
706 static $reservedUsernames = false;
707 if ( !$reservedUsernames ) {
708 $reservedUsernames = $wgReservedUsernames;
709 Hooks
::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
712 // Certain names may be reserved for batch processes.
713 foreach ( $reservedUsernames as $reserved ) {
714 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
715 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
717 if ( $reserved == $name ) {
725 * Usernames which fail to pass this function will be blocked
726 * from new account registrations, but may be used internally
727 * either by batch processes or by user accounts which have
728 * already been created.
730 * Additional blacklisting may be added here rather than in
731 * isValidUserName() to avoid disrupting existing accounts.
733 * @param string $name String to match
736 public static function isCreatableName( $name ) {
737 global $wgInvalidUsernameCharacters;
739 // Ensure that the username isn't longer than 235 bytes, so that
740 // (at least for the builtin skins) user javascript and css files
741 // will work. (bug 23080)
742 if ( strlen( $name ) > 235 ) {
743 wfDebugLog( 'username', __METHOD__
.
744 ": '$name' invalid due to length" );
748 // Preg yells if you try to give it an empty string
749 if ( $wgInvalidUsernameCharacters !== '' ) {
750 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
751 wfDebugLog( 'username', __METHOD__
.
752 ": '$name' invalid due to wgInvalidUsernameCharacters" );
757 return self
::isUsableName( $name );
761 * Is the input a valid password for this user?
763 * @param string $password Desired password
766 public function isValidPassword( $password ) {
767 //simple boolean wrapper for getPasswordValidity
768 return $this->getPasswordValidity( $password ) === true;
773 * Given unvalidated password input, return error message on failure.
775 * @param string $password Desired password
776 * @return bool|string|array True on success, string or array of error message on failure
778 public function getPasswordValidity( $password ) {
779 $result = $this->checkPasswordValidity( $password );
780 if ( $result->isGood() ) {
784 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
785 $messages[] = $error['message'];
787 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
788 $messages[] = $warning['message'];
790 if ( count( $messages ) === 1 ) {
798 * Check if this is a valid password for this user. Status will be good if
799 * the password is valid, or have an array of error messages if not.
801 * @param string $password Desired password
805 public function checkPasswordValidity( $password ) {
806 global $wgMinimalPasswordLength, $wgContLang;
808 static $blockedLogins = array(
809 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
810 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
813 $status = Status
::newGood();
815 $result = false; //init $result to false for the internal checks
817 if ( !Hooks
::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
818 $status->error( $result );
822 if ( $result === false ) {
823 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
824 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
826 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
827 $status->error( 'password-name-match' );
829 } elseif ( isset( $blockedLogins[$this->getName()] )
830 && $password == $blockedLogins[$this->getName()]
832 $status->error( 'password-login-forbidden' );
835 //it seems weird returning a Good status here, but this is because of the
836 //initialization of $result to false above. If the hook is never run or it
837 //doesn't modify $result, then we will likely get down into this if with
841 } elseif ( $result === true ) {
844 $status->error( $result );
845 return $status; //the isValidPassword hook set a string $result and returned true
850 * Expire a user's password
852 * @param int $ts Optional timestamp to convert, default 0 for the current time
854 public function expirePassword( $ts = 0 ) {
855 $this->loadPasswords();
856 $timestamp = wfTimestamp( TS_MW
, $ts );
857 $this->mPasswordExpires
= $timestamp;
858 $this->saveSettings();
862 * Clear the password expiration for a user
864 * @param bool $load Ensure user object is loaded first
866 public function resetPasswordExpiration( $load = true ) {
867 global $wgPasswordExpirationDays;
872 if ( $wgPasswordExpirationDays ) {
873 $newExpire = wfTimestamp(
875 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
878 // Give extensions a chance to force an expiration
879 Hooks
::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
880 $this->mPasswordExpires
= $newExpire;
884 * Check if the user's password is expired.
885 * TODO: Put this and password length into a PasswordPolicy object
887 * @return string|bool The expiration type, or false if not expired
888 * hard: A password change is required to login
889 * soft: Allow login, but encourage password change
890 * false: Password is not expired
892 public function getPasswordExpired() {
893 global $wgPasswordExpireGrace;
895 $now = wfTimestamp();
896 $expiration = $this->getPasswordExpireDate();
897 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
898 if ( $expiration !== null && $expUnix < $now ) {
899 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
905 * Get this user's password expiration date. Since this may be using
906 * the cached User object, we assume that whatever mechanism is setting
907 * the expiration date is also expiring the User cache.
909 * @return string|bool The datestamp of the expiration, or null if not set
911 public function getPasswordExpireDate() {
913 return $this->mPasswordExpires
;
917 * Given unvalidated user input, return a canonical username, or false if
918 * the username is invalid.
919 * @param string $name User input
920 * @param string|bool $validate Type of validation to use:
921 * - false No validation
922 * - 'valid' Valid for batch processes
923 * - 'usable' Valid for batch processes and login
924 * - 'creatable' Valid for batch processes, login and account creation
926 * @throws MWException
927 * @return bool|string
929 public static function getCanonicalName( $name, $validate = 'valid' ) {
930 // Force usernames to capital
932 $name = $wgContLang->ucfirst( $name );
934 # Reject names containing '#'; these will be cleaned up
935 # with title normalisation, but then it's too late to
937 if ( strpos( $name, '#' ) !== false ) {
941 // Clean up name according to title rules,
942 // but only when validation is requested (bug 12654)
943 $t = ( $validate !== false ) ?
944 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
945 // Check for invalid titles
946 if ( is_null( $t ) ) {
950 // Reject various classes of invalid names
952 $name = $wgAuth->getCanonicalName( $t->getText() );
954 switch ( $validate ) {
958 if ( !User
::isValidUserName( $name ) ) {
963 if ( !User
::isUsableName( $name ) ) {
968 if ( !User
::isCreatableName( $name ) ) {
973 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
979 * Count the number of edits of a user
981 * @param int $uid User ID to check
982 * @return int The user's edit count
984 * @deprecated since 1.21 in favour of User::getEditCount
986 public static function edits( $uid ) {
987 wfDeprecated( __METHOD__
, '1.21' );
988 $user = self
::newFromId( $uid );
989 return $user->getEditCount();
993 * Return a random password.
995 * @return string New random password
997 public static function randomPassword() {
998 global $wgMinimalPasswordLength;
999 // Decide the final password length based on our min password length,
1000 // stopping at a minimum of 10 chars.
1001 $length = max( 10, $wgMinimalPasswordLength );
1002 // Multiply by 1.25 to get the number of hex characters we need
1003 $length = $length * 1.25;
1004 // Generate random hex chars
1005 $hex = MWCryptRand
::generateHex( $length );
1006 // Convert from base 16 to base 32 to get a proper password like string
1007 return wfBaseConvert( $hex, 16, 32 );
1011 * Set cached properties to default.
1013 * @note This no longer clears uncached lazy-initialised properties;
1014 * the constructor does that instead.
1016 * @param string|bool $name
1018 public function loadDefaults( $name = false ) {
1020 $passwordFactory = self
::getPasswordFactory();
1023 $this->mName
= $name;
1024 $this->mRealName
= '';
1025 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1026 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1027 $this->mNewpassTime
= null;
1029 $this->mOptionOverrides
= null;
1030 $this->mOptionsLoaded
= false;
1032 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1033 if ( $loggedOut !== null ) {
1034 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1036 $this->mTouched
= '1'; # Allow any pages to be cached
1039 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1040 $this->mEmailAuthenticated
= null;
1041 $this->mEmailToken
= '';
1042 $this->mEmailTokenExpires
= null;
1043 $this->mPasswordExpires
= null;
1044 $this->resetPasswordExpiration( false );
1045 $this->mRegistration
= wfTimestamp( TS_MW
);
1046 $this->mGroups
= array();
1048 Hooks
::run( 'UserLoadDefaults', array( $this, $name ) );
1053 * Return whether an item has been loaded.
1055 * @param string $item Item to check. Current possibilities:
1059 * @param string $all 'all' to check if the whole object has been loaded
1060 * or any other string to check if only the item is available (e.g.
1064 public function isItemLoaded( $item, $all = 'all' ) {
1065 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1066 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1070 * Set that an item has been loaded
1072 * @param string $item
1074 protected function setItemLoaded( $item ) {
1075 if ( is_array( $this->mLoadedItems
) ) {
1076 $this->mLoadedItems
[$item] = true;
1081 * Load user data from the session or login cookie.
1082 * @return bool True if the user is logged in, false otherwise.
1084 private function loadFromSession() {
1086 Hooks
::run( 'UserLoadFromSession', array( $this, &$result ) );
1087 if ( $result !== null ) {
1091 $request = $this->getRequest();
1093 $cookieId = $request->getCookie( 'UserID' );
1094 $sessId = $request->getSessionData( 'wsUserID' );
1096 if ( $cookieId !== null ) {
1097 $sId = intval( $cookieId );
1098 if ( $sessId !== null && $cookieId != $sessId ) {
1099 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1100 cookie user ID ($sId) don't match!" );
1103 $request->setSessionData( 'wsUserID', $sId );
1104 } elseif ( $sessId !== null && $sessId != 0 ) {
1110 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1111 $sName = $request->getSessionData( 'wsUserName' );
1112 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1113 $sName = $request->getCookie( 'UserName' );
1114 $request->setSessionData( 'wsUserName', $sName );
1119 $proposedUser = User
::newFromId( $sId );
1120 if ( !$proposedUser->isLoggedIn() ) {
1125 global $wgBlockDisablesLogin;
1126 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1127 // User blocked and we've disabled blocked user logins
1131 if ( $request->getSessionData( 'wsToken' ) ) {
1133 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1135 } elseif ( $request->getCookie( 'Token' ) ) {
1136 # Get the token from DB/cache and clean it up to remove garbage padding.
1137 # This deals with historical problems with bugs and the default column value.
1138 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1139 // Make comparison in constant time (bug 61346)
1140 $passwordCorrect = strlen( $token )
1141 && hash_equals( $token, $request->getCookie( 'Token' ) );
1144 // No session or persistent login cookie
1148 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1149 $this->loadFromUserObject( $proposedUser );
1150 $request->setSessionData( 'wsToken', $this->mToken
);
1151 wfDebug( "User: logged in from $from\n" );
1154 // Invalid credentials
1155 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1161 * Load user and user_group data from the database.
1162 * $this->mId must be set, this is how the user is identified.
1164 * @param int $flags Supports User::READ_LOCKING
1165 * @return bool True if the user exists, false if the user is anonymous
1167 public function loadFromDatabase( $flags = 0 ) {
1169 $this->mId
= intval( $this->mId
);
1172 if ( !$this->mId
) {
1173 $this->loadDefaults();
1177 $dbr = wfGetDB( DB_MASTER
);
1178 $s = $dbr->selectRow(
1180 self
::selectFields(),
1181 array( 'user_id' => $this->mId
),
1183 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1184 ?
array( 'LOCK IN SHARE MODE' )
1188 Hooks
::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1190 if ( $s !== false ) {
1191 // Initialise user table data
1192 $this->loadFromRow( $s );
1193 $this->mGroups
= null; // deferred
1194 $this->getEditCount(); // revalidation for nulls
1199 $this->loadDefaults();
1205 * Initialize this object from a row from the user table.
1207 * @param stdClass $row Row from the user table to load.
1208 * @param array $data Further user data to load into the object
1210 * user_groups Array with groups out of the user_groups table
1211 * user_properties Array with properties out of the user_properties table
1213 public function loadFromRow( $row, $data = null ) {
1215 $passwordFactory = self
::getPasswordFactory();
1217 $this->mGroups
= null; // deferred
1219 if ( isset( $row->user_name
) ) {
1220 $this->mName
= $row->user_name
;
1221 $this->mFrom
= 'name';
1222 $this->setItemLoaded( 'name' );
1227 if ( isset( $row->user_real_name
) ) {
1228 $this->mRealName
= $row->user_real_name
;
1229 $this->setItemLoaded( 'realname' );
1234 if ( isset( $row->user_id
) ) {
1235 $this->mId
= intval( $row->user_id
);
1236 $this->mFrom
= 'id';
1237 $this->setItemLoaded( 'id' );
1242 if ( isset( $row->user_editcount
) ) {
1243 $this->mEditCount
= $row->user_editcount
;
1248 if ( isset( $row->user_password
) ) {
1249 // Check for *really* old password hashes that don't even have a type
1250 // The old hash format was just an md5 hex hash, with no type information
1251 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1252 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1256 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1257 } catch ( PasswordError
$e ) {
1258 wfDebug( 'Invalid password hash found in database.' );
1259 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1263 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1264 } catch ( PasswordError
$e ) {
1265 wfDebug( 'Invalid password hash found in database.' );
1266 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1269 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1270 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1273 if ( isset( $row->user_email
) ) {
1274 $this->mEmail
= $row->user_email
;
1275 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1276 $this->mToken
= $row->user_token
;
1277 if ( $this->mToken
== '' ) {
1278 $this->mToken
= null;
1280 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1281 $this->mEmailToken
= $row->user_email_token
;
1282 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1283 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1289 $this->mLoadedItems
= true;
1292 if ( is_array( $data ) ) {
1293 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1294 $this->mGroups
= $data['user_groups'];
1296 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1297 $this->loadOptions( $data['user_properties'] );
1303 * Load the data for this user object from another user object.
1307 protected function loadFromUserObject( $user ) {
1309 $user->loadGroups();
1310 $user->loadOptions();
1311 foreach ( self
::$mCacheVars as $var ) {
1312 $this->$var = $user->$var;
1317 * Load the groups from the database if they aren't already loaded.
1319 private function loadGroups() {
1320 if ( is_null( $this->mGroups
) ) {
1321 $dbr = wfGetDB( DB_MASTER
);
1322 $res = $dbr->select( 'user_groups',
1323 array( 'ug_group' ),
1324 array( 'ug_user' => $this->mId
),
1326 $this->mGroups
= array();
1327 foreach ( $res as $row ) {
1328 $this->mGroups
[] = $row->ug_group
;
1334 * Load the user's password hashes from the database
1336 * This is usually called in a scenario where the actual User object was
1337 * loaded from the cache, and then password comparison needs to be performed.
1338 * Password hashes are not stored in memcached.
1342 private function loadPasswords() {
1343 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1344 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1346 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1347 array( 'user_id' => $this->getId() ),
1354 * Add the user to the group if he/she meets given criteria.
1356 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1357 * possible to remove manually via Special:UserRights. In such case it
1358 * will not be re-added automatically. The user will also not lose the
1359 * group if they no longer meet the criteria.
1361 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1363 * @return array Array of groups the user has been promoted to.
1365 * @see $wgAutopromoteOnce
1367 public function addAutopromoteOnceGroups( $event ) {
1368 global $wgAutopromoteOnceLogInRC, $wgAuth;
1370 $toPromote = array();
1371 if ( $this->getId() ) {
1372 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1373 if ( count( $toPromote ) ) {
1374 $oldGroups = $this->getGroups(); // previous groups
1376 foreach ( $toPromote as $group ) {
1377 $this->addGroup( $group );
1379 // update groups in external authentication database
1380 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1382 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1384 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1385 $logEntry->setPerformer( $this );
1386 $logEntry->setTarget( $this->getUserPage() );
1387 $logEntry->setParameters( array(
1388 '4::oldgroups' => $oldGroups,
1389 '5::newgroups' => $newGroups,
1391 $logid = $logEntry->insert();
1392 if ( $wgAutopromoteOnceLogInRC ) {
1393 $logEntry->publish( $logid );
1401 * Clear various cached data stored in this object. The cache of the user table
1402 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1404 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1405 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1407 public function clearInstanceCache( $reloadFrom = false ) {
1408 $this->mNewtalk
= -1;
1409 $this->mDatePreference
= null;
1410 $this->mBlockedby
= -1; # Unset
1411 $this->mHash
= false;
1412 $this->mRights
= null;
1413 $this->mEffectiveGroups
= null;
1414 $this->mImplicitGroups
= null;
1415 $this->mGroups
= null;
1416 $this->mOptions
= null;
1417 $this->mOptionsLoaded
= false;
1418 $this->mEditCount
= null;
1420 if ( $reloadFrom ) {
1421 $this->mLoadedItems
= array();
1422 $this->mFrom
= $reloadFrom;
1427 * Combine the language default options with any site-specific options
1428 * and add the default language variants.
1430 * @return array Array of String options
1432 public static function getDefaultOptions() {
1433 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1435 static $defOpt = null;
1436 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1437 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1438 // mid-request and see that change reflected in the return value of this function.
1439 // Which is insane and would never happen during normal MW operation
1443 $defOpt = $wgDefaultUserOptions;
1444 // Default language setting
1445 $defOpt['language'] = $wgContLang->getCode();
1446 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1447 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1449 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1450 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1452 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1454 Hooks
::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1460 * Get a given default option value.
1462 * @param string $opt Name of option to retrieve
1463 * @return string Default option value
1465 public static function getDefaultOption( $opt ) {
1466 $defOpts = self
::getDefaultOptions();
1467 if ( isset( $defOpts[$opt] ) ) {
1468 return $defOpts[$opt];
1475 * Get blocking information
1476 * @param bool $bFromSlave Whether to check the slave database first.
1477 * To improve performance, non-critical checks are done against slaves.
1478 * Check when actually saving should be done against master.
1480 private function getBlockedStatus( $bFromSlave = true ) {
1481 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1483 if ( -1 != $this->mBlockedby
) {
1487 wfDebug( __METHOD__
. ": checking...\n" );
1489 // Initialize data...
1490 // Otherwise something ends up stomping on $this->mBlockedby when
1491 // things get lazy-loaded later, causing false positive block hits
1492 // due to -1 !== 0. Probably session-related... Nothing should be
1493 // overwriting mBlockedby, surely?
1496 # We only need to worry about passing the IP address to the Block generator if the
1497 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1498 # know which IP address they're actually coming from
1499 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1500 $ip = $this->getRequest()->getIP();
1506 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1509 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1510 && !in_array( $ip, $wgProxyWhitelist )
1513 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1515 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1516 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1517 $block->setTarget( $ip );
1518 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1520 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1521 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1522 $block->setTarget( $ip );
1526 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1527 if ( !$block instanceof Block
1528 && $wgApplyIpBlocksToXff
1530 && !$this->isAllowed( 'proxyunbannable' )
1531 && !in_array( $ip, $wgProxyWhitelist )
1533 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1534 $xff = array_map( 'trim', explode( ',', $xff ) );
1535 $xff = array_diff( $xff, array( $ip ) );
1536 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1537 $block = Block
::chooseBlock( $xffblocks, $xff );
1538 if ( $block instanceof Block
) {
1539 # Mangle the reason to alert the user that the block
1540 # originated from matching the X-Forwarded-For header.
1541 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1545 if ( $block instanceof Block
) {
1546 wfDebug( __METHOD__
. ": Found block.\n" );
1547 $this->mBlock
= $block;
1548 $this->mBlockedby
= $block->getByName();
1549 $this->mBlockreason
= $block->mReason
;
1550 $this->mHideName
= $block->mHideName
;
1551 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1553 $this->mBlockedby
= '';
1554 $this->mHideName
= 0;
1555 $this->mAllowUsertalk
= false;
1559 Hooks
::run( 'GetBlockedStatus', array( &$this ) );
1564 * Whether the given IP is in a DNS blacklist.
1566 * @param string $ip IP to check
1567 * @param bool $checkWhitelist Whether to check the whitelist first
1568 * @return bool True if blacklisted.
1570 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1571 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1573 if ( !$wgEnableDnsBlacklist ) {
1577 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1581 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1585 * Whether the given IP is in a given DNS blacklist.
1587 * @param string $ip IP to check
1588 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1589 * @return bool True if blacklisted.
1591 public function inDnsBlacklist( $ip, $bases ) {
1594 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1595 if ( IP
::isIPv4( $ip ) ) {
1596 // Reverse IP, bug 21255
1597 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1599 foreach ( (array)$bases as $base ) {
1601 // If we have an access key, use that too (ProjectHoneypot, etc.)
1602 if ( is_array( $base ) ) {
1603 if ( count( $base ) >= 2 ) {
1604 // Access key is 1, base URL is 0
1605 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1607 $host = "$ipReversed.{$base[0]}";
1610 $host = "$ipReversed.$base";
1614 $ipList = gethostbynamel( $host );
1617 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1621 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1630 * Check if an IP address is in the local proxy list
1636 public static function isLocallyBlockedProxy( $ip ) {
1637 global $wgProxyList;
1639 if ( !$wgProxyList ) {
1643 if ( !is_array( $wgProxyList ) ) {
1644 // Load from the specified file
1645 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1648 if ( !is_array( $wgProxyList ) ) {
1650 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1652 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1653 // Old-style flipped proxy list
1662 * Is this user subject to rate limiting?
1664 * @return bool True if rate limited
1666 public function isPingLimitable() {
1667 global $wgRateLimitsExcludedIPs;
1668 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1669 // No other good way currently to disable rate limits
1670 // for specific IPs. :P
1671 // But this is a crappy hack and should die.
1674 return !$this->isAllowed( 'noratelimit' );
1678 * Primitive rate limits: enforce maximum actions per time period
1679 * to put a brake on flooding.
1681 * The method generates both a generic profiling point and a per action one
1682 * (suffix being "-$action".
1684 * @note When using a shared cache like memcached, IP-address
1685 * last-hit counters will be shared across wikis.
1687 * @param string $action Action to enforce; 'edit' if unspecified
1688 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1689 * @return bool True if a rate limiter was tripped
1691 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1692 // Call the 'PingLimiter' hook
1694 if ( !Hooks
::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1698 global $wgRateLimits;
1699 if ( !isset( $wgRateLimits[$action] ) ) {
1703 // Some groups shouldn't trigger the ping limiter, ever
1704 if ( !$this->isPingLimitable() ) {
1710 $limits = $wgRateLimits[$action];
1712 $id = $this->getId();
1715 if ( isset( $limits['anon'] ) && $id == 0 ) {
1716 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1719 if ( isset( $limits['user'] ) && $id != 0 ) {
1720 $userLimit = $limits['user'];
1722 if ( $this->isNewbie() ) {
1723 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1724 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1726 if ( isset( $limits['ip'] ) ) {
1727 $ip = $this->getRequest()->getIP();
1728 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1730 if ( isset( $limits['subnet'] ) ) {
1731 $ip = $this->getRequest()->getIP();
1734 if ( IP
::isIPv6( $ip ) ) {
1735 $parts = IP
::parseRange( "$ip/64" );
1736 $subnet = $parts[0];
1737 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1739 $subnet = $matches[1];
1741 if ( $subnet !== false ) {
1742 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1746 // Check for group-specific permissions
1747 // If more than one group applies, use the group with the highest limit
1748 foreach ( $this->getGroups() as $group ) {
1749 if ( isset( $limits[$group] ) ) {
1750 if ( $userLimit === false
1751 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1753 $userLimit = $limits[$group];
1757 // Set the user limit key
1758 if ( $userLimit !== false ) {
1759 list( $max, $period ) = $userLimit;
1760 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1761 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1765 foreach ( $keys as $key => $limit ) {
1766 list( $max, $period ) = $limit;
1767 $summary = "(limit $max in {$period}s)";
1768 $count = $wgMemc->get( $key );
1771 if ( $count >= $max ) {
1772 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1773 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1776 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1779 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1780 if ( $incrBy > 0 ) {
1781 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1784 if ( $incrBy > 0 ) {
1785 $wgMemc->incr( $key, $incrBy );
1793 * Check if user is blocked
1795 * @param bool $bFromSlave Whether to check the slave database instead of
1796 * the master. Hacked from false due to horrible probs on site.
1797 * @return bool True if blocked, false otherwise
1799 public function isBlocked( $bFromSlave = true ) {
1800 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1804 * Get the block affecting the user, or null if the user is not blocked
1806 * @param bool $bFromSlave Whether to check the slave database instead of the master
1807 * @return Block|null
1809 public function getBlock( $bFromSlave = true ) {
1810 $this->getBlockedStatus( $bFromSlave );
1811 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1815 * Check if user is blocked from editing a particular article
1817 * @param Title $title Title to check
1818 * @param bool $bFromSlave Whether to check the slave database instead of the master
1821 public function isBlockedFrom( $title, $bFromSlave = false ) {
1822 global $wgBlockAllowsUTEdit;
1824 $blocked = $this->isBlocked( $bFromSlave );
1825 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1826 // If a user's name is suppressed, they cannot make edits anywhere
1827 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1828 && $title->getNamespace() == NS_USER_TALK
) {
1830 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1833 Hooks
::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1839 * If user is blocked, return the name of the user who placed the block
1840 * @return string Name of blocker
1842 public function blockedBy() {
1843 $this->getBlockedStatus();
1844 return $this->mBlockedby
;
1848 * If user is blocked, return the specified reason for the block
1849 * @return string Blocking reason
1851 public function blockedFor() {
1852 $this->getBlockedStatus();
1853 return $this->mBlockreason
;
1857 * If user is blocked, return the ID for the block
1858 * @return int Block ID
1860 public function getBlockId() {
1861 $this->getBlockedStatus();
1862 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1866 * Check if user is blocked on all wikis.
1867 * Do not use for actual edit permission checks!
1868 * This is intended for quick UI checks.
1870 * @param string $ip IP address, uses current client if none given
1871 * @return bool True if blocked, false otherwise
1873 public function isBlockedGlobally( $ip = '' ) {
1874 if ( $this->mBlockedGlobally
!== null ) {
1875 return $this->mBlockedGlobally
;
1877 // User is already an IP?
1878 if ( IP
::isIPAddress( $this->getName() ) ) {
1879 $ip = $this->getName();
1881 $ip = $this->getRequest()->getIP();
1884 Hooks
::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1885 $this->mBlockedGlobally
= (bool)$blocked;
1886 return $this->mBlockedGlobally
;
1890 * Check if user account is locked
1892 * @return bool True if locked, false otherwise
1894 public function isLocked() {
1895 if ( $this->mLocked
!== null ) {
1896 return $this->mLocked
;
1899 $authUser = $wgAuth->getUserInstance( $this );
1900 $this->mLocked
= (bool)$authUser->isLocked();
1901 return $this->mLocked
;
1905 * Check if user account is hidden
1907 * @return bool True if hidden, false otherwise
1909 public function isHidden() {
1910 if ( $this->mHideName
!== null ) {
1911 return $this->mHideName
;
1913 $this->getBlockedStatus();
1914 if ( !$this->mHideName
) {
1916 $authUser = $wgAuth->getUserInstance( $this );
1917 $this->mHideName
= (bool)$authUser->isHidden();
1919 return $this->mHideName
;
1923 * Get the user's ID.
1924 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1926 public function getId() {
1927 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1928 // Special case, we know the user is anonymous
1930 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1931 // Don't load if this was initialized from an ID
1938 * Set the user and reload all fields according to a given ID
1939 * @param int $v User ID to reload
1941 public function setId( $v ) {
1943 $this->clearInstanceCache( 'id' );
1947 * Get the user name, or the IP of an anonymous user
1948 * @return string User's name or IP address
1950 public function getName() {
1951 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1952 // Special case optimisation
1953 return $this->mName
;
1956 if ( $this->mName
=== false ) {
1958 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1960 return $this->mName
;
1965 * Set the user name.
1967 * This does not reload fields from the database according to the given
1968 * name. Rather, it is used to create a temporary "nonexistent user" for
1969 * later addition to the database. It can also be used to set the IP
1970 * address for an anonymous user to something other than the current
1973 * @note User::newFromName() has roughly the same function, when the named user
1975 * @param string $str New user name to set
1977 public function setName( $str ) {
1979 $this->mName
= $str;
1983 * Get the user's name escaped by underscores.
1984 * @return string Username escaped by underscores.
1986 public function getTitleKey() {
1987 return str_replace( ' ', '_', $this->getName() );
1991 * Check if the user has new messages.
1992 * @return bool True if the user has new messages
1994 public function getNewtalk() {
1997 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1998 if ( $this->mNewtalk
=== -1 ) {
1999 $this->mNewtalk
= false; # reset talk page status
2001 // Check memcached separately for anons, who have no
2002 // entire User object stored in there.
2003 if ( !$this->mId
) {
2004 global $wgDisableAnonTalk;
2005 if ( $wgDisableAnonTalk ) {
2006 // Anon newtalk disabled by configuration.
2007 $this->mNewtalk
= false;
2010 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2011 $newtalk = $wgMemc->get( $key );
2012 if ( strval( $newtalk ) !== '' ) {
2013 $this->mNewtalk
= (bool)$newtalk;
2015 // Since we are caching this, make sure it is up to date by getting it
2017 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2018 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2022 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2026 return (bool)$this->mNewtalk
;
2030 * Return the data needed to construct links for new talk page message
2031 * alerts. If there are new messages, this will return an associative array
2032 * with the following data:
2033 * wiki: The database name of the wiki
2034 * link: Root-relative link to the user's talk page
2035 * rev: The last talk page revision that the user has seen or null. This
2036 * is useful for building diff links.
2037 * If there are no new messages, it returns an empty array.
2038 * @note This function was designed to accomodate multiple talk pages, but
2039 * currently only returns a single link and revision.
2042 public function getNewMessageLinks() {
2044 if ( !Hooks
::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2046 } elseif ( !$this->getNewtalk() ) {
2049 $utp = $this->getTalkPage();
2050 $dbr = wfGetDB( DB_SLAVE
);
2051 // Get the "last viewed rev" timestamp from the oldest message notification
2052 $timestamp = $dbr->selectField( 'user_newtalk',
2053 'MIN(user_last_timestamp)',
2054 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2056 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2057 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2061 * Get the revision ID for the last talk page revision viewed by the talk
2063 * @return int|null Revision ID or null
2065 public function getNewMessageRevisionId() {
2066 $newMessageRevisionId = null;
2067 $newMessageLinks = $this->getNewMessageLinks();
2068 if ( $newMessageLinks ) {
2069 // Note: getNewMessageLinks() never returns more than a single link
2070 // and it is always for the same wiki, but we double-check here in
2071 // case that changes some time in the future.
2072 if ( count( $newMessageLinks ) === 1
2073 && $newMessageLinks[0]['wiki'] === wfWikiID()
2074 && $newMessageLinks[0]['rev']
2076 $newMessageRevision = $newMessageLinks[0]['rev'];
2077 $newMessageRevisionId = $newMessageRevision->getId();
2080 return $newMessageRevisionId;
2084 * Internal uncached check for new messages
2087 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2088 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2089 * @param bool $fromMaster True to fetch from the master, false for a slave
2090 * @return bool True if the user has new messages
2092 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2093 if ( $fromMaster ) {
2094 $db = wfGetDB( DB_MASTER
);
2096 $db = wfGetDB( DB_SLAVE
);
2098 $ok = $db->selectField( 'user_newtalk', $field,
2099 array( $field => $id ), __METHOD__
);
2100 return $ok !== false;
2104 * Add or update the new messages flag
2105 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2106 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2107 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2108 * @return bool True if successful, false otherwise
2110 protected function updateNewtalk( $field, $id, $curRev = null ) {
2111 // Get timestamp of the talk page revision prior to the current one
2112 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2113 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2114 // Mark the user as having new messages since this revision
2115 $dbw = wfGetDB( DB_MASTER
);
2116 $dbw->insert( 'user_newtalk',
2117 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2120 if ( $dbw->affectedRows() ) {
2121 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2124 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2130 * Clear the new messages flag for the given user
2131 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2132 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2133 * @return bool True if successful, false otherwise
2135 protected function deleteNewtalk( $field, $id ) {
2136 $dbw = wfGetDB( DB_MASTER
);
2137 $dbw->delete( 'user_newtalk',
2138 array( $field => $id ),
2140 if ( $dbw->affectedRows() ) {
2141 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2144 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2150 * Update the 'You have new messages!' status.
2151 * @param bool $val Whether the user has new messages
2152 * @param Revision $curRev New, as yet unseen revision of the user talk
2153 * page. Ignored if null or !$val.
2155 public function setNewtalk( $val, $curRev = null ) {
2156 if ( wfReadOnly() ) {
2161 $this->mNewtalk
= $val;
2163 if ( $this->isAnon() ) {
2165 $id = $this->getName();
2168 $id = $this->getId();
2173 $changed = $this->updateNewtalk( $field, $id, $curRev );
2175 $changed = $this->deleteNewtalk( $field, $id );
2178 if ( $this->isAnon() ) {
2179 // Anons have a separate memcached space, since
2180 // user records aren't kept for them.
2181 $key = wfMemcKey( 'newtalk', 'ip', $id );
2182 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2185 $this->invalidateCache();
2190 * Generate a current or new-future timestamp to be stored in the
2191 * user_touched field when we update things.
2192 * @return string Timestamp in TS_MW format
2194 private static function newTouchedTimestamp() {
2195 global $wgClockSkewFudge;
2196 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2200 * Clear user data from memcached.
2201 * Use after applying fun updates to the database; caller's
2202 * responsibility to update user_touched if appropriate.
2204 * Called implicitly from invalidateCache() and saveSettings().
2206 public function clearSharedCache() {
2210 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2215 * Immediately touch the user data cache for this account.
2216 * Updates user_touched field, and removes account data from memcached
2217 * for reload on the next hit.
2219 public function invalidateCache() {
2220 if ( wfReadOnly() ) {
2225 $this->mTouched
= self
::newTouchedTimestamp();
2227 $dbw = wfGetDB( DB_MASTER
);
2228 $userid = $this->mId
;
2229 $touched = $this->mTouched
;
2230 $method = __METHOD__
;
2231 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2232 // Prevent contention slams by checking user_touched first
2233 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2234 $needsPurge = $dbw->selectField( 'user', '1',
2235 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2236 if ( $needsPurge ) {
2237 $dbw->update( 'user',
2238 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2239 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2244 $this->clearSharedCache();
2249 * Validate the cache for this account.
2250 * @param string $timestamp A timestamp in TS_MW format
2253 public function validateCache( $timestamp ) {
2255 return ( $timestamp >= $this->mTouched
);
2259 * Get the user touched timestamp
2260 * @return string Timestamp
2262 public function getTouched() {
2264 return $this->mTouched
;
2271 public function getPassword() {
2272 $this->loadPasswords();
2274 return $this->mPassword
;
2281 public function getTemporaryPassword() {
2282 $this->loadPasswords();
2284 return $this->mNewpassword
;
2288 * Set the password and reset the random token.
2289 * Calls through to authentication plugin if necessary;
2290 * will have no effect if the auth plugin refuses to
2291 * pass the change through or if the legal password
2294 * As a special case, setting the password to null
2295 * wipes it, so the account cannot be logged in until
2296 * a new password is set, for instance via e-mail.
2298 * @param string $str New password to set
2299 * @throws PasswordError On failure
2303 public function setPassword( $str ) {
2306 $this->loadPasswords();
2308 if ( $str !== null ) {
2309 if ( !$wgAuth->allowPasswordChange() ) {
2310 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2313 if ( !$this->isValidPassword( $str ) ) {
2314 global $wgMinimalPasswordLength;
2315 $valid = $this->getPasswordValidity( $str );
2316 if ( is_array( $valid ) ) {
2317 $message = array_shift( $valid );
2321 $params = array( $wgMinimalPasswordLength );
2323 throw new PasswordError( wfMessage( $message, $params )->text() );
2327 if ( !$wgAuth->setPassword( $this, $str ) ) {
2328 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2331 $this->setInternalPassword( $str );
2337 * Set the password and reset the random token unconditionally.
2339 * @param string|null $str New password to set or null to set an invalid
2340 * password hash meaning that the user will not be able to log in
2341 * through the web interface.
2343 public function setInternalPassword( $str ) {
2346 $passwordFactory = self
::getPasswordFactory();
2347 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2349 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2350 $this->mNewpassTime
= null;
2354 * Get the user's current token.
2355 * @param bool $forceCreation Force the generation of a new token if the
2356 * user doesn't have one (default=true for backwards compatibility).
2357 * @return string Token
2359 public function getToken( $forceCreation = true ) {
2361 if ( !$this->mToken
&& $forceCreation ) {
2364 return $this->mToken
;
2368 * Set the random token (used for persistent authentication)
2369 * Called from loadDefaults() among other places.
2371 * @param string|bool $token If specified, set the token to this value
2373 public function setToken( $token = false ) {
2376 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2378 $this->mToken
= $token;
2383 * Set the password for a password reminder or new account email
2385 * @param string $str New password to set or null to set an invalid
2386 * password hash meaning that the user will not be able to use it
2387 * @param bool $throttle If true, reset the throttle timestamp to the present
2389 public function setNewpassword( $str, $throttle = true ) {
2390 $this->loadPasswords();
2392 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2393 if ( $str === null ) {
2394 $this->mNewpassTime
= null;
2395 } elseif ( $throttle ) {
2396 $this->mNewpassTime
= wfTimestampNow();
2401 * Has password reminder email been sent within the last
2402 * $wgPasswordReminderResendTime hours?
2405 public function isPasswordReminderThrottled() {
2406 global $wgPasswordReminderResendTime;
2408 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2411 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2412 return time() < $expiry;
2416 * Get the user's e-mail address
2417 * @return string User's email address
2419 public function getEmail() {
2421 Hooks
::run( 'UserGetEmail', array( $this, &$this->mEmail
) );
2422 return $this->mEmail
;
2426 * Get the timestamp of the user's e-mail authentication
2427 * @return string TS_MW timestamp
2429 public function getEmailAuthenticationTimestamp() {
2431 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2432 return $this->mEmailAuthenticated
;
2436 * Set the user's e-mail address
2437 * @param string $str New e-mail address
2439 public function setEmail( $str ) {
2441 if ( $str == $this->mEmail
) {
2444 $this->invalidateEmail();
2445 $this->mEmail
= $str;
2446 Hooks
::run( 'UserSetEmail', array( $this, &$this->mEmail
) );
2450 * Set the user's e-mail address and a confirmation mail if needed.
2453 * @param string $str New e-mail address
2456 public function setEmailWithConfirmation( $str ) {
2457 global $wgEnableEmail, $wgEmailAuthentication;
2459 if ( !$wgEnableEmail ) {
2460 return Status
::newFatal( 'emaildisabled' );
2463 $oldaddr = $this->getEmail();
2464 if ( $str === $oldaddr ) {
2465 return Status
::newGood( true );
2468 $this->setEmail( $str );
2470 if ( $str !== '' && $wgEmailAuthentication ) {
2471 // Send a confirmation request to the new address if needed
2472 $type = $oldaddr != '' ?
'changed' : 'set';
2473 $result = $this->sendConfirmationMail( $type );
2474 if ( $result->isGood() ) {
2475 // Say to the caller that a confirmation mail has been sent
2476 $result->value
= 'eauth';
2479 $result = Status
::newGood( true );
2486 * Get the user's real name
2487 * @return string User's real name
2489 public function getRealName() {
2490 if ( !$this->isItemLoaded( 'realname' ) ) {
2494 return $this->mRealName
;
2498 * Set the user's real name
2499 * @param string $str New real name
2501 public function setRealName( $str ) {
2503 $this->mRealName
= $str;
2507 * Get the user's current setting for a given option.
2509 * @param string $oname The option to check
2510 * @param string $defaultOverride A default value returned if the option does not exist
2511 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2512 * @return string User's current value for the option
2513 * @see getBoolOption()
2514 * @see getIntOption()
2516 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2517 global $wgHiddenPrefs;
2518 $this->loadOptions();
2520 # We want 'disabled' preferences to always behave as the default value for
2521 # users, even if they have set the option explicitly in their settings (ie they
2522 # set it, and then it was disabled removing their ability to change it). But
2523 # we don't want to erase the preferences in the database in case the preference
2524 # is re-enabled again. So don't touch $mOptions, just override the returned value
2525 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2526 return self
::getDefaultOption( $oname );
2529 if ( array_key_exists( $oname, $this->mOptions
) ) {
2530 return $this->mOptions
[$oname];
2532 return $defaultOverride;
2537 * Get all user's options
2539 * @param int $flags Bitwise combination of:
2540 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2541 * to the default value. (Since 1.25)
2544 public function getOptions( $flags = 0 ) {
2545 global $wgHiddenPrefs;
2546 $this->loadOptions();
2547 $options = $this->mOptions
;
2549 # We want 'disabled' preferences to always behave as the default value for
2550 # users, even if they have set the option explicitly in their settings (ie they
2551 # set it, and then it was disabled removing their ability to change it). But
2552 # we don't want to erase the preferences in the database in case the preference
2553 # is re-enabled again. So don't touch $mOptions, just override the returned value
2554 foreach ( $wgHiddenPrefs as $pref ) {
2555 $default = self
::getDefaultOption( $pref );
2556 if ( $default !== null ) {
2557 $options[$pref] = $default;
2561 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2562 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2569 * Get the user's current setting for a given option, as a boolean value.
2571 * @param string $oname The option to check
2572 * @return bool User's current value for the option
2575 public function getBoolOption( $oname ) {
2576 return (bool)$this->getOption( $oname );
2580 * Get the user's current setting for a given option, as an integer value.
2582 * @param string $oname The option to check
2583 * @param int $defaultOverride A default value returned if the option does not exist
2584 * @return int User's current value for the option
2587 public function getIntOption( $oname, $defaultOverride = 0 ) {
2588 $val = $this->getOption( $oname );
2590 $val = $defaultOverride;
2592 return intval( $val );
2596 * Set the given option for a user.
2598 * You need to call saveSettings() to actually write to the database.
2600 * @param string $oname The option to set
2601 * @param mixed $val New value to set
2603 public function setOption( $oname, $val ) {
2604 $this->loadOptions();
2606 // Explicitly NULL values should refer to defaults
2607 if ( is_null( $val ) ) {
2608 $val = self
::getDefaultOption( $oname );
2611 $this->mOptions
[$oname] = $val;
2615 * Get a token stored in the preferences (like the watchlist one),
2616 * resetting it if it's empty (and saving changes).
2618 * @param string $oname The option name to retrieve the token from
2619 * @return string|bool User's current value for the option, or false if this option is disabled.
2620 * @see resetTokenFromOption()
2623 public function getTokenFromOption( $oname ) {
2624 global $wgHiddenPrefs;
2625 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2629 $token = $this->getOption( $oname );
2631 $token = $this->resetTokenFromOption( $oname );
2632 $this->saveSettings();
2638 * Reset a token stored in the preferences (like the watchlist one).
2639 * *Does not* save user's preferences (similarly to setOption()).
2641 * @param string $oname The option name to reset the token in
2642 * @return string|bool New token value, or false if this option is disabled.
2643 * @see getTokenFromOption()
2646 public function resetTokenFromOption( $oname ) {
2647 global $wgHiddenPrefs;
2648 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2652 $token = MWCryptRand
::generateHex( 40 );
2653 $this->setOption( $oname, $token );
2658 * Return a list of the types of user options currently returned by
2659 * User::getOptionKinds().
2661 * Currently, the option kinds are:
2662 * - 'registered' - preferences which are registered in core MediaWiki or
2663 * by extensions using the UserGetDefaultOptions hook.
2664 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2665 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2666 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2667 * be used by user scripts.
2668 * - 'special' - "preferences" that are not accessible via User::getOptions
2669 * or User::setOptions.
2670 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2671 * These are usually legacy options, removed in newer versions.
2673 * The API (and possibly others) use this function to determine the possible
2674 * option types for validation purposes, so make sure to update this when a
2675 * new option kind is added.
2677 * @see User::getOptionKinds
2678 * @return array Option kinds
2680 public static function listOptionKinds() {
2683 'registered-multiselect',
2684 'registered-checkmatrix',
2692 * Return an associative array mapping preferences keys to the kind of a preference they're
2693 * used for. Different kinds are handled differently when setting or reading preferences.
2695 * See User::listOptionKinds for the list of valid option types that can be provided.
2697 * @see User::listOptionKinds
2698 * @param IContextSource $context
2699 * @param array $options Assoc. array with options keys to check as keys.
2700 * Defaults to $this->mOptions.
2701 * @return array The key => kind mapping data
2703 public function getOptionKinds( IContextSource
$context, $options = null ) {
2704 $this->loadOptions();
2705 if ( $options === null ) {
2706 $options = $this->mOptions
;
2709 $prefs = Preferences
::getPreferences( $this, $context );
2712 // Pull out the "special" options, so they don't get converted as
2713 // multiselect or checkmatrix.
2714 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2715 foreach ( $specialOptions as $name => $value ) {
2716 unset( $prefs[$name] );
2719 // Multiselect and checkmatrix options are stored in the database with
2720 // one key per option, each having a boolean value. Extract those keys.
2721 $multiselectOptions = array();
2722 foreach ( $prefs as $name => $info ) {
2723 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2724 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2725 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2726 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2728 foreach ( $opts as $value ) {
2729 $multiselectOptions["$prefix$value"] = true;
2732 unset( $prefs[$name] );
2735 $checkmatrixOptions = array();
2736 foreach ( $prefs as $name => $info ) {
2737 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2738 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2739 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2740 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2741 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2743 foreach ( $columns as $column ) {
2744 foreach ( $rows as $row ) {
2745 $checkmatrixOptions["$prefix$column-$row"] = true;
2749 unset( $prefs[$name] );
2753 // $value is ignored
2754 foreach ( $options as $key => $value ) {
2755 if ( isset( $prefs[$key] ) ) {
2756 $mapping[$key] = 'registered';
2757 } elseif ( isset( $multiselectOptions[$key] ) ) {
2758 $mapping[$key] = 'registered-multiselect';
2759 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2760 $mapping[$key] = 'registered-checkmatrix';
2761 } elseif ( isset( $specialOptions[$key] ) ) {
2762 $mapping[$key] = 'special';
2763 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2764 $mapping[$key] = 'userjs';
2766 $mapping[$key] = 'unused';
2774 * Reset certain (or all) options to the site defaults
2776 * The optional parameter determines which kinds of preferences will be reset.
2777 * Supported values are everything that can be reported by getOptionKinds()
2778 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2780 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2781 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2782 * for backwards-compatibility.
2783 * @param IContextSource|null $context Context source used when $resetKinds
2784 * does not contain 'all', passed to getOptionKinds().
2785 * Defaults to RequestContext::getMain() when null.
2787 public function resetOptions(
2788 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2789 IContextSource
$context = null
2792 $defaultOptions = self
::getDefaultOptions();
2794 if ( !is_array( $resetKinds ) ) {
2795 $resetKinds = array( $resetKinds );
2798 if ( in_array( 'all', $resetKinds ) ) {
2799 $newOptions = $defaultOptions;
2801 if ( $context === null ) {
2802 $context = RequestContext
::getMain();
2805 $optionKinds = $this->getOptionKinds( $context );
2806 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2807 $newOptions = array();
2809 // Use default values for the options that should be deleted, and
2810 // copy old values for the ones that shouldn't.
2811 foreach ( $this->mOptions
as $key => $value ) {
2812 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2813 if ( array_key_exists( $key, $defaultOptions ) ) {
2814 $newOptions[$key] = $defaultOptions[$key];
2817 $newOptions[$key] = $value;
2822 Hooks
::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2824 $this->mOptions
= $newOptions;
2825 $this->mOptionsLoaded
= true;
2829 * Get the user's preferred date format.
2830 * @return string User's preferred date format
2832 public function getDatePreference() {
2833 // Important migration for old data rows
2834 if ( is_null( $this->mDatePreference
) ) {
2836 $value = $this->getOption( 'date' );
2837 $map = $wgLang->getDatePreferenceMigrationMap();
2838 if ( isset( $map[$value] ) ) {
2839 $value = $map[$value];
2841 $this->mDatePreference
= $value;
2843 return $this->mDatePreference
;
2847 * Determine based on the wiki configuration and the user's options,
2848 * whether this user must be over HTTPS no matter what.
2852 public function requiresHTTPS() {
2853 global $wgSecureLogin;
2854 if ( !$wgSecureLogin ) {
2857 $https = $this->getBoolOption( 'prefershttps' );
2858 Hooks
::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2860 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2867 * Get the user preferred stub threshold
2871 public function getStubThreshold() {
2872 global $wgMaxArticleSize; # Maximum article size, in Kb
2873 $threshold = $this->getIntOption( 'stubthreshold' );
2874 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2875 // If they have set an impossible value, disable the preference
2876 // so we can use the parser cache again.
2883 * Get the permissions this user has.
2884 * @return array Array of String permission names
2886 public function getRights() {
2887 if ( is_null( $this->mRights
) ) {
2888 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2889 Hooks
::run( 'UserGetRights', array( $this, &$this->mRights
) );
2890 // Force reindexation of rights when a hook has unset one of them
2891 $this->mRights
= array_values( array_unique( $this->mRights
) );
2893 return $this->mRights
;
2897 * Get the list of explicit group memberships this user has.
2898 * The implicit * and user groups are not included.
2899 * @return array Array of String internal group names
2901 public function getGroups() {
2903 $this->loadGroups();
2904 return $this->mGroups
;
2908 * Get the list of implicit group memberships this user has.
2909 * This includes all explicit groups, plus 'user' if logged in,
2910 * '*' for all accounts, and autopromoted groups
2911 * @param bool $recache Whether to avoid the cache
2912 * @return array Array of String internal group names
2914 public function getEffectiveGroups( $recache = false ) {
2915 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2916 $this->mEffectiveGroups
= array_unique( array_merge(
2917 $this->getGroups(), // explicit groups
2918 $this->getAutomaticGroups( $recache ) // implicit groups
2920 // Hook for additional groups
2921 Hooks
::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2922 // Force reindexation of groups when a hook has unset one of them
2923 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2925 return $this->mEffectiveGroups
;
2929 * Get the list of implicit group memberships this user has.
2930 * This includes 'user' if logged in, '*' for all accounts,
2931 * and autopromoted groups
2932 * @param bool $recache Whether to avoid the cache
2933 * @return array Array of String internal group names
2935 public function getAutomaticGroups( $recache = false ) {
2936 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2937 $this->mImplicitGroups
= array( '*' );
2938 if ( $this->getId() ) {
2939 $this->mImplicitGroups
[] = 'user';
2941 $this->mImplicitGroups
= array_unique( array_merge(
2942 $this->mImplicitGroups
,
2943 Autopromote
::getAutopromoteGroups( $this )
2947 // Assure data consistency with rights/groups,
2948 // as getEffectiveGroups() depends on this function
2949 $this->mEffectiveGroups
= null;
2952 return $this->mImplicitGroups
;
2956 * Returns the groups the user has belonged to.
2958 * The user may still belong to the returned groups. Compare with getGroups().
2960 * The function will not return groups the user had belonged to before MW 1.17
2962 * @return array Names of the groups the user has belonged to.
2964 public function getFormerGroups() {
2965 if ( is_null( $this->mFormerGroups
) ) {
2966 $dbr = wfGetDB( DB_MASTER
);
2967 $res = $dbr->select( 'user_former_groups',
2968 array( 'ufg_group' ),
2969 array( 'ufg_user' => $this->mId
),
2971 $this->mFormerGroups
= array();
2972 foreach ( $res as $row ) {
2973 $this->mFormerGroups
[] = $row->ufg_group
;
2976 return $this->mFormerGroups
;
2980 * Get the user's edit count.
2981 * @return int|null Null for anonymous users
2983 public function getEditCount() {
2984 if ( !$this->getId() ) {
2988 if ( $this->mEditCount
=== null ) {
2989 /* Populate the count, if it has not been populated yet */
2990 $dbr = wfGetDB( DB_SLAVE
);
2991 // check if the user_editcount field has been initialized
2992 $count = $dbr->selectField(
2993 'user', 'user_editcount',
2994 array( 'user_id' => $this->mId
),
2998 if ( $count === null ) {
2999 // it has not been initialized. do so.
3000 $count = $this->initEditCount();
3002 $this->mEditCount
= $count;
3004 return (int)$this->mEditCount
;
3008 * Add the user to the given group.
3009 * This takes immediate effect.
3010 * @param string $group Name of the group to add
3012 public function addGroup( $group ) {
3013 if ( Hooks
::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3014 $dbw = wfGetDB( DB_MASTER
);
3015 if ( $this->getId() ) {
3016 $dbw->insert( 'user_groups',
3018 'ug_user' => $this->getID(),
3019 'ug_group' => $group,
3022 array( 'IGNORE' ) );
3025 $this->loadGroups();
3026 $this->mGroups
[] = $group;
3027 // In case loadGroups was not called before, we now have the right twice.
3028 // Get rid of the duplicate.
3029 $this->mGroups
= array_unique( $this->mGroups
);
3031 // Refresh the groups caches, and clear the rights cache so it will be
3032 // refreshed on the next call to $this->getRights().
3033 $this->getEffectiveGroups( true );
3034 $this->mRights
= null;
3036 $this->invalidateCache();
3040 * Remove the user from the given group.
3041 * This takes immediate effect.
3042 * @param string $group Name of the group to remove
3044 public function removeGroup( $group ) {
3046 if ( Hooks
::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3047 $dbw = wfGetDB( DB_MASTER
);
3048 $dbw->delete( 'user_groups',
3050 'ug_user' => $this->getID(),
3051 'ug_group' => $group,
3053 // Remember that the user was in this group
3054 $dbw->insert( 'user_former_groups',
3056 'ufg_user' => $this->getID(),
3057 'ufg_group' => $group,
3060 array( 'IGNORE' ) );
3062 $this->loadGroups();
3063 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3065 // Refresh the groups caches, and clear the rights cache so it will be
3066 // refreshed on the next call to $this->getRights().
3067 $this->getEffectiveGroups( true );
3068 $this->mRights
= null;
3070 $this->invalidateCache();
3074 * Get whether the user is logged in
3077 public function isLoggedIn() {
3078 return $this->getID() != 0;
3082 * Get whether the user is anonymous
3085 public function isAnon() {
3086 return !$this->isLoggedIn();
3090 * Check if user is allowed to access a feature / make an action
3092 * @param string $permissions,... Permissions to test
3093 * @return bool True if user is allowed to perform *any* of the given actions
3095 public function isAllowedAny( /*...*/ ) {
3096 $permissions = func_get_args();
3097 foreach ( $permissions as $permission ) {
3098 if ( $this->isAllowed( $permission ) ) {
3107 * @param string $permissions,... Permissions to test
3108 * @return bool True if the user is allowed to perform *all* of the given actions
3110 public function isAllowedAll( /*...*/ ) {
3111 $permissions = func_get_args();
3112 foreach ( $permissions as $permission ) {
3113 if ( !$this->isAllowed( $permission ) ) {
3121 * Internal mechanics of testing a permission
3122 * @param string $action
3125 public function isAllowed( $action = '' ) {
3126 if ( $action === '' ) {
3127 return true; // In the spirit of DWIM
3129 // Patrolling may not be enabled
3130 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3131 global $wgUseRCPatrol, $wgUseNPPatrol;
3132 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3136 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3137 // by misconfiguration: 0 == 'foo'
3138 return in_array( $action, $this->getRights(), true );
3142 * Check whether to enable recent changes patrol features for this user
3143 * @return bool True or false
3145 public function useRCPatrol() {
3146 global $wgUseRCPatrol;
3147 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3151 * Check whether to enable new pages patrol features for this user
3152 * @return bool True or false
3154 public function useNPPatrol() {
3155 global $wgUseRCPatrol, $wgUseNPPatrol;
3157 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3158 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3163 * Get the WebRequest object to use with this object
3165 * @return WebRequest
3167 public function getRequest() {
3168 if ( $this->mRequest
) {
3169 return $this->mRequest
;
3177 * Get the current skin, loading it if required
3178 * @return Skin The current skin
3179 * @todo FIXME: Need to check the old failback system [AV]
3180 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3182 public function getSkin() {
3183 wfDeprecated( __METHOD__
, '1.18' );
3184 return RequestContext
::getMain()->getSkin();
3188 * Get a WatchedItem for this user and $title.
3190 * @since 1.22 $checkRights parameter added
3191 * @param Title $title
3192 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3193 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3194 * @return WatchedItem
3196 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3197 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3199 if ( isset( $this->mWatchedItems
[$key] ) ) {
3200 return $this->mWatchedItems
[$key];
3203 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3204 $this->mWatchedItems
= array();
3207 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3208 return $this->mWatchedItems
[$key];
3212 * Check the watched status of an article.
3213 * @since 1.22 $checkRights parameter added
3214 * @param Title $title Title of the article to look at
3215 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3216 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3219 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3220 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3225 * @since 1.22 $checkRights parameter added
3226 * @param Title $title Title of the article to look at
3227 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3228 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3230 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3231 $this->getWatchedItem( $title, $checkRights )->addWatch();
3232 $this->invalidateCache();
3236 * Stop watching an article.
3237 * @since 1.22 $checkRights parameter added
3238 * @param Title $title Title of the article to look at
3239 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3240 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3242 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3243 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3244 $this->invalidateCache();
3248 * Clear the user's notification timestamp for the given title.
3249 * If e-notif e-mails are on, they will receive notification mails on
3250 * the next change of the page if it's watched etc.
3251 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3252 * @param Title $title Title of the article to look at
3253 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3255 public function clearNotification( &$title, $oldid = 0 ) {
3256 global $wgUseEnotif, $wgShowUpdatedMarker;
3258 // Do nothing if the database is locked to writes
3259 if ( wfReadOnly() ) {
3263 // Do nothing if not allowed to edit the watchlist
3264 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3268 // If we're working on user's talk page, we should update the talk page message indicator
3269 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3270 if ( !Hooks
::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3274 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3276 if ( !$oldid ||
!$nextid ) {
3277 // If we're looking at the latest revision, we should definitely clear it
3278 $this->setNewtalk( false );
3280 // Otherwise we should update its revision, if it's present
3281 if ( $this->getNewtalk() ) {
3282 // Naturally the other one won't clear by itself
3283 $this->setNewtalk( false );
3284 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3289 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3293 if ( $this->isAnon() ) {
3294 // Nothing else to do...
3298 // Only update the timestamp if the page is being watched.
3299 // The query to find out if it is watched is cached both in memcached and per-invocation,
3300 // and when it does have to be executed, it can be on a slave
3301 // If this is the user's newtalk page, we always update the timestamp
3303 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3307 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3311 * Resets all of the given user's page-change notification timestamps.
3312 * If e-notif e-mails are on, they will receive notification mails on
3313 * the next change of any watched page.
3314 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3316 public function clearAllNotifications() {
3317 if ( wfReadOnly() ) {
3321 // Do nothing if not allowed to edit the watchlist
3322 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3326 global $wgUseEnotif, $wgShowUpdatedMarker;
3327 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3328 $this->setNewtalk( false );
3331 $id = $this->getId();
3333 $dbw = wfGetDB( DB_MASTER
);
3334 $dbw->update( 'watchlist',
3335 array( /* SET */ 'wl_notificationtimestamp' => null ),
3336 array( /* WHERE */ 'wl_user' => $id ),
3339 // We also need to clear here the "you have new message" notification for the own user_talk page;
3340 // it's cleared one page view later in WikiPage::doViewUpdates().
3345 * Set a cookie on the user's client. Wrapper for
3346 * WebResponse::setCookie
3347 * @param string $name Name of the cookie to set
3348 * @param string $value Value to set
3349 * @param int $exp Expiration time, as a UNIX time value;
3350 * if 0 or not specified, use the default $wgCookieExpiration
3351 * @param bool $secure
3352 * true: Force setting the secure attribute when setting the cookie
3353 * false: Force NOT setting the secure attribute when setting the cookie
3354 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3355 * @param array $params Array of options sent passed to WebResponse::setcookie()
3357 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3358 $params['secure'] = $secure;
3359 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3363 * Clear a cookie on the user's client
3364 * @param string $name Name of the cookie to clear
3365 * @param bool $secure
3366 * true: Force setting the secure attribute when setting the cookie
3367 * false: Force NOT setting the secure attribute when setting the cookie
3368 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3369 * @param array $params Array of options sent passed to WebResponse::setcookie()
3371 protected function clearCookie( $name, $secure = null, $params = array() ) {
3372 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3376 * Set the default cookies for this session on the user's client.
3378 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3380 * @param bool $secure Whether to force secure/insecure cookies or use default
3381 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3383 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3384 if ( $request === null ) {
3385 $request = $this->getRequest();
3389 if ( 0 == $this->mId
) {
3392 if ( !$this->mToken
) {
3393 // When token is empty or NULL generate a new one and then save it to the database
3394 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3395 // Simply by setting every cell in the user_token column to NULL and letting them be
3396 // regenerated as users log back into the wiki.
3398 $this->saveSettings();
3401 'wsUserID' => $this->mId
,
3402 'wsToken' => $this->mToken
,
3403 'wsUserName' => $this->getName()
3406 'UserID' => $this->mId
,
3407 'UserName' => $this->getName(),
3409 if ( $rememberMe ) {
3410 $cookies['Token'] = $this->mToken
;
3412 $cookies['Token'] = false;
3415 Hooks
::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3417 foreach ( $session as $name => $value ) {
3418 $request->setSessionData( $name, $value );
3420 foreach ( $cookies as $name => $value ) {
3421 if ( $value === false ) {
3422 $this->clearCookie( $name );
3424 $this->setCookie( $name, $value, 0, $secure );
3429 * If wpStickHTTPS was selected, also set an insecure cookie that
3430 * will cause the site to redirect the user to HTTPS, if they access
3431 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3432 * as the one set by centralauth (bug 53538). Also set it to session, or
3433 * standard time setting, based on if rememberme was set.
3435 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3439 $rememberMe ?
0 : null,
3441 array( 'prefix' => '' ) // no prefix
3447 * Log this user out.
3449 public function logout() {
3450 if ( Hooks
::run( 'UserLogout', array( &$this ) ) ) {
3456 * Clear the user's cookies and session, and reset the instance cache.
3459 public function doLogout() {
3460 $this->clearInstanceCache( 'defaults' );
3462 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3464 $this->clearCookie( 'UserID' );
3465 $this->clearCookie( 'Token' );
3466 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3468 // Remember when user logged out, to prevent seeing cached pages
3469 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3473 * Save this user's settings into the database.
3474 * @todo Only rarely do all these fields need to be set!
3476 public function saveSettings() {
3480 $this->loadPasswords();
3481 if ( wfReadOnly() ) {
3484 if ( 0 == $this->mId
) {
3488 $this->mTouched
= self
::newTouchedTimestamp();
3489 if ( !$wgAuth->allowSetLocalPassword() ) {
3490 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3493 $dbw = wfGetDB( DB_MASTER
);
3494 $dbw->update( 'user',
3496 'user_name' => $this->mName
,
3497 'user_password' => $this->mPassword
->toString(),
3498 'user_newpassword' => $this->mNewpassword
->toString(),
3499 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3500 'user_real_name' => $this->mRealName
,
3501 'user_email' => $this->mEmail
,
3502 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3503 'user_touched' => $dbw->timestamp( $this->mTouched
),
3504 'user_token' => strval( $this->mToken
),
3505 'user_email_token' => $this->mEmailToken
,
3506 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3507 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3508 ), array( /* WHERE */
3509 'user_id' => $this->mId
3513 $this->saveOptions();
3515 Hooks
::run( 'UserSaveSettings', array( $this ) );
3516 $this->clearSharedCache();
3517 $this->getUserPage()->invalidateCache();
3521 * If only this user's username is known, and it exists, return the user ID.
3524 public function idForName() {
3525 $s = trim( $this->getName() );
3530 $dbr = wfGetDB( DB_SLAVE
);
3531 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3532 if ( $id === false ) {
3539 * Add a user to the database, return the user object
3541 * @param string $name Username to add
3542 * @param array $params Array of Strings Non-default parameters to save to
3543 * the database as user_* fields:
3544 * - password: The user's password hash. Password logins will be disabled
3545 * if this is omitted.
3546 * - newpassword: Hash for a temporary password that has been mailed to
3548 * - email: The user's email address.
3549 * - email_authenticated: The email authentication timestamp.
3550 * - real_name: The user's real name.
3551 * - options: An associative array of non-default options.
3552 * - token: Random authentication token. Do not set.
3553 * - registration: Registration timestamp. Do not set.
3555 * @return User|null User object, or null if the username already exists.
3557 public static function createNew( $name, $params = array() ) {
3560 $user->loadPasswords();
3561 $user->setToken(); // init token
3562 if ( isset( $params['options'] ) ) {
3563 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3564 unset( $params['options'] );
3566 $dbw = wfGetDB( DB_MASTER
);
3567 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3570 'user_id' => $seqVal,
3571 'user_name' => $name,
3572 'user_password' => $user->mPassword
->toString(),
3573 'user_newpassword' => $user->mNewpassword
->toString(),
3574 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3575 'user_email' => $user->mEmail
,
3576 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3577 'user_real_name' => $user->mRealName
,
3578 'user_token' => strval( $user->mToken
),
3579 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3580 'user_editcount' => 0,
3581 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3583 foreach ( $params as $name => $value ) {
3584 $fields["user_$name"] = $value;
3586 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3587 if ( $dbw->affectedRows() ) {
3588 $newUser = User
::newFromId( $dbw->insertId() );
3596 * Add this existing user object to the database. If the user already
3597 * exists, a fatal status object is returned, and the user object is
3598 * initialised with the data from the database.
3600 * Previously, this function generated a DB error due to a key conflict
3601 * if the user already existed. Many extension callers use this function
3602 * in code along the lines of:
3604 * $user = User::newFromName( $name );
3605 * if ( !$user->isLoggedIn() ) {
3606 * $user->addToDatabase();
3608 * // do something with $user...
3610 * However, this was vulnerable to a race condition (bug 16020). By
3611 * initialising the user object if the user exists, we aim to support this
3612 * calling sequence as far as possible.
3614 * Note that if the user exists, this function will acquire a write lock,
3615 * so it is still advisable to make the call conditional on isLoggedIn(),
3616 * and to commit the transaction after calling.
3618 * @throws MWException
3621 public function addToDatabase() {
3623 $this->loadPasswords();
3624 if ( !$this->mToken
) {
3625 $this->setToken(); // init token
3628 $this->mTouched
= self
::newTouchedTimestamp();
3630 $dbw = wfGetDB( DB_MASTER
);
3631 $inWrite = $dbw->writesOrCallbacksPending();
3632 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3633 $dbw->insert( 'user',
3635 'user_id' => $seqVal,
3636 'user_name' => $this->mName
,
3637 'user_password' => $this->mPassword
->toString(),
3638 'user_newpassword' => $this->mNewpassword
->toString(),
3639 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3640 'user_email' => $this->mEmail
,
3641 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3642 'user_real_name' => $this->mRealName
,
3643 'user_token' => strval( $this->mToken
),
3644 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3645 'user_editcount' => 0,
3646 'user_touched' => $dbw->timestamp( $this->mTouched
),
3650 if ( !$dbw->affectedRows() ) {
3651 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3652 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3654 // Can't commit due to pending writes that may need atomicity.
3655 // This may cause some lock contention unlike the case below.
3656 $options = array( 'LOCK IN SHARE MODE' );
3657 $flags = self
::READ_LOCKING
;
3659 // Often, this case happens early in views before any writes when
3660 // using CentralAuth. It's should be OK to commit and break the snapshot.
3661 $dbw->commit( __METHOD__
, 'flush' );
3665 $this->mId
= $dbw->selectField( 'user', 'user_id',
3666 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3669 if ( $this->loadFromDatabase( $flags ) ) {
3674 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3675 "to insert user '{$this->mName}' row, but it was not present in select!" );
3677 return Status
::newFatal( 'userexists' );
3679 $this->mId
= $dbw->insertId();
3681 // Clear instance cache other than user table data, which is already accurate
3682 $this->clearInstanceCache();
3684 $this->saveOptions();
3685 return Status
::newGood();
3689 * If this user is logged-in and blocked,
3690 * block any IP address they've successfully logged in from.
3691 * @return bool A block was spread
3693 public function spreadAnyEditBlock() {
3694 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3695 return $this->spreadBlock();
3701 * If this (non-anonymous) user is blocked,
3702 * block the IP address they've successfully logged in from.
3703 * @return bool A block was spread
3705 protected function spreadBlock() {
3706 wfDebug( __METHOD__
. "()\n" );
3708 if ( $this->mId
== 0 ) {
3712 $userblock = Block
::newFromTarget( $this->getName() );
3713 if ( !$userblock ) {
3717 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3721 * Get whether the user is explicitly blocked from account creation.
3722 * @return bool|Block
3724 public function isBlockedFromCreateAccount() {
3725 $this->getBlockedStatus();
3726 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3727 return $this->mBlock
;
3730 # bug 13611: if the IP address the user is trying to create an account from is
3731 # blocked with createaccount disabled, prevent new account creation there even
3732 # when the user is logged in
3733 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3734 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3736 return $this->mBlockedFromCreateAccount
instanceof Block
3737 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3738 ?
$this->mBlockedFromCreateAccount
3743 * Get whether the user is blocked from using Special:Emailuser.
3746 public function isBlockedFromEmailuser() {
3747 $this->getBlockedStatus();
3748 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3752 * Get whether the user is allowed to create an account.
3755 public function isAllowedToCreateAccount() {
3756 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3760 * Get this user's personal page title.
3762 * @return Title User's personal page title
3764 public function getUserPage() {
3765 return Title
::makeTitle( NS_USER
, $this->getName() );
3769 * Get this user's talk page title.
3771 * @return Title User's talk page title
3773 public function getTalkPage() {
3774 $title = $this->getUserPage();
3775 return $title->getTalkPage();
3779 * Determine whether the user is a newbie. Newbies are either
3780 * anonymous IPs, or the most recently created accounts.
3783 public function isNewbie() {
3784 return !$this->isAllowed( 'autoconfirmed' );
3788 * Check to see if the given clear-text password is one of the accepted passwords
3789 * @param string $password User password
3790 * @return bool True if the given password is correct, otherwise False
3792 public function checkPassword( $password ) {
3793 global $wgAuth, $wgLegacyEncoding;
3795 $this->loadPasswords();
3797 // Certain authentication plugins do NOT want to save
3798 // domain passwords in a mysql database, so we should
3799 // check this (in case $wgAuth->strict() is false).
3800 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3802 } elseif ( $wgAuth->strict() ) {
3803 // Auth plugin doesn't allow local authentication
3805 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3806 // Auth plugin doesn't allow local authentication for this user name
3810 if ( !$this->mPassword
->equals( $password ) ) {
3811 if ( $wgLegacyEncoding ) {
3812 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3813 // Check for this with iconv
3814 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3815 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3823 $passwordFactory = self
::getPasswordFactory();
3824 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3825 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3826 $this->saveSettings();
3833 * Check if the given clear-text password matches the temporary password
3834 * sent by e-mail for password reset operations.
3836 * @param string $plaintext
3838 * @return bool True if matches, false otherwise
3840 public function checkTemporaryPassword( $plaintext ) {
3841 global $wgNewPasswordExpiry;
3844 $this->loadPasswords();
3845 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3846 if ( is_null( $this->mNewpassTime
) ) {
3849 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3850 return ( time() < $expiry );
3857 * Alias for getEditToken.
3858 * @deprecated since 1.19, use getEditToken instead.
3860 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3861 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3862 * @return string The new edit token
3864 public function editToken( $salt = '', $request = null ) {
3865 wfDeprecated( __METHOD__
, '1.19' );
3866 return $this->getEditToken( $salt, $request );
3870 * Internal implementation for self::getEditToken() and
3871 * self::matchEditToken().
3873 * @param string|array $salt
3874 * @param WebRequest $request
3875 * @param string|int $timestamp
3878 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3879 if ( $this->isAnon() ) {
3880 return self
::EDIT_TOKEN_SUFFIX
;
3882 $token = $request->getSessionData( 'wsEditToken' );
3883 if ( $token === null ) {
3884 $token = MWCryptRand
::generateHex( 32 );
3885 $request->setSessionData( 'wsEditToken', $token );
3887 if ( is_array( $salt ) ) {
3888 $salt = implode( '|', $salt );
3890 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3891 dechex( $timestamp ) .
3892 self
::EDIT_TOKEN_SUFFIX
;
3897 * Initialize (if necessary) and return a session token value
3898 * which can be used in edit forms to show that the user's
3899 * login credentials aren't being hijacked with a foreign form
3904 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3905 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3906 * @return string The new edit token
3908 public function getEditToken( $salt = '', $request = null ) {
3909 return $this->getEditTokenAtTimestamp(
3910 $salt, $request ?
: $this->getRequest(), wfTimestamp()
3915 * Generate a looking random token for various uses.
3917 * @return string The new random token
3918 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3919 * wfRandomString for pseudo-randomness.
3921 public static function generateToken() {
3922 return MWCryptRand
::generateHex( 32 );
3926 * Check given value against the token value stored in the session.
3927 * A match should confirm that the form was submitted from the
3928 * user's own login session, not a form submission from a third-party
3931 * @param string $val Input value to compare
3932 * @param string $salt Optional function-specific data for hashing
3933 * @param WebRequest|null $request Object to use or null to use $wgRequest
3934 * @param int $maxage Fail tokens older than this, in seconds
3935 * @return bool Whether the token matches
3937 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3938 if ( $this->isAnon() ) {
3939 return $val === self
::EDIT_TOKEN_SUFFIX
;
3942 $suffixLen = strlen( self
::EDIT_TOKEN_SUFFIX
);
3943 if ( strlen( $val ) <= 32 +
$suffixLen ) {
3947 $timestamp = hexdec( substr( $val, 32, -$suffixLen ) );
3948 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3953 $sessionToken = $this->getEditTokenAtTimestamp(
3954 $salt, $request ?
: $this->getRequest(), $timestamp
3957 if ( $val != $sessionToken ) {
3958 wfDebug( "User::matchEditToken: broken session data\n" );
3961 return hash_equals( $sessionToken, $val );
3965 * Check given value against the token value stored in the session,
3966 * ignoring the suffix.
3968 * @param string $val Input value to compare
3969 * @param string $salt Optional function-specific data for hashing
3970 * @param WebRequest|null $request Object to use or null to use $wgRequest
3971 * @param int $maxage Fail tokens older than this, in seconds
3972 * @return bool Whether the token matches
3974 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3975 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self
::EDIT_TOKEN_SUFFIX
;
3976 return $this->matchEditToken( $val, $salt, $request, $maxage );
3980 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3981 * mail to the user's given address.
3983 * @param string $type Message to send, either "created", "changed" or "set"
3986 public function sendConfirmationMail( $type = 'created' ) {
3988 $expiration = null; // gets passed-by-ref and defined in next line.
3989 $token = $this->confirmationToken( $expiration );
3990 $url = $this->confirmationTokenUrl( $token );
3991 $invalidateURL = $this->invalidationTokenUrl( $token );
3992 $this->saveSettings();
3994 if ( $type == 'created' ||
$type === false ) {
3995 $message = 'confirmemail_body';
3996 } elseif ( $type === true ) {
3997 $message = 'confirmemail_body_changed';
3999 // Messages: confirmemail_body_changed, confirmemail_body_set
4000 $message = 'confirmemail_body_' . $type;
4003 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4004 wfMessage( $message,
4005 $this->getRequest()->getIP(),
4008 $wgLang->timeanddate( $expiration, false ),
4010 $wgLang->date( $expiration, false ),
4011 $wgLang->time( $expiration, false ) )->text() );
4015 * Send an e-mail to this user's account. Does not check for
4016 * confirmed status or validity.
4018 * @param string $subject Message subject
4019 * @param string $body Message body
4020 * @param string $from Optional From address; if unspecified, default
4021 * $wgPasswordSender will be used.
4022 * @param string $replyto Reply-To address
4025 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4026 if ( is_null( $from ) ) {
4027 global $wgPasswordSender;
4028 $sender = new MailAddress( $wgPasswordSender,
4029 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4031 $sender = MailAddress
::newFromUser( $from );
4034 $to = MailAddress
::newFromUser( $this );
4035 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
4039 * Generate, store, and return a new e-mail confirmation code.
4040 * A hash (unsalted, since it's used as a key) is stored.
4042 * @note Call saveSettings() after calling this function to commit
4043 * this change to the database.
4045 * @param string &$expiration Accepts the expiration time
4046 * @return string New token
4048 protected function confirmationToken( &$expiration ) {
4049 global $wgUserEmailConfirmationTokenExpiry;
4051 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4052 $expiration = wfTimestamp( TS_MW
, $expires );
4054 $token = MWCryptRand
::generateHex( 32 );
4055 $hash = md5( $token );
4056 $this->mEmailToken
= $hash;
4057 $this->mEmailTokenExpires
= $expiration;
4062 * Return a URL the user can use to confirm their email address.
4063 * @param string $token Accepts the email confirmation token
4064 * @return string New token URL
4066 protected function confirmationTokenUrl( $token ) {
4067 return $this->getTokenUrl( 'ConfirmEmail', $token );
4071 * Return a URL the user can use to invalidate their email address.
4072 * @param string $token Accepts the email confirmation token
4073 * @return string New token URL
4075 protected function invalidationTokenUrl( $token ) {
4076 return $this->getTokenUrl( 'InvalidateEmail', $token );
4080 * Internal function to format the e-mail validation/invalidation URLs.
4081 * This uses a quickie hack to use the
4082 * hardcoded English names of the Special: pages, for ASCII safety.
4084 * @note Since these URLs get dropped directly into emails, using the
4085 * short English names avoids insanely long URL-encoded links, which
4086 * also sometimes can get corrupted in some browsers/mailers
4087 * (bug 6957 with Gmail and Internet Explorer).
4089 * @param string $page Special page
4090 * @param string $token Token
4091 * @return string Formatted URL
4093 protected function getTokenUrl( $page, $token ) {
4094 // Hack to bypass localization of 'Special:'
4095 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4096 return $title->getCanonicalURL();
4100 * Mark the e-mail address confirmed.
4102 * @note Call saveSettings() after calling this function to commit the change.
4106 public function confirmEmail() {
4107 // Check if it's already confirmed, so we don't touch the database
4108 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4109 if ( !$this->isEmailConfirmed() ) {
4110 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4111 Hooks
::run( 'ConfirmEmailComplete', array( $this ) );
4117 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4118 * address if it was already confirmed.
4120 * @note Call saveSettings() after calling this function to commit the change.
4121 * @return bool Returns true
4123 public function invalidateEmail() {
4125 $this->mEmailToken
= null;
4126 $this->mEmailTokenExpires
= null;
4127 $this->setEmailAuthenticationTimestamp( null );
4129 Hooks
::run( 'InvalidateEmailComplete', array( $this ) );
4134 * Set the e-mail authentication timestamp.
4135 * @param string $timestamp TS_MW timestamp
4137 public function setEmailAuthenticationTimestamp( $timestamp ) {
4139 $this->mEmailAuthenticated
= $timestamp;
4140 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4144 * Is this user allowed to send e-mails within limits of current
4145 * site configuration?
4148 public function canSendEmail() {
4149 global $wgEnableEmail, $wgEnableUserEmail;
4150 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4153 $canSend = $this->isEmailConfirmed();
4154 Hooks
::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4159 * Is this user allowed to receive e-mails within limits of current
4160 * site configuration?
4163 public function canReceiveEmail() {
4164 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4168 * Is this user's e-mail address valid-looking and confirmed within
4169 * limits of the current site configuration?
4171 * @note If $wgEmailAuthentication is on, this may require the user to have
4172 * confirmed their address by returning a code or using a password
4173 * sent to the address from the wiki.
4177 public function isEmailConfirmed() {
4178 global $wgEmailAuthentication;
4181 if ( Hooks
::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4182 if ( $this->isAnon() ) {
4185 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4188 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4198 * Check whether there is an outstanding request for e-mail confirmation.
4201 public function isEmailConfirmationPending() {
4202 global $wgEmailAuthentication;
4203 return $wgEmailAuthentication &&
4204 !$this->isEmailConfirmed() &&
4205 $this->mEmailToken
&&
4206 $this->mEmailTokenExpires
> wfTimestamp();
4210 * Get the timestamp of account creation.
4212 * @return string|bool|null Timestamp of account creation, false for
4213 * non-existent/anonymous user accounts, or null if existing account
4214 * but information is not in database.
4216 public function getRegistration() {
4217 if ( $this->isAnon() ) {
4221 return $this->mRegistration
;
4225 * Get the timestamp of the first edit
4227 * @return string|bool Timestamp of first edit, or false for
4228 * non-existent/anonymous user accounts.
4230 public function getFirstEditTimestamp() {
4231 if ( $this->getId() == 0 ) {
4232 return false; // anons
4234 $dbr = wfGetDB( DB_SLAVE
);
4235 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4236 array( 'rev_user' => $this->getId() ),
4238 array( 'ORDER BY' => 'rev_timestamp ASC' )
4241 return false; // no edits
4243 return wfTimestamp( TS_MW
, $time );
4247 * Get the permissions associated with a given list of groups
4249 * @param array $groups Array of Strings List of internal group names
4250 * @return array Array of Strings List of permission key names for given groups combined
4252 public static function getGroupPermissions( $groups ) {
4253 global $wgGroupPermissions, $wgRevokePermissions;
4255 // grant every granted permission first
4256 foreach ( $groups as $group ) {
4257 if ( isset( $wgGroupPermissions[$group] ) ) {
4258 $rights = array_merge( $rights,
4259 // array_filter removes empty items
4260 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4263 // now revoke the revoked permissions
4264 foreach ( $groups as $group ) {
4265 if ( isset( $wgRevokePermissions[$group] ) ) {
4266 $rights = array_diff( $rights,
4267 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4270 return array_unique( $rights );
4274 * Get all the groups who have a given permission
4276 * @param string $role Role to check
4277 * @return array Array of Strings List of internal group names with the given permission
4279 public static function getGroupsWithPermission( $role ) {
4280 global $wgGroupPermissions;
4281 $allowedGroups = array();
4282 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4283 if ( self
::groupHasPermission( $group, $role ) ) {
4284 $allowedGroups[] = $group;
4287 return $allowedGroups;
4291 * Check, if the given group has the given permission
4293 * If you're wanting to check whether all users have a permission, use
4294 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4298 * @param string $group Group to check
4299 * @param string $role Role to check
4302 public static function groupHasPermission( $group, $role ) {
4303 global $wgGroupPermissions, $wgRevokePermissions;
4304 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4305 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4309 * Check if all users have the given permission
4312 * @param string $right Right to check
4315 public static function isEveryoneAllowed( $right ) {
4316 global $wgGroupPermissions, $wgRevokePermissions;
4317 static $cache = array();
4319 // Use the cached results, except in unit tests which rely on
4320 // being able change the permission mid-request
4321 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4322 return $cache[$right];
4325 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4326 $cache[$right] = false;
4330 // If it's revoked anywhere, then everyone doesn't have it
4331 foreach ( $wgRevokePermissions as $rights ) {
4332 if ( isset( $rights[$right] ) && $rights[$right] ) {
4333 $cache[$right] = false;
4338 // Allow extensions (e.g. OAuth) to say false
4339 if ( !Hooks
::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4340 $cache[$right] = false;
4344 $cache[$right] = true;
4349 * Get the localized descriptive name for a group, if it exists
4351 * @param string $group Internal group name
4352 * @return string Localized descriptive group name
4354 public static function getGroupName( $group ) {
4355 $msg = wfMessage( "group-$group" );
4356 return $msg->isBlank() ?
$group : $msg->text();
4360 * Get the localized descriptive name for a member of a group, if it exists
4362 * @param string $group Internal group name
4363 * @param string $username Username for gender (since 1.19)
4364 * @return string Localized name for group member
4366 public static function getGroupMember( $group, $username = '#' ) {
4367 $msg = wfMessage( "group-$group-member", $username );
4368 return $msg->isBlank() ?
$group : $msg->text();
4372 * Return the set of defined explicit groups.
4373 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4374 * are not included, as they are defined automatically, not in the database.
4375 * @return array Array of internal group names
4377 public static function getAllGroups() {
4378 global $wgGroupPermissions, $wgRevokePermissions;
4380 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4381 self
::getImplicitGroups()
4386 * Get a list of all available permissions.
4387 * @return array Array of permission names
4389 public static function getAllRights() {
4390 if ( self
::$mAllRights === false ) {
4391 global $wgAvailableRights;
4392 if ( count( $wgAvailableRights ) ) {
4393 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4395 self
::$mAllRights = self
::$mCoreRights;
4397 Hooks
::run( 'UserGetAllRights', array( &self
::$mAllRights ) );
4399 return self
::$mAllRights;
4403 * Get a list of implicit groups
4404 * @return array Array of Strings Array of internal group names
4406 public static function getImplicitGroups() {
4407 global $wgImplicitGroups;
4409 $groups = $wgImplicitGroups;
4410 # Deprecated, use $wgImplicitGroups instead
4411 Hooks
::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4417 * Get the title of a page describing a particular group
4419 * @param string $group Internal group name
4420 * @return Title|bool Title of the page if it exists, false otherwise
4422 public static function getGroupPage( $group ) {
4423 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4424 if ( $msg->exists() ) {
4425 $title = Title
::newFromText( $msg->text() );
4426 if ( is_object( $title ) ) {
4434 * Create a link to the group in HTML, if available;
4435 * else return the group name.
4437 * @param string $group Internal name of the group
4438 * @param string $text The text of the link
4439 * @return string HTML link to the group
4441 public static function makeGroupLinkHTML( $group, $text = '' ) {
4442 if ( $text == '' ) {
4443 $text = self
::getGroupName( $group );
4445 $title = self
::getGroupPage( $group );
4447 return Linker
::link( $title, htmlspecialchars( $text ) );
4449 return htmlspecialchars( $text );
4454 * Create a link to the group in Wikitext, if available;
4455 * else return the group name.
4457 * @param string $group Internal name of the group
4458 * @param string $text The text of the link
4459 * @return string Wikilink to the group
4461 public static function makeGroupLinkWiki( $group, $text = '' ) {
4462 if ( $text == '' ) {
4463 $text = self
::getGroupName( $group );
4465 $title = self
::getGroupPage( $group );
4467 $page = $title->getFullText();
4468 return "[[$page|$text]]";
4475 * Returns an array of the groups that a particular group can add/remove.
4477 * @param string $group The group to check for whether it can add/remove
4478 * @return array Array( 'add' => array( addablegroups ),
4479 * 'remove' => array( removablegroups ),
4480 * 'add-self' => array( addablegroups to self),
4481 * 'remove-self' => array( removable groups from self) )
4483 public static function changeableByGroup( $group ) {
4484 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4488 'remove' => array(),
4489 'add-self' => array(),
4490 'remove-self' => array()
4493 if ( empty( $wgAddGroups[$group] ) ) {
4494 // Don't add anything to $groups
4495 } elseif ( $wgAddGroups[$group] === true ) {
4496 // You get everything
4497 $groups['add'] = self
::getAllGroups();
4498 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4499 $groups['add'] = $wgAddGroups[$group];
4502 // Same thing for remove
4503 if ( empty( $wgRemoveGroups[$group] ) ) {
4505 } elseif ( $wgRemoveGroups[$group] === true ) {
4506 $groups['remove'] = self
::getAllGroups();
4507 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4508 $groups['remove'] = $wgRemoveGroups[$group];
4511 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4512 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4513 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4514 if ( is_int( $key ) ) {
4515 $wgGroupsAddToSelf['user'][] = $value;
4520 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4521 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4522 if ( is_int( $key ) ) {
4523 $wgGroupsRemoveFromSelf['user'][] = $value;
4528 // Now figure out what groups the user can add to him/herself
4529 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4531 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4532 // No idea WHY this would be used, but it's there
4533 $groups['add-self'] = User
::getAllGroups();
4534 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4535 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4538 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4540 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4541 $groups['remove-self'] = User
::getAllGroups();
4542 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4543 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4550 * Returns an array of groups that this user can add and remove
4551 * @return array Array( 'add' => array( addablegroups ),
4552 * 'remove' => array( removablegroups ),
4553 * 'add-self' => array( addablegroups to self),
4554 * 'remove-self' => array( removable groups from self) )
4556 public function changeableGroups() {
4557 if ( $this->isAllowed( 'userrights' ) ) {
4558 // This group gives the right to modify everything (reverse-
4559 // compatibility with old "userrights lets you change
4561 // Using array_merge to make the groups reindexed
4562 $all = array_merge( User
::getAllGroups() );
4566 'add-self' => array(),
4567 'remove-self' => array()
4571 // Okay, it's not so simple, we will have to go through the arrays
4574 'remove' => array(),
4575 'add-self' => array(),
4576 'remove-self' => array()
4578 $addergroups = $this->getEffectiveGroups();
4580 foreach ( $addergroups as $addergroup ) {
4581 $groups = array_merge_recursive(
4582 $groups, $this->changeableByGroup( $addergroup )
4584 $groups['add'] = array_unique( $groups['add'] );
4585 $groups['remove'] = array_unique( $groups['remove'] );
4586 $groups['add-self'] = array_unique( $groups['add-self'] );
4587 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4593 * Increment the user's edit-count field.
4594 * Will have no effect for anonymous users.
4596 public function incEditCount() {
4597 if ( !$this->isAnon() ) {
4598 $dbw = wfGetDB( DB_MASTER
);
4601 array( 'user_editcount=user_editcount+1' ),
4602 array( 'user_id' => $this->getId() ),
4606 // Lazy initialization check...
4607 if ( $dbw->affectedRows() == 0 ) {
4608 // Now here's a goddamn hack...
4609 $dbr = wfGetDB( DB_SLAVE
);
4610 if ( $dbr !== $dbw ) {
4611 // If we actually have a slave server, the count is
4612 // at least one behind because the current transaction
4613 // has not been committed and replicated.
4614 $this->initEditCount( 1 );
4616 // But if DB_SLAVE is selecting the master, then the
4617 // count we just read includes the revision that was
4618 // just added in the working transaction.
4619 $this->initEditCount();
4623 // edit count in user cache too
4624 $this->invalidateCache();
4628 * Initialize user_editcount from data out of the revision table
4630 * @param int $add Edits to add to the count from the revision table
4631 * @return int Number of edits
4633 protected function initEditCount( $add = 0 ) {
4634 // Pull from a slave to be less cruel to servers
4635 // Accuracy isn't the point anyway here
4636 $dbr = wfGetDB( DB_SLAVE
);
4637 $count = (int)$dbr->selectField(
4640 array( 'rev_user' => $this->getId() ),
4643 $count = $count +
$add;
4645 $dbw = wfGetDB( DB_MASTER
);
4648 array( 'user_editcount' => $count ),
4649 array( 'user_id' => $this->getId() ),
4657 * Get the description of a given right
4659 * @param string $right Right to query
4660 * @return string Localized description of the right
4662 public static function getRightDescription( $right ) {
4663 $key = "right-$right";
4664 $msg = wfMessage( $key );
4665 return $msg->isBlank() ?
$right : $msg->text();
4669 * Make a new-style password hash
4671 * @param string $password Plain-text password
4672 * @param bool|string $salt Optional salt, may be random or the user ID.
4673 * If unspecified or false, will generate one automatically
4674 * @return string Password hash
4675 * @deprecated since 1.24, use Password class
4677 public static function crypt( $password, $salt = false ) {
4678 wfDeprecated( __METHOD__
, '1.24' );
4679 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4680 return $hash->toString();
4684 * Compare a password hash with a plain-text password. Requires the user
4685 * ID if there's a chance that the hash is an old-style hash.
4687 * @param string $hash Password hash
4688 * @param string $password Plain-text password to compare
4689 * @param string|bool $userId User ID for old-style password salt
4692 * @deprecated since 1.24, use Password class
4694 public static function comparePasswords( $hash, $password, $userId = false ) {
4695 wfDeprecated( __METHOD__
, '1.24' );
4697 // Check for *really* old password hashes that don't even have a type
4698 // The old hash format was just an md5 hex hash, with no type information
4699 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4700 global $wgPasswordSalt;
4701 if ( $wgPasswordSalt ) {
4702 $password = ":B:{$userId}:{$hash}";
4704 $password = ":A:{$hash}";
4708 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4709 return $hash->equals( $password );
4713 * Add a newuser log entry for this user.
4714 * Before 1.19 the return value was always true.
4716 * @param string|bool $action Account creation type.
4717 * - String, one of the following values:
4718 * - 'create' for an anonymous user creating an account for himself.
4719 * This will force the action's performer to be the created user itself,
4720 * no matter the value of $wgUser
4721 * - 'create2' for a logged in user creating an account for someone else
4722 * - 'byemail' when the created user will receive its password by e-mail
4723 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4724 * - Boolean means whether the account was created by e-mail (deprecated):
4725 * - true will be converted to 'byemail'
4726 * - false will be converted to 'create' if this object is the same as
4727 * $wgUser and to 'create2' otherwise
4729 * @param string $reason User supplied reason
4731 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4733 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4734 global $wgUser, $wgNewUserLog;
4735 if ( empty( $wgNewUserLog ) ) {
4736 return true; // disabled
4739 if ( $action === true ) {
4740 $action = 'byemail';
4741 } elseif ( $action === false ) {
4742 if ( $this->equals( $wgUser ) ) {
4745 $action = 'create2';
4749 if ( $action === 'create' ||
$action === 'autocreate' ) {
4752 $performer = $wgUser;
4755 $logEntry = new ManualLogEntry( 'newusers', $action );
4756 $logEntry->setPerformer( $performer );
4757 $logEntry->setTarget( $this->getUserPage() );
4758 $logEntry->setComment( $reason );
4759 $logEntry->setParameters( array(
4760 '4::userid' => $this->getId(),
4762 $logid = $logEntry->insert();
4764 if ( $action !== 'autocreate' ) {
4765 $logEntry->publish( $logid );
4772 * Add an autocreate newuser log entry for this user
4773 * Used by things like CentralAuth and perhaps other authplugins.
4774 * Consider calling addNewUserLogEntry() directly instead.
4778 public function addNewUserLogEntryAutoCreate() {
4779 $this->addNewUserLogEntry( 'autocreate' );
4785 * Load the user options either from cache, the database or an array
4787 * @param array $data Rows for the current user out of the user_properties table
4789 protected function loadOptions( $data = null ) {
4794 if ( $this->mOptionsLoaded
) {
4798 $this->mOptions
= self
::getDefaultOptions();
4800 if ( !$this->getId() ) {
4801 // For unlogged-in users, load language/variant options from request.
4802 // There's no need to do it for logged-in users: they can set preferences,
4803 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4804 // so don't override user's choice (especially when the user chooses site default).
4805 $variant = $wgContLang->getDefaultVariant();
4806 $this->mOptions
['variant'] = $variant;
4807 $this->mOptions
['language'] = $variant;
4808 $this->mOptionsLoaded
= true;
4812 // Maybe load from the object
4813 if ( !is_null( $this->mOptionOverrides
) ) {
4814 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4815 foreach ( $this->mOptionOverrides
as $key => $value ) {
4816 $this->mOptions
[$key] = $value;
4819 if ( !is_array( $data ) ) {
4820 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4821 // Load from database
4822 $dbr = wfGetDB( DB_SLAVE
);
4824 $res = $dbr->select(
4826 array( 'up_property', 'up_value' ),
4827 array( 'up_user' => $this->getId() ),
4831 $this->mOptionOverrides
= array();
4833 foreach ( $res as $row ) {
4834 $data[$row->up_property
] = $row->up_value
;
4837 foreach ( $data as $property => $value ) {
4838 $this->mOptionOverrides
[$property] = $value;
4839 $this->mOptions
[$property] = $value;
4843 $this->mOptionsLoaded
= true;
4845 Hooks
::run( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4849 * Saves the non-default options for this user, as previously set e.g. via
4850 * setOption(), in the database's "user_properties" (preferences) table.
4851 * Usually used via saveSettings().
4853 protected function saveOptions() {
4854 $this->loadOptions();
4856 // Not using getOptions(), to keep hidden preferences in database
4857 $saveOptions = $this->mOptions
;
4859 // Allow hooks to abort, for instance to save to a global profile.
4860 // Reset options to default state before saving.
4861 if ( !Hooks
::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4865 $userId = $this->getId();
4867 $insert_rows = array(); // all the new preference rows
4868 foreach ( $saveOptions as $key => $value ) {
4869 // Don't bother storing default values
4870 $defaultOption = self
::getDefaultOption( $key );
4871 if ( ( $defaultOption === null && $value !== false && $value !== null )
4872 ||
$value != $defaultOption
4874 $insert_rows[] = array(
4875 'up_user' => $userId,
4876 'up_property' => $key,
4877 'up_value' => $value,
4882 $dbw = wfGetDB( DB_MASTER
);
4884 $res = $dbw->select( 'user_properties',
4885 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4887 // Find prior rows that need to be removed or updated. These rows will
4888 // all be deleted (the later so that INSERT IGNORE applies the new values).
4889 $keysDelete = array();
4890 foreach ( $res as $row ) {
4891 if ( !isset( $saveOptions[$row->up_property
] )
4892 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4894 $keysDelete[] = $row->up_property
;
4898 if ( count( $keysDelete ) ) {
4899 // Do the DELETE by PRIMARY KEY for prior rows.
4900 // In the past a very large portion of calls to this function are for setting
4901 // 'rememberpassword' for new accounts (a preference that has since been removed).
4902 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4903 // caused gap locks on [max user ID,+infinity) which caused high contention since
4904 // updates would pile up on each other as they are for higher (newer) user IDs.
4905 // It might not be necessary these days, but it shouldn't hurt either.
4906 $dbw->delete( 'user_properties',
4907 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4909 // Insert the new preference rows
4910 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4914 * Lazily instantiate and return a factory object for making passwords
4916 * @return PasswordFactory
4918 public static function getPasswordFactory() {
4919 if ( self
::$mPasswordFactory === null ) {
4920 self
::$mPasswordFactory = new PasswordFactory();
4921 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4924 return self
::$mPasswordFactory;
4928 * Provide an array of HTML5 attributes to put on an input element
4929 * intended for the user to enter a new password. This may include
4930 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4932 * Do *not* use this when asking the user to enter his current password!
4933 * Regardless of configuration, users may have invalid passwords for whatever
4934 * reason (e.g., they were set before requirements were tightened up).
4935 * Only use it when asking for a new password, like on account creation or
4938 * Obviously, you still need to do server-side checking.
4940 * NOTE: A combination of bugs in various browsers means that this function
4941 * actually just returns array() unconditionally at the moment. May as
4942 * well keep it around for when the browser bugs get fixed, though.
4944 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4946 * @return array Array of HTML attributes suitable for feeding to
4947 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4948 * That will get confused by the boolean attribute syntax used.)
4950 public static function passwordChangeInputAttribs() {
4951 global $wgMinimalPasswordLength;
4953 if ( $wgMinimalPasswordLength == 0 ) {
4957 # Note that the pattern requirement will always be satisfied if the
4958 # input is empty, so we need required in all cases.
4960 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4961 # if e-mail confirmation is being used. Since HTML5 input validation
4962 # is b0rked anyway in some browsers, just return nothing. When it's
4963 # re-enabled, fix this code to not output required for e-mail
4965 #$ret = array( 'required' );
4968 # We can't actually do this right now, because Opera 9.6 will print out
4969 # the entered password visibly in its error message! When other
4970 # browsers add support for this attribute, or Opera fixes its support,
4971 # we can add support with a version check to avoid doing this on Opera
4972 # versions where it will be a problem. Reported to Opera as
4973 # DSK-262266, but they don't have a public bug tracker for us to follow.
4975 if ( $wgMinimalPasswordLength > 1 ) {
4976 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4977 $ret['title'] = wfMessage( 'passwordtooshort' )
4978 ->numParams( $wgMinimalPasswordLength )->text();
4986 * Return the list of user fields that should be selected to create
4987 * a new user object.
4990 public static function selectFields() {
4998 'user_email_authenticated',
5000 'user_email_token_expires',
5001 'user_registration',
5007 * Factory function for fatal permission-denied errors
5010 * @param string $permission User right required
5013 static function newFatalPermissionDeniedStatus( $permission ) {
5016 $groups = array_map(
5017 array( 'User', 'makeGroupLinkWiki' ),
5018 User
::getGroupsWithPermission( $permission )
5022 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5024 return Status
::newFatal( 'badaccess-group0' );
5029 * Checks if two user objects point to the same user.
5035 public function equals( User
$user ) {
5036 return $this->getName() === $user->getName();