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 * @var PasswordFactory Lazily loaded factory object for passwords
64 private static $mPasswordFactory = null;
67 * Array of Strings List of member variables which are saved to the
68 * shared cache (memcached). Any operation which changes the
69 * corresponding database fields must call a cache-clearing function.
72 protected static $mCacheVars = array(
80 'mEmailAuthenticated',
87 // user_properties table
92 * Array of Strings Core rights.
93 * Each of these should have a corresponding message of the form
97 protected static $mCoreRights = array(
123 'editusercssjs', #deprecated
135 'move-categorypages',
136 'move-rootuserpages',
140 'override-export-depth',
164 'userrights-interwiki',
172 * String Cached results of getAllRights()
174 protected static $mAllRights = false;
176 /** @name Cache variables */
186 public $mNewpassword;
188 public $mNewpassTime;
196 public $mEmailAuthenticated;
198 protected $mEmailToken;
200 protected $mEmailTokenExpires;
202 protected $mRegistration;
204 protected $mEditCount;
208 protected $mOptionOverrides;
210 protected $mPasswordExpires;
214 * Bool Whether the cache variables have been loaded.
217 public $mOptionsLoaded;
220 * Array with already loaded items or true if all items have been loaded.
222 protected $mLoadedItems = array();
226 * String Initialization data source if mLoadedItems!==true. May be one of:
227 * - 'defaults' anonymous user initialised from class defaults
228 * - 'name' initialise from mName
229 * - 'id' initialise from mId
230 * - 'session' log in from cookies or session if possible
232 * Use the User::newFrom*() family of functions to set this.
237 * Lazy-initialized variables, invalidated with clearInstanceCache
241 protected $mDatePreference;
249 protected $mBlockreason;
251 protected $mEffectiveGroups;
253 protected $mImplicitGroups;
255 protected $mFormerGroups;
257 protected $mBlockedGlobally;
274 protected $mAllowUsertalk;
277 private $mBlockedFromCreateAccount = false;
280 private $mWatchedItems = array();
282 public static $idCacheByName = array();
285 * Lightweight constructor for an anonymous user.
286 * Use the User::newFrom* factory functions for other kinds of users.
290 * @see newFromConfirmationCode()
291 * @see newFromSession()
294 public function __construct() {
295 $this->clearInstanceCache( 'defaults' );
301 public function __toString() {
302 return $this->getName();
306 * Load the user table data for this object from the source given by mFrom.
308 public function load() {
309 if ( $this->mLoadedItems
=== true ) {
312 wfProfileIn( __METHOD__
);
314 // Set it now to avoid infinite recursion in accessors
315 $this->mLoadedItems
= true;
317 switch ( $this->mFrom
) {
319 $this->loadDefaults();
322 $this->mId
= self
::idFromName( $this->mName
);
324 // Nonexistent user placeholder object
325 $this->loadDefaults( $this->mName
);
334 if ( !$this->loadFromSession() ) {
335 // Loading from session failed. Load defaults.
336 $this->loadDefaults();
338 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
341 wfProfileOut( __METHOD__
);
342 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
344 wfProfileOut( __METHOD__
);
348 * Load user table data, given mId has already been set.
349 * @return bool False if the ID does not exist, true otherwise
351 public function loadFromId() {
353 if ( $this->mId
== 0 ) {
354 $this->loadDefaults();
359 $key = wfMemcKey( 'user', 'id', $this->mId
);
360 $data = $wgMemc->get( $key );
361 if ( !is_array( $data ) ||
$data['mVersion'] != self
::VERSION
) {
362 // Object is expired, load from DB
367 wfDebug( "User: cache miss for user {$this->mId}\n" );
369 if ( !$this->loadFromDatabase() ) {
370 // Can't load from ID, user is anonymous
373 $this->saveToCache();
375 wfDebug( "User: got user {$this->mId} from cache\n" );
376 // Restore from cache
377 foreach ( self
::$mCacheVars as $name ) {
378 $this->$name = $data[$name];
382 $this->mLoadedItems
= true;
388 * Save user data to the shared cache
390 public function saveToCache() {
393 $this->loadOptions();
394 if ( $this->isAnon() ) {
395 // Anonymous users are uncached
399 foreach ( self
::$mCacheVars as $name ) {
400 $data[$name] = $this->$name;
402 $data['mVersion'] = self
::VERSION
;
403 $key = wfMemcKey( 'user', 'id', $this->mId
);
405 $wgMemc->set( $key, $data );
408 /** @name newFrom*() static factory methods */
412 * Static factory method for creation from username.
414 * This is slightly less efficient than newFromId(), so use newFromId() if
415 * you have both an ID and a name handy.
417 * @param string $name Username, validated by Title::newFromText()
418 * @param string|bool $validate Validate username. Takes the same parameters as
419 * User::getCanonicalName(), except that true is accepted as an alias
420 * for 'valid', for BC.
422 * @return User|bool User object, or false if the username is invalid
423 * (e.g. if it contains illegal characters or is an IP address). If the
424 * username is not present in the database, the result will be a user object
425 * with a name, zero user ID and default settings.
427 public static function newFromName( $name, $validate = 'valid' ) {
428 if ( $validate === true ) {
431 $name = self
::getCanonicalName( $name, $validate );
432 if ( $name === false ) {
435 // Create unloaded user object
439 $u->setItemLoaded( 'name' );
445 * Static factory method for creation from a given user ID.
447 * @param int $id Valid user ID
448 * @return User The corresponding User object
450 public static function newFromId( $id ) {
454 $u->setItemLoaded( 'id' );
459 * Factory method to fetch whichever user has a given email confirmation code.
460 * This code is generated when an account is created or its e-mail address
463 * If the code is invalid or has expired, returns NULL.
465 * @param string $code Confirmation code
468 public static function newFromConfirmationCode( $code ) {
469 $dbr = wfGetDB( DB_SLAVE
);
470 $id = $dbr->selectField( 'user', 'user_id', array(
471 'user_email_token' => md5( $code ),
472 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
474 if ( $id !== false ) {
475 return User
::newFromId( $id );
482 * Create a new user object using data from session or cookies. If the
483 * login credentials are invalid, the result is an anonymous user.
485 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
488 public static function newFromSession( WebRequest
$request = null ) {
490 $user->mFrom
= 'session';
491 $user->mRequest
= $request;
496 * Create a new user object from a user row.
497 * The row should have the following fields from the user table in it:
498 * - either user_name or user_id to load further data if needed (or both)
500 * - all other fields (email, password, etc.)
501 * It is useless to provide the remaining fields if either user_id,
502 * user_name and user_real_name are not provided because the whole row
503 * will be loaded once more from the database when accessing them.
505 * @param stdClass $row A row from the user table
506 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
509 public static function newFromRow( $row, $data = null ) {
511 $user->loadFromRow( $row, $data );
518 * Get the username corresponding to a given user ID
519 * @param int $id User ID
520 * @return string|bool The corresponding username
522 public static function whoIs( $id ) {
523 return UserCache
::singleton()->getProp( $id, 'name' );
527 * Get the real name of a user given their user ID
529 * @param int $id User ID
530 * @return string|bool The corresponding user's real name
532 public static function whoIsReal( $id ) {
533 return UserCache
::singleton()->getProp( $id, 'real_name' );
537 * Get database id given a user name
538 * @param string $name Username
539 * @return int|null The corresponding user's ID, or null if user is nonexistent
541 public static function idFromName( $name ) {
542 $nt = Title
::makeTitleSafe( NS_USER
, $name );
543 if ( is_null( $nt ) ) {
548 if ( isset( self
::$idCacheByName[$name] ) ) {
549 return self
::$idCacheByName[$name];
552 $dbr = wfGetDB( DB_SLAVE
);
553 $s = $dbr->selectRow(
556 array( 'user_name' => $nt->getText() ),
560 if ( $s === false ) {
563 $result = $s->user_id
;
566 self
::$idCacheByName[$name] = $result;
568 if ( count( self
::$idCacheByName ) > 1000 ) {
569 self
::$idCacheByName = array();
576 * Reset the cache used in idFromName(). For use in tests.
578 public static function resetIdByNameCache() {
579 self
::$idCacheByName = array();
583 * Does the string match an anonymous IPv4 address?
585 * This function exists for username validation, in order to reject
586 * usernames which are similar in form to IP addresses. Strings such
587 * as 300.300.300.300 will return true because it looks like an IP
588 * address, despite not being strictly valid.
590 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
591 * address because the usemod software would "cloak" anonymous IP
592 * addresses like this, if we allowed accounts like this to be created
593 * new users could get the old edits of these anonymous users.
595 * @param string $name Name to match
598 public static function isIP( $name ) {
599 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
600 || IP
::isIPv6( $name );
604 * Is the input a valid username?
606 * Checks if the input is a valid username, we don't want an empty string,
607 * an IP address, anything that contains slashes (would mess up subpages),
608 * is longer than the maximum allowed username size or doesn't begin with
611 * @param string $name Name to match
614 public static function isValidUserName( $name ) {
615 global $wgContLang, $wgMaxNameChars;
618 || User
::isIP( $name )
619 ||
strpos( $name, '/' ) !== false
620 ||
strlen( $name ) > $wgMaxNameChars
621 ||
$name != $wgContLang->ucfirst( $name ) ) {
622 wfDebugLog( 'username', __METHOD__
.
623 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
627 // Ensure that the name can't be misresolved as a different title,
628 // such as with extra namespace keys at the start.
629 $parsed = Title
::newFromText( $name );
630 if ( is_null( $parsed )
631 ||
$parsed->getNamespace()
632 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
633 wfDebugLog( 'username', __METHOD__
.
634 ": '$name' invalid due to ambiguous prefixes" );
638 // Check an additional blacklist of troublemaker characters.
639 // Should these be merged into the title char list?
640 $unicodeBlacklist = '/[' .
641 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
642 '\x{00a0}' . # non-breaking space
643 '\x{2000}-\x{200f}' . # various whitespace
644 '\x{2028}-\x{202f}' . # breaks and control chars
645 '\x{3000}' . # ideographic space
646 '\x{e000}-\x{f8ff}' . # private use
648 if ( preg_match( $unicodeBlacklist, $name ) ) {
649 wfDebugLog( 'username', __METHOD__
.
650 ": '$name' invalid due to blacklisted characters" );
658 * Usernames which fail to pass this function will be blocked
659 * from user login and new account registrations, but may be used
660 * internally by batch processes.
662 * If an account already exists in this form, login will be blocked
663 * by a failure to pass this function.
665 * @param string $name Name to match
668 public static function isUsableName( $name ) {
669 global $wgReservedUsernames;
670 // Must be a valid username, obviously ;)
671 if ( !self
::isValidUserName( $name ) ) {
675 static $reservedUsernames = false;
676 if ( !$reservedUsernames ) {
677 $reservedUsernames = $wgReservedUsernames;
678 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
681 // Certain names may be reserved for batch processes.
682 foreach ( $reservedUsernames as $reserved ) {
683 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
684 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
686 if ( $reserved == $name ) {
694 * Usernames which fail to pass this function will be blocked
695 * from new account registrations, but may be used internally
696 * either by batch processes or by user accounts which have
697 * already been created.
699 * Additional blacklisting may be added here rather than in
700 * isValidUserName() to avoid disrupting existing accounts.
702 * @param string $name String to match
705 public static function isCreatableName( $name ) {
706 global $wgInvalidUsernameCharacters;
708 // Ensure that the username isn't longer than 235 bytes, so that
709 // (at least for the builtin skins) user javascript and css files
710 // will work. (bug 23080)
711 if ( strlen( $name ) > 235 ) {
712 wfDebugLog( 'username', __METHOD__
.
713 ": '$name' invalid due to length" );
717 // Preg yells if you try to give it an empty string
718 if ( $wgInvalidUsernameCharacters !== '' ) {
719 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
720 wfDebugLog( 'username', __METHOD__
.
721 ": '$name' invalid due to wgInvalidUsernameCharacters" );
726 return self
::isUsableName( $name );
730 * Is the input a valid password for this user?
732 * @param string $password Desired password
735 public function isValidPassword( $password ) {
736 //simple boolean wrapper for getPasswordValidity
737 return $this->getPasswordValidity( $password ) === true;
742 * Given unvalidated password input, return error message on failure.
744 * @param string $password Desired password
745 * @return bool|string|array True on success, string or array of error message on failure
747 public function getPasswordValidity( $password ) {
748 $result = $this->checkPasswordValidity( $password );
749 if ( $result->isGood() ) {
753 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
754 $messages[] = $error['message'];
756 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
757 $messages[] = $warning['message'];
759 if ( count( $messages ) === 1 ) {
767 * Check if this is a valid password for this user. Status will be good if
768 * the password is valid, or have an array of error messages if not.
770 * @param string $password Desired password
774 public function checkPasswordValidity( $password ) {
775 global $wgMinimalPasswordLength, $wgContLang;
777 static $blockedLogins = array(
778 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
779 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
782 $status = Status
::newGood();
784 $result = false; //init $result to false for the internal checks
786 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
787 $status->error( $result );
791 if ( $result === false ) {
792 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
793 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
795 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName
) ) {
796 $status->error( 'password-name-match' );
798 } elseif ( isset( $blockedLogins[$this->getName()] )
799 && $password == $blockedLogins[$this->getName()]
801 $status->error( 'password-login-forbidden' );
804 //it seems weird returning a Good status here, but this is because of the
805 //initialization of $result to false above. If the hook is never run or it
806 //doesn't modify $result, then we will likely get down into this if with
810 } elseif ( $result === true ) {
813 $status->error( $result );
814 return $status; //the isValidPassword hook set a string $result and returned true
819 * Expire a user's password
821 * @param int $ts Optional timestamp to convert, default 0 for the current time
823 public function expirePassword( $ts = 0 ) {
825 $timestamp = wfTimestamp( TS_MW
, $ts );
826 $this->mPasswordExpires
= $timestamp;
827 $this->saveSettings();
831 * Clear the password expiration for a user
833 * @param bool $load Ensure user object is loaded first
835 public function resetPasswordExpiration( $load = true ) {
836 global $wgPasswordExpirationDays;
841 if ( $wgPasswordExpirationDays ) {
842 $newExpire = wfTimestamp(
844 time() +
( $wgPasswordExpirationDays * 24 * 3600 )
847 // Give extensions a chance to force an expiration
848 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
849 $this->mPasswordExpires
= $newExpire;
853 * Check if the user's password is expired.
854 * TODO: Put this and password length into a PasswordPolicy object
856 * @return string|bool The expiration type, or false if not expired
857 * hard: A password change is required to login
858 * soft: Allow login, but encourage password change
859 * false: Password is not expired
861 public function getPasswordExpired() {
862 global $wgPasswordExpireGrace;
864 $now = wfTimestamp();
865 $expiration = $this->getPasswordExpireDate();
866 $expUnix = wfTimestamp( TS_UNIX
, $expiration );
867 if ( $expiration !== null && $expUnix < $now ) {
868 $expired = ( $expUnix +
$wgPasswordExpireGrace < $now ) ?
'hard' : 'soft';
874 * Get this user's password expiration date. Since this may be using
875 * the cached User object, we assume that whatever mechanism is setting
876 * the expiration date is also expiring the User cache.
878 * @return string|bool The datestamp of the expiration, or null if not set
880 public function getPasswordExpireDate() {
882 return $this->mPasswordExpires
;
886 * Given unvalidated user input, return a canonical username, or false if
887 * the username is invalid.
888 * @param string $name User input
889 * @param string|bool $validate Type of validation to use:
890 * - false No validation
891 * - 'valid' Valid for batch processes
892 * - 'usable' Valid for batch processes and login
893 * - 'creatable' Valid for batch processes, login and account creation
895 * @throws MWException
896 * @return bool|string
898 public static function getCanonicalName( $name, $validate = 'valid' ) {
899 // Force usernames to capital
901 $name = $wgContLang->ucfirst( $name );
903 # Reject names containing '#'; these will be cleaned up
904 # with title normalisation, but then it's too late to
906 if ( strpos( $name, '#' ) !== false ) {
910 // Clean up name according to title rules,
911 // but only when validation is requested (bug 12654)
912 $t = ( $validate !== false ) ?
913 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
914 // Check for invalid titles
915 if ( is_null( $t ) ) {
919 // Reject various classes of invalid names
921 $name = $wgAuth->getCanonicalName( $t->getText() );
923 switch ( $validate ) {
927 if ( !User
::isValidUserName( $name ) ) {
932 if ( !User
::isUsableName( $name ) ) {
937 if ( !User
::isCreatableName( $name ) ) {
942 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
948 * Count the number of edits of a user
950 * @param int $uid User ID to check
951 * @return int The user's edit count
953 * @deprecated since 1.21 in favour of User::getEditCount
955 public static function edits( $uid ) {
956 wfDeprecated( __METHOD__
, '1.21' );
957 $user = self
::newFromId( $uid );
958 return $user->getEditCount();
962 * Return a random password.
964 * @return string New random password
966 public static function randomPassword() {
967 global $wgMinimalPasswordLength;
968 // Decide the final password length based on our min password length,
969 // stopping at a minimum of 10 chars.
970 $length = max( 10, $wgMinimalPasswordLength );
971 // Multiply by 1.25 to get the number of hex characters we need
972 $length = $length * 1.25;
973 // Generate random hex chars
974 $hex = MWCryptRand
::generateHex( $length );
975 // Convert from base 16 to base 32 to get a proper password like string
976 return wfBaseConvert( $hex, 16, 32 );
980 * Set cached properties to default.
982 * @note This no longer clears uncached lazy-initialised properties;
983 * the constructor does that instead.
985 * @param string|bool $name
987 public function loadDefaults( $name = false ) {
988 wfProfileIn( __METHOD__
);
990 $passwordFactory = self
::getPasswordFactory();
993 $this->mName
= $name;
994 $this->mRealName
= '';
995 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
996 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
997 $this->mNewpassTime
= null;
999 $this->mOptionOverrides
= null;
1000 $this->mOptionsLoaded
= false;
1002 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1003 if ( $loggedOut !== null ) {
1004 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1006 $this->mTouched
= '1'; # Allow any pages to be cached
1009 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1010 $this->mEmailAuthenticated
= null;
1011 $this->mEmailToken
= '';
1012 $this->mEmailTokenExpires
= null;
1013 $this->mPasswordExpires
= null;
1014 $this->resetPasswordExpiration( false );
1015 $this->mRegistration
= wfTimestamp( TS_MW
);
1016 $this->mGroups
= array();
1018 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1020 wfProfileOut( __METHOD__
);
1024 * Return whether an item has been loaded.
1026 * @param string $item Item to check. Current possibilities:
1030 * @param string $all 'all' to check if the whole object has been loaded
1031 * or any other string to check if only the item is available (e.g.
1035 public function isItemLoaded( $item, $all = 'all' ) {
1036 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1037 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1041 * Set that an item has been loaded
1043 * @param string $item
1045 protected function setItemLoaded( $item ) {
1046 if ( is_array( $this->mLoadedItems
) ) {
1047 $this->mLoadedItems
[$item] = true;
1052 * Load user data from the session or login cookie.
1053 * @return bool True if the user is logged in, false otherwise.
1055 private function loadFromSession() {
1057 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1058 if ( $result !== null ) {
1062 $request = $this->getRequest();
1064 $cookieId = $request->getCookie( 'UserID' );
1065 $sessId = $request->getSessionData( 'wsUserID' );
1067 if ( $cookieId !== null ) {
1068 $sId = intval( $cookieId );
1069 if ( $sessId !== null && $cookieId != $sessId ) {
1070 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1071 cookie user ID ($sId) don't match!" );
1074 $request->setSessionData( 'wsUserID', $sId );
1075 } elseif ( $sessId !== null && $sessId != 0 ) {
1081 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1082 $sName = $request->getSessionData( 'wsUserName' );
1083 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1084 $sName = $request->getCookie( 'UserName' );
1085 $request->setSessionData( 'wsUserName', $sName );
1090 $proposedUser = User
::newFromId( $sId );
1091 if ( !$proposedUser->isLoggedIn() ) {
1096 global $wgBlockDisablesLogin;
1097 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1098 // User blocked and we've disabled blocked user logins
1102 if ( $request->getSessionData( 'wsToken' ) ) {
1104 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1106 } elseif ( $request->getCookie( 'Token' ) ) {
1107 # Get the token from DB/cache and clean it up to remove garbage padding.
1108 # This deals with historical problems with bugs and the default column value.
1109 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1110 // Make comparison in constant time (bug 61346)
1111 $passwordCorrect = strlen( $token )
1112 && hash_equals( $token, $request->getCookie( 'Token' ) );
1115 // No session or persistent login cookie
1119 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1120 $this->loadFromUserObject( $proposedUser );
1121 $request->setSessionData( 'wsToken', $this->mToken
);
1122 wfDebug( "User: logged in from $from\n" );
1125 // Invalid credentials
1126 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1132 * Load user and user_group data from the database.
1133 * $this->mId must be set, this is how the user is identified.
1135 * @param int $flags Supports User::READ_LOCKING
1136 * @return bool True if the user exists, false if the user is anonymous
1138 public function loadFromDatabase( $flags = 0 ) {
1140 $this->mId
= intval( $this->mId
);
1143 if ( !$this->mId
) {
1144 $this->loadDefaults();
1148 $dbr = wfGetDB( DB_MASTER
);
1149 $s = $dbr->selectRow(
1151 self
::selectFields(),
1152 array( 'user_id' => $this->mId
),
1154 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1155 ?
array( 'LOCK IN SHARE MODE' )
1159 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1161 if ( $s !== false ) {
1162 // Initialise user table data
1163 $this->loadFromRow( $s );
1164 $this->mGroups
= null; // deferred
1165 $this->getEditCount(); // revalidation for nulls
1170 $this->loadDefaults();
1176 * Initialize this object from a row from the user table.
1178 * @param stdClass $row Row from the user table to load.
1179 * @param array $data Further user data to load into the object
1181 * user_groups Array with groups out of the user_groups table
1182 * user_properties Array with properties out of the user_properties table
1184 public function loadFromRow( $row, $data = null ) {
1186 $passwordFactory = self
::getPasswordFactory();
1188 $this->mGroups
= null; // deferred
1190 if ( isset( $row->user_name
) ) {
1191 $this->mName
= $row->user_name
;
1192 $this->mFrom
= 'name';
1193 $this->setItemLoaded( 'name' );
1198 if ( isset( $row->user_real_name
) ) {
1199 $this->mRealName
= $row->user_real_name
;
1200 $this->setItemLoaded( 'realname' );
1205 if ( isset( $row->user_id
) ) {
1206 $this->mId
= intval( $row->user_id
);
1207 $this->mFrom
= 'id';
1208 $this->setItemLoaded( 'id' );
1213 if ( isset( $row->user_editcount
) ) {
1214 $this->mEditCount
= $row->user_editcount
;
1219 if ( isset( $row->user_password
) ) {
1220 // Check for *really* old password hashes that don't even have a type
1221 // The old hash format was just an md5 hex hash, with no type information
1222 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1223 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1227 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1228 } catch ( PasswordError
$e ) {
1229 wfDebug( 'Invalid password hash found in database.' );
1230 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1234 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1235 } catch ( PasswordError
$e ) {
1236 wfDebug( 'Invalid password hash found in database.' );
1237 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1240 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1241 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1244 if ( isset( $row->user_email
) ) {
1245 $this->mEmail
= $row->user_email
;
1246 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1247 $this->mToken
= $row->user_token
;
1248 if ( $this->mToken
== '' ) {
1249 $this->mToken
= null;
1251 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1252 $this->mEmailToken
= $row->user_email_token
;
1253 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1254 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1260 $this->mLoadedItems
= true;
1263 if ( is_array( $data ) ) {
1264 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1265 $this->mGroups
= $data['user_groups'];
1267 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1268 $this->loadOptions( $data['user_properties'] );
1274 * Load the data for this user object from another user object.
1278 protected function loadFromUserObject( $user ) {
1280 $user->loadGroups();
1281 $user->loadOptions();
1282 foreach ( self
::$mCacheVars as $var ) {
1283 $this->$var = $user->$var;
1288 * Load the groups from the database if they aren't already loaded.
1290 private function loadGroups() {
1291 if ( is_null( $this->mGroups
) ) {
1292 $dbr = wfGetDB( DB_MASTER
);
1293 $res = $dbr->select( 'user_groups',
1294 array( 'ug_group' ),
1295 array( 'ug_user' => $this->mId
),
1297 $this->mGroups
= array();
1298 foreach ( $res as $row ) {
1299 $this->mGroups
[] = $row->ug_group
;
1305 * Load the user's password hashes from the database
1307 * This is usually called in a scenario where the actual User object was
1308 * loaded from the cache, and then password comparison needs to be performed.
1309 * Password hashes are not stored in memcached.
1313 private function loadPasswords() {
1314 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1315 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1317 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1318 array( 'user_id' => $this->getId() ),
1325 * Add the user to the group if he/she meets given criteria.
1327 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1328 * possible to remove manually via Special:UserRights. In such case it
1329 * will not be re-added automatically. The user will also not lose the
1330 * group if they no longer meet the criteria.
1332 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1334 * @return array Array of groups the user has been promoted to.
1336 * @see $wgAutopromoteOnce
1338 public function addAutopromoteOnceGroups( $event ) {
1339 global $wgAutopromoteOnceLogInRC, $wgAuth;
1341 $toPromote = array();
1342 if ( $this->getId() ) {
1343 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1344 if ( count( $toPromote ) ) {
1345 $oldGroups = $this->getGroups(); // previous groups
1347 foreach ( $toPromote as $group ) {
1348 $this->addGroup( $group );
1350 // update groups in external authentication database
1351 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1353 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1355 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1356 $logEntry->setPerformer( $this );
1357 $logEntry->setTarget( $this->getUserPage() );
1358 $logEntry->setParameters( array(
1359 '4::oldgroups' => $oldGroups,
1360 '5::newgroups' => $newGroups,
1362 $logid = $logEntry->insert();
1363 if ( $wgAutopromoteOnceLogInRC ) {
1364 $logEntry->publish( $logid );
1372 * Clear various cached data stored in this object. The cache of the user table
1373 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1375 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1376 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1378 public function clearInstanceCache( $reloadFrom = false ) {
1379 $this->mNewtalk
= -1;
1380 $this->mDatePreference
= null;
1381 $this->mBlockedby
= -1; # Unset
1382 $this->mHash
= false;
1383 $this->mRights
= null;
1384 $this->mEffectiveGroups
= null;
1385 $this->mImplicitGroups
= null;
1386 $this->mGroups
= null;
1387 $this->mOptions
= null;
1388 $this->mOptionsLoaded
= false;
1389 $this->mEditCount
= null;
1391 if ( $reloadFrom ) {
1392 $this->mLoadedItems
= array();
1393 $this->mFrom
= $reloadFrom;
1398 * Combine the language default options with any site-specific options
1399 * and add the default language variants.
1401 * @return array Array of String options
1403 public static function getDefaultOptions() {
1404 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1406 static $defOpt = null;
1407 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1408 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1409 // mid-request and see that change reflected in the return value of this function.
1410 // Which is insane and would never happen during normal MW operation
1414 $defOpt = $wgDefaultUserOptions;
1415 // Default language setting
1416 $defOpt['language'] = $wgContLang->getCode();
1417 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1418 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1420 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1421 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1423 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1425 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1431 * Get a given default option value.
1433 * @param string $opt Name of option to retrieve
1434 * @return string Default option value
1436 public static function getDefaultOption( $opt ) {
1437 $defOpts = self
::getDefaultOptions();
1438 if ( isset( $defOpts[$opt] ) ) {
1439 return $defOpts[$opt];
1446 * Get blocking information
1447 * @param bool $bFromSlave Whether to check the slave database first.
1448 * To improve performance, non-critical checks are done against slaves.
1449 * Check when actually saving should be done against master.
1451 private function getBlockedStatus( $bFromSlave = true ) {
1452 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1454 if ( -1 != $this->mBlockedby
) {
1458 wfProfileIn( __METHOD__
);
1459 wfDebug( __METHOD__
. ": checking...\n" );
1461 // Initialize data...
1462 // Otherwise something ends up stomping on $this->mBlockedby when
1463 // things get lazy-loaded later, causing false positive block hits
1464 // due to -1 !== 0. Probably session-related... Nothing should be
1465 // overwriting mBlockedby, surely?
1468 # We only need to worry about passing the IP address to the Block generator if the
1469 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1470 # know which IP address they're actually coming from
1471 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1472 $ip = $this->getRequest()->getIP();
1478 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1481 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1482 && !in_array( $ip, $wgProxyWhitelist )
1485 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1487 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1488 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1489 $block->setTarget( $ip );
1490 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1492 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1493 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1494 $block->setTarget( $ip );
1498 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1499 if ( !$block instanceof Block
1500 && $wgApplyIpBlocksToXff
1502 && !$this->isAllowed( 'proxyunbannable' )
1503 && !in_array( $ip, $wgProxyWhitelist )
1505 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1506 $xff = array_map( 'trim', explode( ',', $xff ) );
1507 $xff = array_diff( $xff, array( $ip ) );
1508 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1509 $block = Block
::chooseBlock( $xffblocks, $xff );
1510 if ( $block instanceof Block
) {
1511 # Mangle the reason to alert the user that the block
1512 # originated from matching the X-Forwarded-For header.
1513 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1517 if ( $block instanceof Block
) {
1518 wfDebug( __METHOD__
. ": Found block.\n" );
1519 $this->mBlock
= $block;
1520 $this->mBlockedby
= $block->getByName();
1521 $this->mBlockreason
= $block->mReason
;
1522 $this->mHideName
= $block->mHideName
;
1523 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1525 $this->mBlockedby
= '';
1526 $this->mHideName
= 0;
1527 $this->mAllowUsertalk
= false;
1531 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1533 wfProfileOut( __METHOD__
);
1537 * Whether the given IP is in a DNS blacklist.
1539 * @param string $ip IP to check
1540 * @param bool $checkWhitelist Whether to check the whitelist first
1541 * @return bool True if blacklisted.
1543 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1544 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1546 if ( !$wgEnableDnsBlacklist ) {
1550 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1554 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1558 * Whether the given IP is in a given DNS blacklist.
1560 * @param string $ip IP to check
1561 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1562 * @return bool True if blacklisted.
1564 public function inDnsBlacklist( $ip, $bases ) {
1565 wfProfileIn( __METHOD__
);
1568 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1569 if ( IP
::isIPv4( $ip ) ) {
1570 // Reverse IP, bug 21255
1571 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1573 foreach ( (array)$bases as $base ) {
1575 // If we have an access key, use that too (ProjectHoneypot, etc.)
1576 if ( is_array( $base ) ) {
1577 if ( count( $base ) >= 2 ) {
1578 // Access key is 1, base URL is 0
1579 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1581 $host = "$ipReversed.{$base[0]}";
1584 $host = "$ipReversed.$base";
1588 $ipList = gethostbynamel( $host );
1591 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1595 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1600 wfProfileOut( __METHOD__
);
1605 * Check if an IP address is in the local proxy list
1611 public static function isLocallyBlockedProxy( $ip ) {
1612 global $wgProxyList;
1614 if ( !$wgProxyList ) {
1617 wfProfileIn( __METHOD__
);
1619 if ( !is_array( $wgProxyList ) ) {
1620 // Load from the specified file
1621 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1624 if ( !is_array( $wgProxyList ) ) {
1626 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1628 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1629 // Old-style flipped proxy list
1634 wfProfileOut( __METHOD__
);
1639 * Is this user subject to rate limiting?
1641 * @return bool True if rate limited
1643 public function isPingLimitable() {
1644 global $wgRateLimitsExcludedIPs;
1645 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1646 // No other good way currently to disable rate limits
1647 // for specific IPs. :P
1648 // But this is a crappy hack and should die.
1651 return !$this->isAllowed( 'noratelimit' );
1655 * Primitive rate limits: enforce maximum actions per time period
1656 * to put a brake on flooding.
1658 * The method generates both a generic profiling point and a per action one
1659 * (suffix being "-$action".
1661 * @note When using a shared cache like memcached, IP-address
1662 * last-hit counters will be shared across wikis.
1664 * @param string $action Action to enforce; 'edit' if unspecified
1665 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1666 * @return bool True if a rate limiter was tripped
1668 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1669 // Call the 'PingLimiter' hook
1671 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1675 global $wgRateLimits;
1676 if ( !isset( $wgRateLimits[$action] ) ) {
1680 // Some groups shouldn't trigger the ping limiter, ever
1681 if ( !$this->isPingLimitable() ) {
1686 wfProfileIn( __METHOD__
);
1687 wfProfileIn( __METHOD__
. '-' . $action );
1689 $limits = $wgRateLimits[$action];
1691 $id = $this->getId();
1694 if ( isset( $limits['anon'] ) && $id == 0 ) {
1695 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1698 if ( isset( $limits['user'] ) && $id != 0 ) {
1699 $userLimit = $limits['user'];
1701 if ( $this->isNewbie() ) {
1702 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1703 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1705 if ( isset( $limits['ip'] ) ) {
1706 $ip = $this->getRequest()->getIP();
1707 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1709 if ( isset( $limits['subnet'] ) ) {
1710 $ip = $this->getRequest()->getIP();
1713 if ( IP
::isIPv6( $ip ) ) {
1714 $parts = IP
::parseRange( "$ip/64" );
1715 $subnet = $parts[0];
1716 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1718 $subnet = $matches[1];
1720 if ( $subnet !== false ) {
1721 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1725 // Check for group-specific permissions
1726 // If more than one group applies, use the group with the highest limit
1727 foreach ( $this->getGroups() as $group ) {
1728 if ( isset( $limits[$group] ) ) {
1729 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1730 $userLimit = $limits[$group];
1734 // Set the user limit key
1735 if ( $userLimit !== false ) {
1736 list( $max, $period ) = $userLimit;
1737 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1738 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1742 foreach ( $keys as $key => $limit ) {
1743 list( $max, $period ) = $limit;
1744 $summary = "(limit $max in {$period}s)";
1745 $count = $wgMemc->get( $key );
1748 if ( $count >= $max ) {
1749 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1750 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1753 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1756 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1757 if ( $incrBy > 0 ) {
1758 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1761 if ( $incrBy > 0 ) {
1762 $wgMemc->incr( $key, $incrBy );
1766 wfProfileOut( __METHOD__
. '-' . $action );
1767 wfProfileOut( __METHOD__
);
1772 * Check if user is blocked
1774 * @param bool $bFromSlave Whether to check the slave database instead of
1775 * the master. Hacked from false due to horrible probs on site.
1776 * @return bool True if blocked, false otherwise
1778 public function isBlocked( $bFromSlave = true ) {
1779 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1783 * Get the block affecting the user, or null if the user is not blocked
1785 * @param bool $bFromSlave Whether to check the slave database instead of the master
1786 * @return Block|null
1788 public function getBlock( $bFromSlave = true ) {
1789 $this->getBlockedStatus( $bFromSlave );
1790 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1794 * Check if user is blocked from editing a particular article
1796 * @param Title $title Title to check
1797 * @param bool $bFromSlave Whether to check the slave database instead of the master
1800 public function isBlockedFrom( $title, $bFromSlave = false ) {
1801 global $wgBlockAllowsUTEdit;
1802 wfProfileIn( __METHOD__
);
1804 $blocked = $this->isBlocked( $bFromSlave );
1805 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1806 // If a user's name is suppressed, they cannot make edits anywhere
1807 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1808 && $title->getNamespace() == NS_USER_TALK
) {
1810 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1813 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1815 wfProfileOut( __METHOD__
);
1820 * If user is blocked, return the name of the user who placed the block
1821 * @return string Name of blocker
1823 public function blockedBy() {
1824 $this->getBlockedStatus();
1825 return $this->mBlockedby
;
1829 * If user is blocked, return the specified reason for the block
1830 * @return string Blocking reason
1832 public function blockedFor() {
1833 $this->getBlockedStatus();
1834 return $this->mBlockreason
;
1838 * If user is blocked, return the ID for the block
1839 * @return int Block ID
1841 public function getBlockId() {
1842 $this->getBlockedStatus();
1843 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1847 * Check if user is blocked on all wikis.
1848 * Do not use for actual edit permission checks!
1849 * This is intended for quick UI checks.
1851 * @param string $ip IP address, uses current client if none given
1852 * @return bool True if blocked, false otherwise
1854 public function isBlockedGlobally( $ip = '' ) {
1855 if ( $this->mBlockedGlobally
!== null ) {
1856 return $this->mBlockedGlobally
;
1858 // User is already an IP?
1859 if ( IP
::isIPAddress( $this->getName() ) ) {
1860 $ip = $this->getName();
1862 $ip = $this->getRequest()->getIP();
1865 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1866 $this->mBlockedGlobally
= (bool)$blocked;
1867 return $this->mBlockedGlobally
;
1871 * Check if user account is locked
1873 * @return bool True if locked, false otherwise
1875 public function isLocked() {
1876 if ( $this->mLocked
!== null ) {
1877 return $this->mLocked
;
1880 StubObject
::unstub( $wgAuth );
1881 $authUser = $wgAuth->getUserInstance( $this );
1882 $this->mLocked
= (bool)$authUser->isLocked();
1883 return $this->mLocked
;
1887 * Check if user account is hidden
1889 * @return bool True if hidden, false otherwise
1891 public function isHidden() {
1892 if ( $this->mHideName
!== null ) {
1893 return $this->mHideName
;
1895 $this->getBlockedStatus();
1896 if ( !$this->mHideName
) {
1898 StubObject
::unstub( $wgAuth );
1899 $authUser = $wgAuth->getUserInstance( $this );
1900 $this->mHideName
= (bool)$authUser->isHidden();
1902 return $this->mHideName
;
1906 * Get the user's ID.
1907 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1909 public function getId() {
1910 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1911 // Special case, we know the user is anonymous
1913 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1914 // Don't load if this was initialized from an ID
1921 * Set the user and reload all fields according to a given ID
1922 * @param int $v User ID to reload
1924 public function setId( $v ) {
1926 $this->clearInstanceCache( 'id' );
1930 * Get the user name, or the IP of an anonymous user
1931 * @return string User's name or IP address
1933 public function getName() {
1934 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1935 // Special case optimisation
1936 return $this->mName
;
1939 if ( $this->mName
=== false ) {
1941 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1943 return $this->mName
;
1948 * Set the user name.
1950 * This does not reload fields from the database according to the given
1951 * name. Rather, it is used to create a temporary "nonexistent user" for
1952 * later addition to the database. It can also be used to set the IP
1953 * address for an anonymous user to something other than the current
1956 * @note User::newFromName() has roughly the same function, when the named user
1958 * @param string $str New user name to set
1960 public function setName( $str ) {
1962 $this->mName
= $str;
1966 * Get the user's name escaped by underscores.
1967 * @return string Username escaped by underscores.
1969 public function getTitleKey() {
1970 return str_replace( ' ', '_', $this->getName() );
1974 * Check if the user has new messages.
1975 * @return bool True if the user has new messages
1977 public function getNewtalk() {
1980 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1981 if ( $this->mNewtalk
=== -1 ) {
1982 $this->mNewtalk
= false; # reset talk page status
1984 // Check memcached separately for anons, who have no
1985 // entire User object stored in there.
1986 if ( !$this->mId
) {
1987 global $wgDisableAnonTalk;
1988 if ( $wgDisableAnonTalk ) {
1989 // Anon newtalk disabled by configuration.
1990 $this->mNewtalk
= false;
1993 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1994 $newtalk = $wgMemc->get( $key );
1995 if ( strval( $newtalk ) !== '' ) {
1996 $this->mNewtalk
= (bool)$newtalk;
1998 // Since we are caching this, make sure it is up to date by getting it
2000 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2001 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2005 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2009 return (bool)$this->mNewtalk
;
2013 * Return the data needed to construct links for new talk page message
2014 * alerts. If there are new messages, this will return an associative array
2015 * with the following data:
2016 * wiki: The database name of the wiki
2017 * link: Root-relative link to the user's talk page
2018 * rev: The last talk page revision that the user has seen or null. This
2019 * is useful for building diff links.
2020 * If there are no new messages, it returns an empty array.
2021 * @note This function was designed to accomodate multiple talk pages, but
2022 * currently only returns a single link and revision.
2025 public function getNewMessageLinks() {
2027 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2029 } elseif ( !$this->getNewtalk() ) {
2032 $utp = $this->getTalkPage();
2033 $dbr = wfGetDB( DB_SLAVE
);
2034 // Get the "last viewed rev" timestamp from the oldest message notification
2035 $timestamp = $dbr->selectField( 'user_newtalk',
2036 'MIN(user_last_timestamp)',
2037 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2039 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2040 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2044 * Get the revision ID for the last talk page revision viewed by the talk
2046 * @return int|null Revision ID or null
2048 public function getNewMessageRevisionId() {
2049 $newMessageRevisionId = null;
2050 $newMessageLinks = $this->getNewMessageLinks();
2051 if ( $newMessageLinks ) {
2052 // Note: getNewMessageLinks() never returns more than a single link
2053 // and it is always for the same wiki, but we double-check here in
2054 // case that changes some time in the future.
2055 if ( count( $newMessageLinks ) === 1
2056 && $newMessageLinks[0]['wiki'] === wfWikiID()
2057 && $newMessageLinks[0]['rev']
2059 $newMessageRevision = $newMessageLinks[0]['rev'];
2060 $newMessageRevisionId = $newMessageRevision->getId();
2063 return $newMessageRevisionId;
2067 * Internal uncached check for new messages
2070 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2071 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2072 * @param bool $fromMaster True to fetch from the master, false for a slave
2073 * @return bool True if the user has new messages
2075 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2076 if ( $fromMaster ) {
2077 $db = wfGetDB( DB_MASTER
);
2079 $db = wfGetDB( DB_SLAVE
);
2081 $ok = $db->selectField( 'user_newtalk', $field,
2082 array( $field => $id ), __METHOD__
);
2083 return $ok !== false;
2087 * Add or update the new messages flag
2088 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2089 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2090 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2091 * @return bool True if successful, false otherwise
2093 protected function updateNewtalk( $field, $id, $curRev = null ) {
2094 // Get timestamp of the talk page revision prior to the current one
2095 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2096 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2097 // Mark the user as having new messages since this revision
2098 $dbw = wfGetDB( DB_MASTER
);
2099 $dbw->insert( 'user_newtalk',
2100 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2103 if ( $dbw->affectedRows() ) {
2104 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2107 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2113 * Clear the new messages flag for the given user
2114 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2115 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2116 * @return bool True if successful, false otherwise
2118 protected function deleteNewtalk( $field, $id ) {
2119 $dbw = wfGetDB( DB_MASTER
);
2120 $dbw->delete( 'user_newtalk',
2121 array( $field => $id ),
2123 if ( $dbw->affectedRows() ) {
2124 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2127 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2133 * Update the 'You have new messages!' status.
2134 * @param bool $val Whether the user has new messages
2135 * @param Revision $curRev New, as yet unseen revision of the user talk
2136 * page. Ignored if null or !$val.
2138 public function setNewtalk( $val, $curRev = null ) {
2139 if ( wfReadOnly() ) {
2144 $this->mNewtalk
= $val;
2146 if ( $this->isAnon() ) {
2148 $id = $this->getName();
2151 $id = $this->getId();
2156 $changed = $this->updateNewtalk( $field, $id, $curRev );
2158 $changed = $this->deleteNewtalk( $field, $id );
2161 if ( $this->isAnon() ) {
2162 // Anons have a separate memcached space, since
2163 // user records aren't kept for them.
2164 $key = wfMemcKey( 'newtalk', 'ip', $id );
2165 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2168 $this->invalidateCache();
2173 * Generate a current or new-future timestamp to be stored in the
2174 * user_touched field when we update things.
2175 * @return string Timestamp in TS_MW format
2177 private static function newTouchedTimestamp() {
2178 global $wgClockSkewFudge;
2179 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2183 * Clear user data from memcached.
2184 * Use after applying fun updates to the database; caller's
2185 * responsibility to update user_touched if appropriate.
2187 * Called implicitly from invalidateCache() and saveSettings().
2189 public function clearSharedCache() {
2193 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2198 * Immediately touch the user data cache for this account.
2199 * Updates user_touched field, and removes account data from memcached
2200 * for reload on the next hit.
2202 public function invalidateCache() {
2203 if ( wfReadOnly() ) {
2208 $this->mTouched
= self
::newTouchedTimestamp();
2210 $dbw = wfGetDB( DB_MASTER
);
2211 $userid = $this->mId
;
2212 $touched = $this->mTouched
;
2213 $method = __METHOD__
;
2214 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2215 // Prevent contention slams by checking user_touched first
2216 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2217 $needsPurge = $dbw->selectField( 'user', '1',
2218 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2219 if ( $needsPurge ) {
2220 $dbw->update( 'user',
2221 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2222 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2227 $this->clearSharedCache();
2232 * Validate the cache for this account.
2233 * @param string $timestamp A timestamp in TS_MW format
2236 public function validateCache( $timestamp ) {
2238 return ( $timestamp >= $this->mTouched
);
2242 * Get the user touched timestamp
2243 * @return string Timestamp
2245 public function getTouched() {
2247 return $this->mTouched
;
2251 * Set the password and reset the random token.
2252 * Calls through to authentication plugin if necessary;
2253 * will have no effect if the auth plugin refuses to
2254 * pass the change through or if the legal password
2257 * As a special case, setting the password to null
2258 * wipes it, so the account cannot be logged in until
2259 * a new password is set, for instance via e-mail.
2261 * @param string $str New password to set
2262 * @throws PasswordError On failure
2266 public function setPassword( $str ) {
2269 if ( $str !== null ) {
2270 if ( !$wgAuth->allowPasswordChange() ) {
2271 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2274 if ( !$this->isValidPassword( $str ) ) {
2275 global $wgMinimalPasswordLength;
2276 $valid = $this->getPasswordValidity( $str );
2277 if ( is_array( $valid ) ) {
2278 $message = array_shift( $valid );
2282 $params = array( $wgMinimalPasswordLength );
2284 throw new PasswordError( wfMessage( $message, $params )->text() );
2288 if ( !$wgAuth->setPassword( $this, $str ) ) {
2289 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2292 $this->setInternalPassword( $str );
2298 * Set the password and reset the random token unconditionally.
2300 * @param string|null $str New password to set or null to set an invalid
2301 * password hash meaning that the user will not be able to log in
2302 * through the web interface.
2304 public function setInternalPassword( $str ) {
2307 $passwordFactory = self
::getPasswordFactory();
2308 if ( $str === null ) {
2309 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
2311 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2314 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2315 $this->mNewpassTime
= null;
2319 * Get the user's current token.
2320 * @param bool $forceCreation Force the generation of a new token if the
2321 * user doesn't have one (default=true for backwards compatibility).
2322 * @return string Token
2324 public function getToken( $forceCreation = true ) {
2326 if ( !$this->mToken
&& $forceCreation ) {
2329 return $this->mToken
;
2333 * Set the random token (used for persistent authentication)
2334 * Called from loadDefaults() among other places.
2336 * @param string|bool $token If specified, set the token to this value
2338 public function setToken( $token = false ) {
2341 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2343 $this->mToken
= $token;
2348 * Set the password for a password reminder or new account email
2350 * @param string $str New password to set or null to set an invalid
2351 * password hash meaning that the user will not be able to use it
2352 * @param bool $throttle If true, reset the throttle timestamp to the present
2354 public function setNewpassword( $str, $throttle = true ) {
2357 if ( $str === null ) {
2358 $this->mNewpassword
= '';
2359 $this->mNewpassTime
= null;
2361 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2363 $this->mNewpassTime
= wfTimestampNow();
2369 * Has password reminder email been sent within the last
2370 * $wgPasswordReminderResendTime hours?
2373 public function isPasswordReminderThrottled() {
2374 global $wgPasswordReminderResendTime;
2376 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2379 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2380 return time() < $expiry;
2384 * Get the user's e-mail address
2385 * @return string User's email address
2387 public function getEmail() {
2389 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2390 return $this->mEmail
;
2394 * Get the timestamp of the user's e-mail authentication
2395 * @return string TS_MW timestamp
2397 public function getEmailAuthenticationTimestamp() {
2399 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2400 return $this->mEmailAuthenticated
;
2404 * Set the user's e-mail address
2405 * @param string $str New e-mail address
2407 public function setEmail( $str ) {
2409 if ( $str == $this->mEmail
) {
2412 $this->invalidateEmail();
2413 $this->mEmail
= $str;
2414 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2418 * Set the user's e-mail address and a confirmation mail if needed.
2421 * @param string $str New e-mail address
2424 public function setEmailWithConfirmation( $str ) {
2425 global $wgEnableEmail, $wgEmailAuthentication;
2427 if ( !$wgEnableEmail ) {
2428 return Status
::newFatal( 'emaildisabled' );
2431 $oldaddr = $this->getEmail();
2432 if ( $str === $oldaddr ) {
2433 return Status
::newGood( true );
2436 $this->setEmail( $str );
2438 if ( $str !== '' && $wgEmailAuthentication ) {
2439 // Send a confirmation request to the new address if needed
2440 $type = $oldaddr != '' ?
'changed' : 'set';
2441 $result = $this->sendConfirmationMail( $type );
2442 if ( $result->isGood() ) {
2443 // Say the the caller that a confirmation mail has been sent
2444 $result->value
= 'eauth';
2447 $result = Status
::newGood( true );
2454 * Get the user's real name
2455 * @return string User's real name
2457 public function getRealName() {
2458 if ( !$this->isItemLoaded( 'realname' ) ) {
2462 return $this->mRealName
;
2466 * Set the user's real name
2467 * @param string $str New real name
2469 public function setRealName( $str ) {
2471 $this->mRealName
= $str;
2475 * Get the user's current setting for a given option.
2477 * @param string $oname The option to check
2478 * @param string $defaultOverride A default value returned if the option does not exist
2479 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2480 * @return string User's current value for the option
2481 * @see getBoolOption()
2482 * @see getIntOption()
2484 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2485 global $wgHiddenPrefs;
2486 $this->loadOptions();
2488 # We want 'disabled' preferences to always behave as the default value for
2489 # users, even if they have set the option explicitly in their settings (ie they
2490 # set it, and then it was disabled removing their ability to change it). But
2491 # we don't want to erase the preferences in the database in case the preference
2492 # is re-enabled again. So don't touch $mOptions, just override the returned value
2493 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2494 return self
::getDefaultOption( $oname );
2497 if ( array_key_exists( $oname, $this->mOptions
) ) {
2498 return $this->mOptions
[$oname];
2500 return $defaultOverride;
2505 * Get all user's options
2509 public function getOptions() {
2510 global $wgHiddenPrefs;
2511 $this->loadOptions();
2512 $options = $this->mOptions
;
2514 # We want 'disabled' preferences to always behave as the default value for
2515 # users, even if they have set the option explicitly in their settings (ie they
2516 # set it, and then it was disabled removing their ability to change it). But
2517 # we don't want to erase the preferences in the database in case the preference
2518 # is re-enabled again. So don't touch $mOptions, just override the returned value
2519 foreach ( $wgHiddenPrefs as $pref ) {
2520 $default = self
::getDefaultOption( $pref );
2521 if ( $default !== null ) {
2522 $options[$pref] = $default;
2530 * Get the user's current setting for a given option, as a boolean value.
2532 * @param string $oname The option to check
2533 * @return bool User's current value for the option
2536 public function getBoolOption( $oname ) {
2537 return (bool)$this->getOption( $oname );
2541 * Get the user's current setting for a given option, as an integer value.
2543 * @param string $oname The option to check
2544 * @param int $defaultOverride A default value returned if the option does not exist
2545 * @return int User's current value for the option
2548 public function getIntOption( $oname, $defaultOverride = 0 ) {
2549 $val = $this->getOption( $oname );
2551 $val = $defaultOverride;
2553 return intval( $val );
2557 * Set the given option for a user.
2559 * You need to call saveSettings() to actually write to the database.
2561 * @param string $oname The option to set
2562 * @param mixed $val New value to set
2564 public function setOption( $oname, $val ) {
2565 $this->loadOptions();
2567 // Explicitly NULL values should refer to defaults
2568 if ( is_null( $val ) ) {
2569 $val = self
::getDefaultOption( $oname );
2572 $this->mOptions
[$oname] = $val;
2576 * Get a token stored in the preferences (like the watchlist one),
2577 * resetting it if it's empty (and saving changes).
2579 * @param string $oname The option name to retrieve the token from
2580 * @return string|bool User's current value for the option, or false if this option is disabled.
2581 * @see resetTokenFromOption()
2584 public function getTokenFromOption( $oname ) {
2585 global $wgHiddenPrefs;
2586 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2590 $token = $this->getOption( $oname );
2592 $token = $this->resetTokenFromOption( $oname );
2593 $this->saveSettings();
2599 * Reset a token stored in the preferences (like the watchlist one).
2600 * *Does not* save user's preferences (similarly to setOption()).
2602 * @param string $oname The option name to reset the token in
2603 * @return string|bool New token value, or false if this option is disabled.
2604 * @see getTokenFromOption()
2607 public function resetTokenFromOption( $oname ) {
2608 global $wgHiddenPrefs;
2609 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2613 $token = MWCryptRand
::generateHex( 40 );
2614 $this->setOption( $oname, $token );
2619 * Return a list of the types of user options currently returned by
2620 * User::getOptionKinds().
2622 * Currently, the option kinds are:
2623 * - 'registered' - preferences which are registered in core MediaWiki or
2624 * by extensions using the UserGetDefaultOptions hook.
2625 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2626 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2627 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2628 * be used by user scripts.
2629 * - 'special' - "preferences" that are not accessible via User::getOptions
2630 * or User::setOptions.
2631 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2632 * These are usually legacy options, removed in newer versions.
2634 * The API (and possibly others) use this function to determine the possible
2635 * option types for validation purposes, so make sure to update this when a
2636 * new option kind is added.
2638 * @see User::getOptionKinds
2639 * @return array Option kinds
2641 public static function listOptionKinds() {
2644 'registered-multiselect',
2645 'registered-checkmatrix',
2653 * Return an associative array mapping preferences keys to the kind of a preference they're
2654 * used for. Different kinds are handled differently when setting or reading preferences.
2656 * See User::listOptionKinds for the list of valid option types that can be provided.
2658 * @see User::listOptionKinds
2659 * @param IContextSource $context
2660 * @param array $options Assoc. array with options keys to check as keys.
2661 * Defaults to $this->mOptions.
2662 * @return array The key => kind mapping data
2664 public function getOptionKinds( IContextSource
$context, $options = null ) {
2665 $this->loadOptions();
2666 if ( $options === null ) {
2667 $options = $this->mOptions
;
2670 $prefs = Preferences
::getPreferences( $this, $context );
2673 // Pull out the "special" options, so they don't get converted as
2674 // multiselect or checkmatrix.
2675 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2676 foreach ( $specialOptions as $name => $value ) {
2677 unset( $prefs[$name] );
2680 // Multiselect and checkmatrix options are stored in the database with
2681 // one key per option, each having a boolean value. Extract those keys.
2682 $multiselectOptions = array();
2683 foreach ( $prefs as $name => $info ) {
2684 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2685 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2686 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2687 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2689 foreach ( $opts as $value ) {
2690 $multiselectOptions["$prefix$value"] = true;
2693 unset( $prefs[$name] );
2696 $checkmatrixOptions = array();
2697 foreach ( $prefs as $name => $info ) {
2698 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2699 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2700 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2701 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2702 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2704 foreach ( $columns as $column ) {
2705 foreach ( $rows as $row ) {
2706 $checkmatrixOptions["$prefix-$column-$row"] = true;
2710 unset( $prefs[$name] );
2714 // $value is ignored
2715 foreach ( $options as $key => $value ) {
2716 if ( isset( $prefs[$key] ) ) {
2717 $mapping[$key] = 'registered';
2718 } elseif ( isset( $multiselectOptions[$key] ) ) {
2719 $mapping[$key] = 'registered-multiselect';
2720 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2721 $mapping[$key] = 'registered-checkmatrix';
2722 } elseif ( isset( $specialOptions[$key] ) ) {
2723 $mapping[$key] = 'special';
2724 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2725 $mapping[$key] = 'userjs';
2727 $mapping[$key] = 'unused';
2735 * Reset certain (or all) options to the site defaults
2737 * The optional parameter determines which kinds of preferences will be reset.
2738 * Supported values are everything that can be reported by getOptionKinds()
2739 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2741 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2742 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2743 * for backwards-compatibility.
2744 * @param IContextSource|null $context Context source used when $resetKinds
2745 * does not contain 'all', passed to getOptionKinds().
2746 * Defaults to RequestContext::getMain() when null.
2748 public function resetOptions(
2749 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2750 IContextSource
$context = null
2753 $defaultOptions = self
::getDefaultOptions();
2755 if ( !is_array( $resetKinds ) ) {
2756 $resetKinds = array( $resetKinds );
2759 if ( in_array( 'all', $resetKinds ) ) {
2760 $newOptions = $defaultOptions;
2762 if ( $context === null ) {
2763 $context = RequestContext
::getMain();
2766 $optionKinds = $this->getOptionKinds( $context );
2767 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2768 $newOptions = array();
2770 // Use default values for the options that should be deleted, and
2771 // copy old values for the ones that shouldn't.
2772 foreach ( $this->mOptions
as $key => $value ) {
2773 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2774 if ( array_key_exists( $key, $defaultOptions ) ) {
2775 $newOptions[$key] = $defaultOptions[$key];
2778 $newOptions[$key] = $value;
2783 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2785 $this->mOptions
= $newOptions;
2786 $this->mOptionsLoaded
= true;
2790 * Get the user's preferred date format.
2791 * @return string User's preferred date format
2793 public function getDatePreference() {
2794 // Important migration for old data rows
2795 if ( is_null( $this->mDatePreference
) ) {
2797 $value = $this->getOption( 'date' );
2798 $map = $wgLang->getDatePreferenceMigrationMap();
2799 if ( isset( $map[$value] ) ) {
2800 $value = $map[$value];
2802 $this->mDatePreference
= $value;
2804 return $this->mDatePreference
;
2808 * Determine based on the wiki configuration and the user's options,
2809 * whether this user must be over HTTPS no matter what.
2813 public function requiresHTTPS() {
2814 global $wgSecureLogin;
2815 if ( !$wgSecureLogin ) {
2818 $https = $this->getBoolOption( 'prefershttps' );
2819 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2821 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2828 * Get the user preferred stub threshold
2832 public function getStubThreshold() {
2833 global $wgMaxArticleSize; # Maximum article size, in Kb
2834 $threshold = $this->getIntOption( 'stubthreshold' );
2835 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2836 // If they have set an impossible value, disable the preference
2837 // so we can use the parser cache again.
2844 * Get the permissions this user has.
2845 * @return array Array of String permission names
2847 public function getRights() {
2848 if ( is_null( $this->mRights
) ) {
2849 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2850 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2851 // Force reindexation of rights when a hook has unset one of them
2852 $this->mRights
= array_values( array_unique( $this->mRights
) );
2854 return $this->mRights
;
2858 * Get the list of explicit group memberships this user has.
2859 * The implicit * and user groups are not included.
2860 * @return array Array of String internal group names
2862 public function getGroups() {
2864 $this->loadGroups();
2865 return $this->mGroups
;
2869 * Get the list of implicit group memberships this user has.
2870 * This includes all explicit groups, plus 'user' if logged in,
2871 * '*' for all accounts, and autopromoted groups
2872 * @param bool $recache Whether to avoid the cache
2873 * @return array Array of String internal group names
2875 public function getEffectiveGroups( $recache = false ) {
2876 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2877 wfProfileIn( __METHOD__
);
2878 $this->mEffectiveGroups
= array_unique( array_merge(
2879 $this->getGroups(), // explicit groups
2880 $this->getAutomaticGroups( $recache ) // implicit groups
2882 // Hook for additional groups
2883 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2884 // Force reindexation of groups when a hook has unset one of them
2885 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2886 wfProfileOut( __METHOD__
);
2888 return $this->mEffectiveGroups
;
2892 * Get the list of implicit group memberships this user has.
2893 * This includes 'user' if logged in, '*' for all accounts,
2894 * and autopromoted groups
2895 * @param bool $recache Whether to avoid the cache
2896 * @return array Array of String internal group names
2898 public function getAutomaticGroups( $recache = false ) {
2899 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2900 wfProfileIn( __METHOD__
);
2901 $this->mImplicitGroups
= array( '*' );
2902 if ( $this->getId() ) {
2903 $this->mImplicitGroups
[] = 'user';
2905 $this->mImplicitGroups
= array_unique( array_merge(
2906 $this->mImplicitGroups
,
2907 Autopromote
::getAutopromoteGroups( $this )
2911 // Assure data consistency with rights/groups,
2912 // as getEffectiveGroups() depends on this function
2913 $this->mEffectiveGroups
= null;
2915 wfProfileOut( __METHOD__
);
2917 return $this->mImplicitGroups
;
2921 * Returns the groups the user has belonged to.
2923 * The user may still belong to the returned groups. Compare with getGroups().
2925 * The function will not return groups the user had belonged to before MW 1.17
2927 * @return array Names of the groups the user has belonged to.
2929 public function getFormerGroups() {
2930 if ( is_null( $this->mFormerGroups
) ) {
2931 $dbr = wfGetDB( DB_MASTER
);
2932 $res = $dbr->select( 'user_former_groups',
2933 array( 'ufg_group' ),
2934 array( 'ufg_user' => $this->mId
),
2936 $this->mFormerGroups
= array();
2937 foreach ( $res as $row ) {
2938 $this->mFormerGroups
[] = $row->ufg_group
;
2941 return $this->mFormerGroups
;
2945 * Get the user's edit count.
2946 * @return int|null Null for anonymous users
2948 public function getEditCount() {
2949 if ( !$this->getId() ) {
2953 if ( $this->mEditCount
=== null ) {
2954 /* Populate the count, if it has not been populated yet */
2955 wfProfileIn( __METHOD__
);
2956 $dbr = wfGetDB( DB_SLAVE
);
2957 // check if the user_editcount field has been initialized
2958 $count = $dbr->selectField(
2959 'user', 'user_editcount',
2960 array( 'user_id' => $this->mId
),
2964 if ( $count === null ) {
2965 // it has not been initialized. do so.
2966 $count = $this->initEditCount();
2968 $this->mEditCount
= $count;
2969 wfProfileOut( __METHOD__
);
2971 return (int)$this->mEditCount
;
2975 * Add the user to the given group.
2976 * This takes immediate effect.
2977 * @param string $group Name of the group to add
2979 public function addGroup( $group ) {
2980 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2981 $dbw = wfGetDB( DB_MASTER
);
2982 if ( $this->getId() ) {
2983 $dbw->insert( 'user_groups',
2985 'ug_user' => $this->getID(),
2986 'ug_group' => $group,
2989 array( 'IGNORE' ) );
2992 $this->loadGroups();
2993 $this->mGroups
[] = $group;
2994 // In case loadGroups was not called before, we now have the right twice.
2995 // Get rid of the duplicate.
2996 $this->mGroups
= array_unique( $this->mGroups
);
2998 // Refresh the groups caches, and clear the rights cache so it will be
2999 // refreshed on the next call to $this->getRights().
3000 $this->getEffectiveGroups( true );
3001 $this->mRights
= null;
3003 $this->invalidateCache();
3007 * Remove the user from the given group.
3008 * This takes immediate effect.
3009 * @param string $group Name of the group to remove
3011 public function removeGroup( $group ) {
3013 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3014 $dbw = wfGetDB( DB_MASTER
);
3015 $dbw->delete( 'user_groups',
3017 'ug_user' => $this->getID(),
3018 'ug_group' => $group,
3020 // Remember that the user was in this group
3021 $dbw->insert( 'user_former_groups',
3023 'ufg_user' => $this->getID(),
3024 'ufg_group' => $group,
3027 array( 'IGNORE' ) );
3029 $this->loadGroups();
3030 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3032 // Refresh the groups caches, and clear the rights cache so it will be
3033 // refreshed on the next call to $this->getRights().
3034 $this->getEffectiveGroups( true );
3035 $this->mRights
= null;
3037 $this->invalidateCache();
3041 * Get whether the user is logged in
3044 public function isLoggedIn() {
3045 return $this->getID() != 0;
3049 * Get whether the user is anonymous
3052 public function isAnon() {
3053 return !$this->isLoggedIn();
3057 * Check if user is allowed to access a feature / make an action
3059 * @internal param \String $varargs permissions to test
3060 * @return bool True if user is allowed to perform *any* of the given actions
3064 public function isAllowedAny( /*...*/ ) {
3065 $permissions = func_get_args();
3066 foreach ( $permissions as $permission ) {
3067 if ( $this->isAllowed( $permission ) ) {
3076 * @internal param $varargs string
3077 * @return bool True if the user is allowed to perform *all* of the given actions
3079 public function isAllowedAll( /*...*/ ) {
3080 $permissions = func_get_args();
3081 foreach ( $permissions as $permission ) {
3082 if ( !$this->isAllowed( $permission ) ) {
3090 * Internal mechanics of testing a permission
3091 * @param string $action
3094 public function isAllowed( $action = '' ) {
3095 if ( $action === '' ) {
3096 return true; // In the spirit of DWIM
3098 // Patrolling may not be enabled
3099 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3100 global $wgUseRCPatrol, $wgUseNPPatrol;
3101 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3105 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3106 // by misconfiguration: 0 == 'foo'
3107 return in_array( $action, $this->getRights(), true );
3111 * Check whether to enable recent changes patrol features for this user
3112 * @return bool True or false
3114 public function useRCPatrol() {
3115 global $wgUseRCPatrol;
3116 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3120 * Check whether to enable new pages patrol features for this user
3121 * @return bool True or false
3123 public function useNPPatrol() {
3124 global $wgUseRCPatrol, $wgUseNPPatrol;
3126 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3127 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3132 * Get the WebRequest object to use with this object
3134 * @return WebRequest
3136 public function getRequest() {
3137 if ( $this->mRequest
) {
3138 return $this->mRequest
;
3146 * Get the current skin, loading it if required
3147 * @return Skin The current skin
3148 * @todo FIXME: Need to check the old failback system [AV]
3149 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3151 public function getSkin() {
3152 wfDeprecated( __METHOD__
, '1.18' );
3153 return RequestContext
::getMain()->getSkin();
3157 * Get a WatchedItem for this user and $title.
3159 * @since 1.22 $checkRights parameter added
3160 * @param Title $title
3161 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3162 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3163 * @return WatchedItem
3165 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3166 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3168 if ( isset( $this->mWatchedItems
[$key] ) ) {
3169 return $this->mWatchedItems
[$key];
3172 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3173 $this->mWatchedItems
= array();
3176 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3177 return $this->mWatchedItems
[$key];
3181 * Check the watched status of an article.
3182 * @since 1.22 $checkRights parameter added
3183 * @param Title $title Title of the article to look at
3184 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3185 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3188 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3189 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3194 * @since 1.22 $checkRights parameter added
3195 * @param Title $title Title of the article to look at
3196 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3197 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3199 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3200 $this->getWatchedItem( $title, $checkRights )->addWatch();
3201 $this->invalidateCache();
3205 * Stop watching an article.
3206 * @since 1.22 $checkRights parameter added
3207 * @param Title $title Title of the article to look at
3208 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3209 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3211 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3212 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3213 $this->invalidateCache();
3217 * Clear the user's notification timestamp for the given title.
3218 * If e-notif e-mails are on, they will receive notification mails on
3219 * the next change of the page if it's watched etc.
3220 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3221 * @param Title $title Title of the article to look at
3222 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3224 public function clearNotification( &$title, $oldid = 0 ) {
3225 global $wgUseEnotif, $wgShowUpdatedMarker;
3227 // Do nothing if the database is locked to writes
3228 if ( wfReadOnly() ) {
3232 // Do nothing if not allowed to edit the watchlist
3233 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3237 // If we're working on user's talk page, we should update the talk page message indicator
3238 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3239 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3243 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3245 if ( !$oldid ||
!$nextid ) {
3246 // If we're looking at the latest revision, we should definitely clear it
3247 $this->setNewtalk( false );
3249 // Otherwise we should update its revision, if it's present
3250 if ( $this->getNewtalk() ) {
3251 // Naturally the other one won't clear by itself
3252 $this->setNewtalk( false );
3253 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3258 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3262 if ( $this->isAnon() ) {
3263 // Nothing else to do...
3267 // Only update the timestamp if the page is being watched.
3268 // The query to find out if it is watched is cached both in memcached and per-invocation,
3269 // and when it does have to be executed, it can be on a slave
3270 // If this is the user's newtalk page, we always update the timestamp
3272 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3276 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3280 * Resets all of the given user's page-change notification timestamps.
3281 * If e-notif e-mails are on, they will receive notification mails on
3282 * the next change of any watched page.
3283 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3285 public function clearAllNotifications() {
3286 if ( wfReadOnly() ) {
3290 // Do nothing if not allowed to edit the watchlist
3291 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3295 global $wgUseEnotif, $wgShowUpdatedMarker;
3296 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3297 $this->setNewtalk( false );
3300 $id = $this->getId();
3302 $dbw = wfGetDB( DB_MASTER
);
3303 $dbw->update( 'watchlist',
3304 array( /* SET */ 'wl_notificationtimestamp' => null ),
3305 array( /* WHERE */ 'wl_user' => $id ),
3308 // We also need to clear here the "you have new message" notification for the own user_talk page;
3309 // it's cleared one page view later in WikiPage::doViewUpdates().
3314 * Set a cookie on the user's client. Wrapper for
3315 * WebResponse::setCookie
3316 * @param string $name Name of the cookie to set
3317 * @param string $value Value to set
3318 * @param int $exp Expiration time, as a UNIX time value;
3319 * if 0 or not specified, use the default $wgCookieExpiration
3320 * @param bool $secure
3321 * true: Force setting the secure attribute when setting the cookie
3322 * false: Force NOT setting the secure attribute when setting the cookie
3323 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3324 * @param array $params Array of options sent passed to WebResponse::setcookie()
3326 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3327 $params['secure'] = $secure;
3328 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3332 * Clear a cookie on the user's client
3333 * @param string $name Name of the cookie to clear
3334 * @param bool $secure
3335 * true: Force setting the secure attribute when setting the cookie
3336 * false: Force NOT setting the secure attribute when setting the cookie
3337 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3338 * @param array $params Array of options sent passed to WebResponse::setcookie()
3340 protected function clearCookie( $name, $secure = null, $params = array() ) {
3341 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3345 * Set the default cookies for this session on the user's client.
3347 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3349 * @param bool $secure Whether to force secure/insecure cookies or use default
3350 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3352 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3353 if ( $request === null ) {
3354 $request = $this->getRequest();
3358 if ( 0 == $this->mId
) {
3361 if ( !$this->mToken
) {
3362 // When token is empty or NULL generate a new one and then save it to the database
3363 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3364 // Simply by setting every cell in the user_token column to NULL and letting them be
3365 // regenerated as users log back into the wiki.
3367 $this->saveSettings();
3370 'wsUserID' => $this->mId
,
3371 'wsToken' => $this->mToken
,
3372 'wsUserName' => $this->getName()
3375 'UserID' => $this->mId
,
3376 'UserName' => $this->getName(),
3378 if ( $rememberMe ) {
3379 $cookies['Token'] = $this->mToken
;
3381 $cookies['Token'] = false;
3384 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3386 foreach ( $session as $name => $value ) {
3387 $request->setSessionData( $name, $value );
3389 foreach ( $cookies as $name => $value ) {
3390 if ( $value === false ) {
3391 $this->clearCookie( $name );
3393 $this->setCookie( $name, $value, 0, $secure );
3398 * If wpStickHTTPS was selected, also set an insecure cookie that
3399 * will cause the site to redirect the user to HTTPS, if they access
3400 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3401 * as the one set by centralauth (bug 53538). Also set it to session, or
3402 * standard time setting, based on if rememberme was set.
3404 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3408 $rememberMe ?
0 : null,
3410 array( 'prefix' => '' ) // no prefix
3416 * Log this user out.
3418 public function logout() {
3419 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3425 * Clear the user's cookies and session, and reset the instance cache.
3428 public function doLogout() {
3429 $this->clearInstanceCache( 'defaults' );
3431 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3433 $this->clearCookie( 'UserID' );
3434 $this->clearCookie( 'Token' );
3435 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3437 // Remember when user logged out, to prevent seeing cached pages
3438 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3442 * Save this user's settings into the database.
3443 * @todo Only rarely do all these fields need to be set!
3445 public function saveSettings() {
3449 $this->loadPasswords();
3450 if ( wfReadOnly() ) {
3453 if ( 0 == $this->mId
) {
3457 $this->mTouched
= self
::newTouchedTimestamp();
3458 if ( !$wgAuth->allowSetLocalPassword() ) {
3459 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3462 $dbw = wfGetDB( DB_MASTER
);
3463 $dbw->update( 'user',
3465 'user_name' => $this->mName
,
3466 'user_password' => $this->mPassword
->toString(),
3467 'user_newpassword' => $this->mNewpassword
->toString(),
3468 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3469 'user_real_name' => $this->mRealName
,
3470 'user_email' => $this->mEmail
,
3471 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3472 'user_touched' => $dbw->timestamp( $this->mTouched
),
3473 'user_token' => strval( $this->mToken
),
3474 'user_email_token' => $this->mEmailToken
,
3475 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3476 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3477 ), array( /* WHERE */
3478 'user_id' => $this->mId
3482 $this->saveOptions();
3484 wfRunHooks( 'UserSaveSettings', array( $this ) );
3485 $this->clearSharedCache();
3486 $this->getUserPage()->invalidateCache();
3490 * If only this user's username is known, and it exists, return the user ID.
3493 public function idForName() {
3494 $s = trim( $this->getName() );
3499 $dbr = wfGetDB( DB_SLAVE
);
3500 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3501 if ( $id === false ) {
3508 * Add a user to the database, return the user object
3510 * @param string $name Username to add
3511 * @param array $params Array of Strings Non-default parameters to save to
3512 * the database as user_* fields:
3513 * - password: The user's password hash. Password logins will be disabled
3514 * if this is omitted.
3515 * - newpassword: Hash for a temporary password that has been mailed to
3517 * - email: The user's email address.
3518 * - email_authenticated: The email authentication timestamp.
3519 * - real_name: The user's real name.
3520 * - options: An associative array of non-default options.
3521 * - token: Random authentication token. Do not set.
3522 * - registration: Registration timestamp. Do not set.
3524 * @return User|null User object, or null if the username already exists.
3526 public static function createNew( $name, $params = array() ) {
3529 $user->loadPasswords();
3530 $user->setToken(); // init token
3531 if ( isset( $params['options'] ) ) {
3532 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3533 unset( $params['options'] );
3535 $dbw = wfGetDB( DB_MASTER
);
3536 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3539 'user_id' => $seqVal,
3540 'user_name' => $name,
3541 'user_password' => $user->mPassword
->toString(),
3542 'user_newpassword' => $user->mNewpassword
->toString(),
3543 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3544 'user_email' => $user->mEmail
,
3545 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3546 'user_real_name' => $user->mRealName
,
3547 'user_token' => strval( $user->mToken
),
3548 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3549 'user_editcount' => 0,
3550 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3552 foreach ( $params as $name => $value ) {
3553 $fields["user_$name"] = $value;
3555 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3556 if ( $dbw->affectedRows() ) {
3557 $newUser = User
::newFromId( $dbw->insertId() );
3565 * Add this existing user object to the database. If the user already
3566 * exists, a fatal status object is returned, and the user object is
3567 * initialised with the data from the database.
3569 * Previously, this function generated a DB error due to a key conflict
3570 * if the user already existed. Many extension callers use this function
3571 * in code along the lines of:
3573 * $user = User::newFromName( $name );
3574 * if ( !$user->isLoggedIn() ) {
3575 * $user->addToDatabase();
3577 * // do something with $user...
3579 * However, this was vulnerable to a race condition (bug 16020). By
3580 * initialising the user object if the user exists, we aim to support this
3581 * calling sequence as far as possible.
3583 * Note that if the user exists, this function will acquire a write lock,
3584 * so it is still advisable to make the call conditional on isLoggedIn(),
3585 * and to commit the transaction after calling.
3587 * @throws MWException
3590 public function addToDatabase() {
3592 $this->loadPasswords();
3593 if ( !$this->mToken
) {
3594 $this->setToken(); // init token
3597 $this->mTouched
= self
::newTouchedTimestamp();
3599 $dbw = wfGetDB( DB_MASTER
);
3600 $inWrite = $dbw->writesOrCallbacksPending();
3601 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3602 $dbw->insert( 'user',
3604 'user_id' => $seqVal,
3605 'user_name' => $this->mName
,
3606 'user_password' => $this->mPassword
->toString(),
3607 'user_newpassword' => $this->mNewpassword
->toString(),
3608 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3609 'user_email' => $this->mEmail
,
3610 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3611 'user_real_name' => $this->mRealName
,
3612 'user_token' => strval( $this->mToken
),
3613 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3614 'user_editcount' => 0,
3615 'user_touched' => $dbw->timestamp( $this->mTouched
),
3619 if ( !$dbw->affectedRows() ) {
3620 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3621 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3623 // Can't commit due to pending writes that may need atomicity.
3624 // This may cause some lock contention unlike the case below.
3625 $options = array( 'LOCK IN SHARE MODE' );
3626 $flags = self
::READ_LOCKING
;
3628 // Often, this case happens early in views before any writes when
3629 // using CentralAuth. It's should be OK to commit and break the snapshot.
3630 $dbw->commit( __METHOD__
, 'flush' );
3634 $this->mId
= $dbw->selectField( 'user', 'user_id',
3635 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3638 if ( $this->loadFromDatabase( $flags ) ) {
3643 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3644 "to insert user '{$this->mName}' row, but it was not present in select!" );
3646 return Status
::newFatal( 'userexists' );
3648 $this->mId
= $dbw->insertId();
3650 // Clear instance cache other than user table data, which is already accurate
3651 $this->clearInstanceCache();
3653 $this->saveOptions();
3654 return Status
::newGood();
3658 * If this user is logged-in and blocked,
3659 * block any IP address they've successfully logged in from.
3660 * @return bool A block was spread
3662 public function spreadAnyEditBlock() {
3663 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3664 return $this->spreadBlock();
3670 * If this (non-anonymous) user is blocked,
3671 * block the IP address they've successfully logged in from.
3672 * @return bool A block was spread
3674 protected function spreadBlock() {
3675 wfDebug( __METHOD__
. "()\n" );
3677 if ( $this->mId
== 0 ) {
3681 $userblock = Block
::newFromTarget( $this->getName() );
3682 if ( !$userblock ) {
3686 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3690 * Get whether the user is explicitly blocked from account creation.
3691 * @return bool|Block
3693 public function isBlockedFromCreateAccount() {
3694 $this->getBlockedStatus();
3695 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3696 return $this->mBlock
;
3699 # bug 13611: if the IP address the user is trying to create an account from is
3700 # blocked with createaccount disabled, prevent new account creation there even
3701 # when the user is logged in
3702 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3703 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3705 return $this->mBlockedFromCreateAccount
instanceof Block
3706 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3707 ?
$this->mBlockedFromCreateAccount
3712 * Get whether the user is blocked from using Special:Emailuser.
3715 public function isBlockedFromEmailuser() {
3716 $this->getBlockedStatus();
3717 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3721 * Get whether the user is allowed to create an account.
3724 public function isAllowedToCreateAccount() {
3725 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3729 * Get this user's personal page title.
3731 * @return Title User's personal page title
3733 public function getUserPage() {
3734 return Title
::makeTitle( NS_USER
, $this->getName() );
3738 * Get this user's talk page title.
3740 * @return Title User's talk page title
3742 public function getTalkPage() {
3743 $title = $this->getUserPage();
3744 return $title->getTalkPage();
3748 * Determine whether the user is a newbie. Newbies are either
3749 * anonymous IPs, or the most recently created accounts.
3752 public function isNewbie() {
3753 return !$this->isAllowed( 'autoconfirmed' );
3757 * Check to see if the given clear-text password is one of the accepted passwords
3758 * @param string $password User password
3759 * @return bool True if the given password is correct, otherwise False
3761 public function checkPassword( $password ) {
3762 global $wgAuth, $wgLegacyEncoding;
3763 $this->loadPasswords();
3765 // Certain authentication plugins do NOT want to save
3766 // domain passwords in a mysql database, so we should
3767 // check this (in case $wgAuth->strict() is false).
3769 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3771 } elseif ( $wgAuth->strict() ) {
3772 // Auth plugin doesn't allow local authentication
3774 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3775 // Auth plugin doesn't allow local authentication for this user name
3779 $passwordFactory = self
::getPasswordFactory();
3780 if ( !$this->mPassword
->equals( $password ) ) {
3781 if ( $wgLegacyEncoding ) {
3782 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3783 // Check for this with iconv
3784 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3785 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3793 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3794 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3795 $this->saveSettings();
3802 * Check if the given clear-text password matches the temporary password
3803 * sent by e-mail for password reset operations.
3805 * @param string $plaintext
3807 * @return bool True if matches, false otherwise
3809 public function checkTemporaryPassword( $plaintext ) {
3810 global $wgNewPasswordExpiry;
3813 $this->loadPasswords();
3814 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3815 if ( is_null( $this->mNewpassTime
) ) {
3818 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3819 return ( time() < $expiry );
3826 * Alias for getEditToken.
3827 * @deprecated since 1.19, use getEditToken instead.
3829 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3830 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3831 * @return string The new edit token
3833 public function editToken( $salt = '', $request = null ) {
3834 wfDeprecated( __METHOD__
, '1.19' );
3835 return $this->getEditToken( $salt, $request );
3839 * Initialize (if necessary) and return a session token value
3840 * which can be used in edit forms to show that the user's
3841 * login credentials aren't being hijacked with a foreign form
3846 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3847 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3848 * @return string The new edit token
3850 public function getEditToken( $salt = '', $request = null ) {
3851 if ( $request == null ) {
3852 $request = $this->getRequest();
3855 if ( $this->isAnon() ) {
3856 return self
::EDIT_TOKEN_SUFFIX
;
3858 $token = $request->getSessionData( 'wsEditToken' );
3859 if ( $token === null ) {
3860 $token = MWCryptRand
::generateHex( 32 );
3861 $request->setSessionData( 'wsEditToken', $token );
3863 if ( is_array( $salt ) ) {
3864 $salt = implode( '|', $salt );
3866 return md5( $token . $salt ) . self
::EDIT_TOKEN_SUFFIX
;
3871 * Generate a looking random token for various uses.
3873 * @return string The new random token
3874 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3875 * wfRandomString for pseudo-randomness.
3877 public static function generateToken() {
3878 return MWCryptRand
::generateHex( 32 );
3882 * Check given value against the token value stored in the session.
3883 * A match should confirm that the form was submitted from the
3884 * user's own login session, not a form submission from a third-party
3887 * @param string $val Input value to compare
3888 * @param string $salt Optional function-specific data for hashing
3889 * @param WebRequest|null $request Object to use or null to use $wgRequest
3890 * @return bool Whether the token matches
3892 public function matchEditToken( $val, $salt = '', $request = null ) {
3893 $sessionToken = $this->getEditToken( $salt, $request );
3894 if ( $val != $sessionToken ) {
3895 wfDebug( "User::matchEditToken: broken session data\n" );
3898 return $val == $sessionToken;
3902 * Check given value against the token value stored in the session,
3903 * ignoring the suffix.
3905 * @param string $val Input value to compare
3906 * @param string $salt Optional function-specific data for hashing
3907 * @param WebRequest|null $request Object to use or null to use $wgRequest
3908 * @return bool Whether the token matches
3910 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3911 $sessionToken = $this->getEditToken( $salt, $request );
3912 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3916 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3917 * mail to the user's given address.
3919 * @param string $type Message to send, either "created", "changed" or "set"
3922 public function sendConfirmationMail( $type = 'created' ) {
3924 $expiration = null; // gets passed-by-ref and defined in next line.
3925 $token = $this->confirmationToken( $expiration );
3926 $url = $this->confirmationTokenUrl( $token );
3927 $invalidateURL = $this->invalidationTokenUrl( $token );
3928 $this->saveSettings();
3930 if ( $type == 'created' ||
$type === false ) {
3931 $message = 'confirmemail_body';
3932 } elseif ( $type === true ) {
3933 $message = 'confirmemail_body_changed';
3935 // Messages: confirmemail_body_changed, confirmemail_body_set
3936 $message = 'confirmemail_body_' . $type;
3939 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3940 wfMessage( $message,
3941 $this->getRequest()->getIP(),
3944 $wgLang->timeanddate( $expiration, false ),
3946 $wgLang->date( $expiration, false ),
3947 $wgLang->time( $expiration, false ) )->text() );
3951 * Send an e-mail to this user's account. Does not check for
3952 * confirmed status or validity.
3954 * @param string $subject Message subject
3955 * @param string $body Message body
3956 * @param string $from Optional From address; if unspecified, default
3957 * $wgPasswordSender will be used.
3958 * @param string $replyto Reply-To address
3961 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3962 if ( is_null( $from ) ) {
3963 global $wgPasswordSender;
3964 $sender = new MailAddress( $wgPasswordSender,
3965 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3967 $sender = new MailAddress( $from );
3970 $to = new MailAddress( $this );
3971 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3975 * Generate, store, and return a new e-mail confirmation code.
3976 * A hash (unsalted, since it's used as a key) is stored.
3978 * @note Call saveSettings() after calling this function to commit
3979 * this change to the database.
3981 * @param string &$expiration Accepts the expiration time
3982 * @return string New token
3984 protected function confirmationToken( &$expiration ) {
3985 global $wgUserEmailConfirmationTokenExpiry;
3987 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3988 $expiration = wfTimestamp( TS_MW
, $expires );
3990 $token = MWCryptRand
::generateHex( 32 );
3991 $hash = md5( $token );
3992 $this->mEmailToken
= $hash;
3993 $this->mEmailTokenExpires
= $expiration;
3998 * Return a URL the user can use to confirm their email address.
3999 * @param string $token Accepts the email confirmation token
4000 * @return string New token URL
4002 protected function confirmationTokenUrl( $token ) {
4003 return $this->getTokenUrl( 'ConfirmEmail', $token );
4007 * Return a URL the user can use to invalidate their email address.
4008 * @param string $token Accepts the email confirmation token
4009 * @return string New token URL
4011 protected function invalidationTokenUrl( $token ) {
4012 return $this->getTokenUrl( 'InvalidateEmail', $token );
4016 * Internal function to format the e-mail validation/invalidation URLs.
4017 * This uses a quickie hack to use the
4018 * hardcoded English names of the Special: pages, for ASCII safety.
4020 * @note Since these URLs get dropped directly into emails, using the
4021 * short English names avoids insanely long URL-encoded links, which
4022 * also sometimes can get corrupted in some browsers/mailers
4023 * (bug 6957 with Gmail and Internet Explorer).
4025 * @param string $page Special page
4026 * @param string $token Token
4027 * @return string Formatted URL
4029 protected function getTokenUrl( $page, $token ) {
4030 // Hack to bypass localization of 'Special:'
4031 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4032 return $title->getCanonicalURL();
4036 * Mark the e-mail address confirmed.
4038 * @note Call saveSettings() after calling this function to commit the change.
4042 public function confirmEmail() {
4043 // Check if it's already confirmed, so we don't touch the database
4044 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4045 if ( !$this->isEmailConfirmed() ) {
4046 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4047 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4053 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4054 * address if it was already confirmed.
4056 * @note Call saveSettings() after calling this function to commit the change.
4057 * @return bool Returns true
4059 public function invalidateEmail() {
4061 $this->mEmailToken
= null;
4062 $this->mEmailTokenExpires
= null;
4063 $this->setEmailAuthenticationTimestamp( null );
4065 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4070 * Set the e-mail authentication timestamp.
4071 * @param string $timestamp TS_MW timestamp
4073 public function setEmailAuthenticationTimestamp( $timestamp ) {
4075 $this->mEmailAuthenticated
= $timestamp;
4076 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4080 * Is this user allowed to send e-mails within limits of current
4081 * site configuration?
4084 public function canSendEmail() {
4085 global $wgEnableEmail, $wgEnableUserEmail;
4086 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4089 $canSend = $this->isEmailConfirmed();
4090 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4095 * Is this user allowed to receive e-mails within limits of current
4096 * site configuration?
4099 public function canReceiveEmail() {
4100 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4104 * Is this user's e-mail address valid-looking and confirmed within
4105 * limits of the current site configuration?
4107 * @note If $wgEmailAuthentication is on, this may require the user to have
4108 * confirmed their address by returning a code or using a password
4109 * sent to the address from the wiki.
4113 public function isEmailConfirmed() {
4114 global $wgEmailAuthentication;
4117 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4118 if ( $this->isAnon() ) {
4121 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4124 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4134 * Check whether there is an outstanding request for e-mail confirmation.
4137 public function isEmailConfirmationPending() {
4138 global $wgEmailAuthentication;
4139 return $wgEmailAuthentication &&
4140 !$this->isEmailConfirmed() &&
4141 $this->mEmailToken
&&
4142 $this->mEmailTokenExpires
> wfTimestamp();
4146 * Get the timestamp of account creation.
4148 * @return string|bool|null Timestamp of account creation, false for
4149 * non-existent/anonymous user accounts, or null if existing account
4150 * but information is not in database.
4152 public function getRegistration() {
4153 if ( $this->isAnon() ) {
4157 return $this->mRegistration
;
4161 * Get the timestamp of the first edit
4163 * @return string|bool Timestamp of first edit, or false for
4164 * non-existent/anonymous user accounts.
4166 public function getFirstEditTimestamp() {
4167 if ( $this->getId() == 0 ) {
4168 return false; // anons
4170 $dbr = wfGetDB( DB_SLAVE
);
4171 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4172 array( 'rev_user' => $this->getId() ),
4174 array( 'ORDER BY' => 'rev_timestamp ASC' )
4177 return false; // no edits
4179 return wfTimestamp( TS_MW
, $time );
4183 * Get the permissions associated with a given list of groups
4185 * @param array $groups Array of Strings List of internal group names
4186 * @return array Array of Strings List of permission key names for given groups combined
4188 public static function getGroupPermissions( $groups ) {
4189 global $wgGroupPermissions, $wgRevokePermissions;
4191 // grant every granted permission first
4192 foreach ( $groups as $group ) {
4193 if ( isset( $wgGroupPermissions[$group] ) ) {
4194 $rights = array_merge( $rights,
4195 // array_filter removes empty items
4196 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4199 // now revoke the revoked permissions
4200 foreach ( $groups as $group ) {
4201 if ( isset( $wgRevokePermissions[$group] ) ) {
4202 $rights = array_diff( $rights,
4203 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4206 return array_unique( $rights );
4210 * Get all the groups who have a given permission
4212 * @param string $role Role to check
4213 * @return array Array of Strings List of internal group names with the given permission
4215 public static function getGroupsWithPermission( $role ) {
4216 global $wgGroupPermissions;
4217 $allowedGroups = array();
4218 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4219 if ( self
::groupHasPermission( $group, $role ) ) {
4220 $allowedGroups[] = $group;
4223 return $allowedGroups;
4227 * Check, if the given group has the given permission
4229 * If you're wanting to check whether all users have a permission, use
4230 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4234 * @param string $group Group to check
4235 * @param string $role Role to check
4238 public static function groupHasPermission( $group, $role ) {
4239 global $wgGroupPermissions, $wgRevokePermissions;
4240 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4241 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4245 * Check if all users have the given permission
4248 * @param string $right Right to check
4251 public static function isEveryoneAllowed( $right ) {
4252 global $wgGroupPermissions, $wgRevokePermissions;
4253 static $cache = array();
4255 // Use the cached results, except in unit tests which rely on
4256 // being able change the permission mid-request
4257 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4258 return $cache[$right];
4261 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4262 $cache[$right] = false;
4266 // If it's revoked anywhere, then everyone doesn't have it
4267 foreach ( $wgRevokePermissions as $rights ) {
4268 if ( isset( $rights[$right] ) && $rights[$right] ) {
4269 $cache[$right] = false;
4274 // Allow extensions (e.g. OAuth) to say false
4275 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4276 $cache[$right] = false;
4280 $cache[$right] = true;
4285 * Get the localized descriptive name for a group, if it exists
4287 * @param string $group Internal group name
4288 * @return string Localized descriptive group name
4290 public static function getGroupName( $group ) {
4291 $msg = wfMessage( "group-$group" );
4292 return $msg->isBlank() ?
$group : $msg->text();
4296 * Get the localized descriptive name for a member of a group, if it exists
4298 * @param string $group Internal group name
4299 * @param string $username Username for gender (since 1.19)
4300 * @return string Localized name for group member
4302 public static function getGroupMember( $group, $username = '#' ) {
4303 $msg = wfMessage( "group-$group-member", $username );
4304 return $msg->isBlank() ?
$group : $msg->text();
4308 * Return the set of defined explicit groups.
4309 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4310 * are not included, as they are defined automatically, not in the database.
4311 * @return array Array of internal group names
4313 public static function getAllGroups() {
4314 global $wgGroupPermissions, $wgRevokePermissions;
4316 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4317 self
::getImplicitGroups()
4322 * Get a list of all available permissions.
4323 * @return array Array of permission names
4325 public static function getAllRights() {
4326 if ( self
::$mAllRights === false ) {
4327 global $wgAvailableRights;
4328 if ( count( $wgAvailableRights ) ) {
4329 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4331 self
::$mAllRights = self
::$mCoreRights;
4333 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4335 return self
::$mAllRights;
4339 * Get a list of implicit groups
4340 * @return array Array of Strings Array of internal group names
4342 public static function getImplicitGroups() {
4343 global $wgImplicitGroups;
4345 $groups = $wgImplicitGroups;
4346 # Deprecated, use $wgImplictGroups instead
4347 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4353 * Get the title of a page describing a particular group
4355 * @param string $group Internal group name
4356 * @return Title|bool Title of the page if it exists, false otherwise
4358 public static function getGroupPage( $group ) {
4359 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4360 if ( $msg->exists() ) {
4361 $title = Title
::newFromText( $msg->text() );
4362 if ( is_object( $title ) ) {
4370 * Create a link to the group in HTML, if available;
4371 * else return the group name.
4373 * @param string $group Internal name of the group
4374 * @param string $text The text of the link
4375 * @return string HTML link to the group
4377 public static function makeGroupLinkHTML( $group, $text = '' ) {
4378 if ( $text == '' ) {
4379 $text = self
::getGroupName( $group );
4381 $title = self
::getGroupPage( $group );
4383 return Linker
::link( $title, htmlspecialchars( $text ) );
4390 * Create a link to the group in Wikitext, if available;
4391 * else return the group name.
4393 * @param string $group Internal name of the group
4394 * @param string $text The text of the link
4395 * @return string Wikilink to the group
4397 public static function makeGroupLinkWiki( $group, $text = '' ) {
4398 if ( $text == '' ) {
4399 $text = self
::getGroupName( $group );
4401 $title = self
::getGroupPage( $group );
4403 $page = $title->getPrefixedText();
4404 return "[[$page|$text]]";
4411 * Returns an array of the groups that a particular group can add/remove.
4413 * @param string $group The group to check for whether it can add/remove
4414 * @return array Array( 'add' => array( addablegroups ),
4415 * 'remove' => array( removablegroups ),
4416 * 'add-self' => array( addablegroups to self),
4417 * 'remove-self' => array( removable groups from self) )
4419 public static function changeableByGroup( $group ) {
4420 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4424 'remove' => array(),
4425 'add-self' => array(),
4426 'remove-self' => array()
4429 if ( empty( $wgAddGroups[$group] ) ) {
4430 // Don't add anything to $groups
4431 } elseif ( $wgAddGroups[$group] === true ) {
4432 // You get everything
4433 $groups['add'] = self
::getAllGroups();
4434 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4435 $groups['add'] = $wgAddGroups[$group];
4438 // Same thing for remove
4439 if ( empty( $wgRemoveGroups[$group] ) ) {
4440 } elseif ( $wgRemoveGroups[$group] === true ) {
4441 $groups['remove'] = self
::getAllGroups();
4442 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4443 $groups['remove'] = $wgRemoveGroups[$group];
4446 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4447 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4448 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4449 if ( is_int( $key ) ) {
4450 $wgGroupsAddToSelf['user'][] = $value;
4455 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4456 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4457 if ( is_int( $key ) ) {
4458 $wgGroupsRemoveFromSelf['user'][] = $value;
4463 // Now figure out what groups the user can add to him/herself
4464 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4465 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4466 // No idea WHY this would be used, but it's there
4467 $groups['add-self'] = User
::getAllGroups();
4468 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4469 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4472 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4473 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4474 $groups['remove-self'] = User
::getAllGroups();
4475 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4476 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4483 * Returns an array of groups that this user can add and remove
4484 * @return array Array( 'add' => array( addablegroups ),
4485 * 'remove' => array( removablegroups ),
4486 * 'add-self' => array( addablegroups to self),
4487 * 'remove-self' => array( removable groups from self) )
4489 public function changeableGroups() {
4490 if ( $this->isAllowed( 'userrights' ) ) {
4491 // This group gives the right to modify everything (reverse-
4492 // compatibility with old "userrights lets you change
4494 // Using array_merge to make the groups reindexed
4495 $all = array_merge( User
::getAllGroups() );
4499 'add-self' => array(),
4500 'remove-self' => array()
4504 // Okay, it's not so simple, we will have to go through the arrays
4507 'remove' => array(),
4508 'add-self' => array(),
4509 'remove-self' => array()
4511 $addergroups = $this->getEffectiveGroups();
4513 foreach ( $addergroups as $addergroup ) {
4514 $groups = array_merge_recursive(
4515 $groups, $this->changeableByGroup( $addergroup )
4517 $groups['add'] = array_unique( $groups['add'] );
4518 $groups['remove'] = array_unique( $groups['remove'] );
4519 $groups['add-self'] = array_unique( $groups['add-self'] );
4520 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4526 * Increment the user's edit-count field.
4527 * Will have no effect for anonymous users.
4529 public function incEditCount() {
4530 if ( !$this->isAnon() ) {
4531 $dbw = wfGetDB( DB_MASTER
);
4534 array( 'user_editcount=user_editcount+1' ),
4535 array( 'user_id' => $this->getId() ),
4539 // Lazy initialization check...
4540 if ( $dbw->affectedRows() == 0 ) {
4541 // Now here's a goddamn hack...
4542 $dbr = wfGetDB( DB_SLAVE
);
4543 if ( $dbr !== $dbw ) {
4544 // If we actually have a slave server, the count is
4545 // at least one behind because the current transaction
4546 // has not been committed and replicated.
4547 $this->initEditCount( 1 );
4549 // But if DB_SLAVE is selecting the master, then the
4550 // count we just read includes the revision that was
4551 // just added in the working transaction.
4552 $this->initEditCount();
4556 // edit count in user cache too
4557 $this->invalidateCache();
4561 * Initialize user_editcount from data out of the revision table
4563 * @param int $add Edits to add to the count from the revision table
4564 * @return int Number of edits
4566 protected function initEditCount( $add = 0 ) {
4567 // Pull from a slave to be less cruel to servers
4568 // Accuracy isn't the point anyway here
4569 $dbr = wfGetDB( DB_SLAVE
);
4570 $count = (int)$dbr->selectField(
4573 array( 'rev_user' => $this->getId() ),
4576 $count = $count +
$add;
4578 $dbw = wfGetDB( DB_MASTER
);
4581 array( 'user_editcount' => $count ),
4582 array( 'user_id' => $this->getId() ),
4590 * Get the description of a given right
4592 * @param string $right Right to query
4593 * @return string Localized description of the right
4595 public static function getRightDescription( $right ) {
4596 $key = "right-$right";
4597 $msg = wfMessage( $key );
4598 return $msg->isBlank() ?
$right : $msg->text();
4602 * Make a new-style password hash
4604 * @param string $password Plain-text password
4605 * @param bool|string $salt Optional salt, may be random or the user ID.
4606 * If unspecified or false, will generate one automatically
4607 * @return string Password hash
4608 * @deprecated since 1.24, use Password class
4610 public static function crypt( $password, $salt = false ) {
4611 wfDeprecated( __METHOD__
, '1.24' );
4612 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4613 return $hash->toString();
4617 * Compare a password hash with a plain-text password. Requires the user
4618 * ID if there's a chance that the hash is an old-style hash.
4620 * @param string $hash Password hash
4621 * @param string $password Plain-text password to compare
4622 * @param string|bool $userId User ID for old-style password salt
4625 * @deprecated since 1.24, use Password class
4627 public static function comparePasswords( $hash, $password, $userId = false ) {
4628 wfDeprecated( __METHOD__
, '1.24' );
4630 // Check for *really* old password hashes that don't even have a type
4631 // The old hash format was just an md5 hex hash, with no type information
4632 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4633 global $wgPasswordSalt;
4634 if ( $wgPasswordSalt ) {
4635 $password = ":B:{$userId}:{$hash}";
4637 $password = ":A:{$hash}";
4641 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4642 return $hash->equals( $password );
4646 * Add a newuser log entry for this user.
4647 * Before 1.19 the return value was always true.
4649 * @param string|bool $action Account creation type.
4650 * - String, one of the following values:
4651 * - 'create' for an anonymous user creating an account for himself.
4652 * This will force the action's performer to be the created user itself,
4653 * no matter the value of $wgUser
4654 * - 'create2' for a logged in user creating an account for someone else
4655 * - 'byemail' when the created user will receive its password by e-mail
4656 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4657 * - Boolean means whether the account was created by e-mail (deprecated):
4658 * - true will be converted to 'byemail'
4659 * - false will be converted to 'create' if this object is the same as
4660 * $wgUser and to 'create2' otherwise
4662 * @param string $reason User supplied reason
4664 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4666 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4667 global $wgUser, $wgNewUserLog;
4668 if ( empty( $wgNewUserLog ) ) {
4669 return true; // disabled
4672 if ( $action === true ) {
4673 $action = 'byemail';
4674 } elseif ( $action === false ) {
4675 if ( $this->getName() == $wgUser->getName() ) {
4678 $action = 'create2';
4682 if ( $action === 'create' ||
$action === 'autocreate' ) {
4685 $performer = $wgUser;
4688 $logEntry = new ManualLogEntry( 'newusers', $action );
4689 $logEntry->setPerformer( $performer );
4690 $logEntry->setTarget( $this->getUserPage() );
4691 $logEntry->setComment( $reason );
4692 $logEntry->setParameters( array(
4693 '4::userid' => $this->getId(),
4695 $logid = $logEntry->insert();
4697 if ( $action !== 'autocreate' ) {
4698 $logEntry->publish( $logid );
4705 * Add an autocreate newuser log entry for this user
4706 * Used by things like CentralAuth and perhaps other authplugins.
4707 * Consider calling addNewUserLogEntry() directly instead.
4711 public function addNewUserLogEntryAutoCreate() {
4712 $this->addNewUserLogEntry( 'autocreate' );
4718 * Load the user options either from cache, the database or an array
4720 * @param array $data Rows for the current user out of the user_properties table
4722 protected function loadOptions( $data = null ) {
4727 if ( $this->mOptionsLoaded
) {
4731 $this->mOptions
= self
::getDefaultOptions();
4733 if ( !$this->getId() ) {
4734 // For unlogged-in users, load language/variant options from request.
4735 // There's no need to do it for logged-in users: they can set preferences,
4736 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4737 // so don't override user's choice (especially when the user chooses site default).
4738 $variant = $wgContLang->getDefaultVariant();
4739 $this->mOptions
['variant'] = $variant;
4740 $this->mOptions
['language'] = $variant;
4741 $this->mOptionsLoaded
= true;
4745 // Maybe load from the object
4746 if ( !is_null( $this->mOptionOverrides
) ) {
4747 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4748 foreach ( $this->mOptionOverrides
as $key => $value ) {
4749 $this->mOptions
[$key] = $value;
4752 if ( !is_array( $data ) ) {
4753 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4754 // Load from database
4755 $dbr = wfGetDB( DB_SLAVE
);
4757 $res = $dbr->select(
4759 array( 'up_property', 'up_value' ),
4760 array( 'up_user' => $this->getId() ),
4764 $this->mOptionOverrides
= array();
4766 foreach ( $res as $row ) {
4767 $data[$row->up_property
] = $row->up_value
;
4770 foreach ( $data as $property => $value ) {
4771 $this->mOptionOverrides
[$property] = $value;
4772 $this->mOptions
[$property] = $value;
4776 $this->mOptionsLoaded
= true;
4778 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4782 * Saves the non-default options for this user, as previously set e.g. via
4783 * setOption(), in the database's "user_properties" (preferences) table.
4784 * Usually used via saveSettings().
4786 protected function saveOptions() {
4787 $this->loadOptions();
4789 // Not using getOptions(), to keep hidden preferences in database
4790 $saveOptions = $this->mOptions
;
4792 // Allow hooks to abort, for instance to save to a global profile.
4793 // Reset options to default state before saving.
4794 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4798 $userId = $this->getId();
4800 $insert_rows = array(); // all the new preference rows
4801 foreach ( $saveOptions as $key => $value ) {
4802 // Don't bother storing default values
4803 $defaultOption = self
::getDefaultOption( $key );
4804 if ( ( $defaultOption === null && $value !== false && $value !== null )
4805 ||
$value != $defaultOption
4807 $insert_rows[] = array(
4808 'up_user' => $userId,
4809 'up_property' => $key,
4810 'up_value' => $value,
4815 $dbw = wfGetDB( DB_MASTER
);
4817 $res = $dbw->select( 'user_properties',
4818 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4820 // Find prior rows that need to be removed or updated. These rows will
4821 // all be deleted (the later so that INSERT IGNORE applies the new values).
4822 $keysDelete = array();
4823 foreach ( $res as $row ) {
4824 if ( !isset( $saveOptions[$row->up_property
] )
4825 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4827 $keysDelete[] = $row->up_property
;
4831 if ( count( $keysDelete ) ) {
4832 // Do the DELETE by PRIMARY KEY for prior rows.
4833 // In the past a very large portion of calls to this function are for setting
4834 // 'rememberpassword' for new accounts (a preference that has since been removed).
4835 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4836 // caused gap locks on [max user ID,+infinity) which caused high contention since
4837 // updates would pile up on each other as they are for higher (newer) user IDs.
4838 // It might not be necessary these days, but it shouldn't hurt either.
4839 $dbw->delete( 'user_properties',
4840 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4842 // Insert the new preference rows
4843 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4847 * Lazily instantiate and return a factory object for making passwords
4849 * @return PasswordFactory
4851 public static function getPasswordFactory() {
4852 if ( self
::$mPasswordFactory === null ) {
4853 self
::$mPasswordFactory = new PasswordFactory();
4854 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4857 return self
::$mPasswordFactory;
4861 * Provide an array of HTML5 attributes to put on an input element
4862 * intended for the user to enter a new password. This may include
4863 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4865 * Do *not* use this when asking the user to enter his current password!
4866 * Regardless of configuration, users may have invalid passwords for whatever
4867 * reason (e.g., they were set before requirements were tightened up).
4868 * Only use it when asking for a new password, like on account creation or
4871 * Obviously, you still need to do server-side checking.
4873 * NOTE: A combination of bugs in various browsers means that this function
4874 * actually just returns array() unconditionally at the moment. May as
4875 * well keep it around for when the browser bugs get fixed, though.
4877 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4879 * @return array Array of HTML attributes suitable for feeding to
4880 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4881 * That will get confused by the boolean attribute syntax used.)
4883 public static function passwordChangeInputAttribs() {
4884 global $wgMinimalPasswordLength;
4886 if ( $wgMinimalPasswordLength == 0 ) {
4890 # Note that the pattern requirement will always be satisfied if the
4891 # input is empty, so we need required in all cases.
4893 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4894 # if e-mail confirmation is being used. Since HTML5 input validation
4895 # is b0rked anyway in some browsers, just return nothing. When it's
4896 # re-enabled, fix this code to not output required for e-mail
4898 #$ret = array( 'required' );
4901 # We can't actually do this right now, because Opera 9.6 will print out
4902 # the entered password visibly in its error message! When other
4903 # browsers add support for this attribute, or Opera fixes its support,
4904 # we can add support with a version check to avoid doing this on Opera
4905 # versions where it will be a problem. Reported to Opera as
4906 # DSK-262266, but they don't have a public bug tracker for us to follow.
4908 if ( $wgMinimalPasswordLength > 1 ) {
4909 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4910 $ret['title'] = wfMessage( 'passwordtooshort' )
4911 ->numParams( $wgMinimalPasswordLength )->text();
4919 * Return the list of user fields that should be selected to create
4920 * a new user object.
4923 public static function selectFields() {
4931 'user_email_authenticated',
4933 'user_email_token_expires',
4934 'user_registration',
4940 * Factory function for fatal permission-denied errors
4943 * @param string $permission User right required
4946 static function newFatalPermissionDeniedStatus( $permission ) {
4949 $groups = array_map(
4950 array( 'User', 'makeGroupLinkWiki' ),
4951 User
::getGroupsWithPermission( $permission )
4955 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4957 return Status
::newFatal( 'badaccess-group0' );