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 $t = ( $validate === 'valid' ) ?
912 Title
::newFromText( $name ) : Title
::makeTitle( NS_USER
, $name );
913 // Check for invalid titles
914 if ( is_null( $t ) ) {
918 // Reject various classes of invalid names
920 $name = $wgAuth->getCanonicalName( $t->getText() );
922 switch ( $validate ) {
926 if ( !User
::isValidUserName( $name ) ) {
931 if ( !User
::isUsableName( $name ) ) {
936 if ( !User
::isCreatableName( $name ) ) {
941 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__
);
947 * Count the number of edits of a user
949 * @param int $uid User ID to check
950 * @return int The user's edit count
952 * @deprecated since 1.21 in favour of User::getEditCount
954 public static function edits( $uid ) {
955 wfDeprecated( __METHOD__
, '1.21' );
956 $user = self
::newFromId( $uid );
957 return $user->getEditCount();
961 * Return a random password.
963 * @return string New random password
965 public static function randomPassword() {
966 global $wgMinimalPasswordLength;
967 // Decide the final password length based on our min password length,
968 // stopping at a minimum of 10 chars.
969 $length = max( 10, $wgMinimalPasswordLength );
970 // Multiply by 1.25 to get the number of hex characters we need
971 $length = $length * 1.25;
972 // Generate random hex chars
973 $hex = MWCryptRand
::generateHex( $length );
974 // Convert from base 16 to base 32 to get a proper password like string
975 return wfBaseConvert( $hex, 16, 32 );
979 * Set cached properties to default.
981 * @note This no longer clears uncached lazy-initialised properties;
982 * the constructor does that instead.
984 * @param string|bool $name
986 public function loadDefaults( $name = false ) {
987 wfProfileIn( __METHOD__
);
989 $passwordFactory = self
::getPasswordFactory();
992 $this->mName
= $name;
993 $this->mRealName
= '';
994 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
995 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
996 $this->mNewpassTime
= null;
998 $this->mOptionOverrides
= null;
999 $this->mOptionsLoaded
= false;
1001 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1002 if ( $loggedOut !== null ) {
1003 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1005 $this->mTouched
= '1'; # Allow any pages to be cached
1008 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1009 $this->mEmailAuthenticated
= null;
1010 $this->mEmailToken
= '';
1011 $this->mEmailTokenExpires
= null;
1012 $this->mPasswordExpires
= null;
1013 $this->resetPasswordExpiration( false );
1014 $this->mRegistration
= wfTimestamp( TS_MW
);
1015 $this->mGroups
= array();
1017 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1019 wfProfileOut( __METHOD__
);
1023 * Return whether an item has been loaded.
1025 * @param string $item Item to check. Current possibilities:
1029 * @param string $all 'all' to check if the whole object has been loaded
1030 * or any other string to check if only the item is available (e.g.
1034 public function isItemLoaded( $item, $all = 'all' ) {
1035 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1036 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1040 * Set that an item has been loaded
1042 * @param string $item
1044 protected function setItemLoaded( $item ) {
1045 if ( is_array( $this->mLoadedItems
) ) {
1046 $this->mLoadedItems
[$item] = true;
1051 * Load user data from the session or login cookie.
1052 * @return bool True if the user is logged in, false otherwise.
1054 private function loadFromSession() {
1056 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1057 if ( $result !== null ) {
1061 $request = $this->getRequest();
1063 $cookieId = $request->getCookie( 'UserID' );
1064 $sessId = $request->getSessionData( 'wsUserID' );
1066 if ( $cookieId !== null ) {
1067 $sId = intval( $cookieId );
1068 if ( $sessId !== null && $cookieId != $sessId ) {
1069 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1070 cookie user ID ($sId) don't match!" );
1073 $request->setSessionData( 'wsUserID', $sId );
1074 } elseif ( $sessId !== null && $sessId != 0 ) {
1080 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1081 $sName = $request->getSessionData( 'wsUserName' );
1082 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1083 $sName = $request->getCookie( 'UserName' );
1084 $request->setSessionData( 'wsUserName', $sName );
1089 $proposedUser = User
::newFromId( $sId );
1090 if ( !$proposedUser->isLoggedIn() ) {
1095 global $wgBlockDisablesLogin;
1096 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1097 // User blocked and we've disabled blocked user logins
1101 if ( $request->getSessionData( 'wsToken' ) ) {
1103 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1105 } elseif ( $request->getCookie( 'Token' ) ) {
1106 # Get the token from DB/cache and clean it up to remove garbage padding.
1107 # This deals with historical problems with bugs and the default column value.
1108 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1109 // Make comparison in constant time (bug 61346)
1110 $passwordCorrect = strlen( $token )
1111 && hash_equals( $token, $request->getCookie( 'Token' ) );
1114 // No session or persistent login cookie
1118 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1119 $this->loadFromUserObject( $proposedUser );
1120 $request->setSessionData( 'wsToken', $this->mToken
);
1121 wfDebug( "User: logged in from $from\n" );
1124 // Invalid credentials
1125 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1131 * Load user and user_group data from the database.
1132 * $this->mId must be set, this is how the user is identified.
1134 * @param int $flags Supports User::READ_LOCKING
1135 * @return bool True if the user exists, false if the user is anonymous
1137 public function loadFromDatabase( $flags = 0 ) {
1139 $this->mId
= intval( $this->mId
);
1142 if ( !$this->mId
) {
1143 $this->loadDefaults();
1147 $dbr = wfGetDB( DB_MASTER
);
1148 $s = $dbr->selectRow(
1150 self
::selectFields(),
1151 array( 'user_id' => $this->mId
),
1153 ( $flags & self
::READ_LOCKING
== self
::READ_LOCKING
)
1154 ?
array( 'LOCK IN SHARE MODE' )
1158 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1160 if ( $s !== false ) {
1161 // Initialise user table data
1162 $this->loadFromRow( $s );
1163 $this->mGroups
= null; // deferred
1164 $this->getEditCount(); // revalidation for nulls
1169 $this->loadDefaults();
1175 * Initialize this object from a row from the user table.
1177 * @param stdClass $row Row from the user table to load.
1178 * @param array $data Further user data to load into the object
1180 * user_groups Array with groups out of the user_groups table
1181 * user_properties Array with properties out of the user_properties table
1183 public function loadFromRow( $row, $data = null ) {
1185 $passwordFactory = self
::getPasswordFactory();
1187 $this->mGroups
= null; // deferred
1189 if ( isset( $row->user_name
) ) {
1190 $this->mName
= $row->user_name
;
1191 $this->mFrom
= 'name';
1192 $this->setItemLoaded( 'name' );
1197 if ( isset( $row->user_real_name
) ) {
1198 $this->mRealName
= $row->user_real_name
;
1199 $this->setItemLoaded( 'realname' );
1204 if ( isset( $row->user_id
) ) {
1205 $this->mId
= intval( $row->user_id
);
1206 $this->mFrom
= 'id';
1207 $this->setItemLoaded( 'id' );
1212 if ( isset( $row->user_editcount
) ) {
1213 $this->mEditCount
= $row->user_editcount
;
1218 if ( isset( $row->user_password
) ) {
1219 // Check for *really* old password hashes that don't even have a type
1220 // The old hash format was just an md5 hex hash, with no type information
1221 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password
) ) {
1222 $row->user_password
= ":A:{$this->mId}:{$row->user_password}";
1226 $this->mPassword
= $passwordFactory->newFromCiphertext( $row->user_password
);
1227 } catch ( PasswordError
$e ) {
1228 wfDebug( 'Invalid password hash found in database.' );
1229 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
1233 $this->mNewpassword
= $passwordFactory->newFromCiphertext( $row->user_newpassword
);
1234 } catch ( PasswordError
$e ) {
1235 wfDebug( 'Invalid password hash found in database.' );
1236 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
1239 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
1240 $this->mPasswordExpires
= wfTimestampOrNull( TS_MW
, $row->user_password_expires
);
1243 if ( isset( $row->user_email
) ) {
1244 $this->mEmail
= $row->user_email
;
1245 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1246 $this->mToken
= $row->user_token
;
1247 if ( $this->mToken
== '' ) {
1248 $this->mToken
= null;
1250 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1251 $this->mEmailToken
= $row->user_email_token
;
1252 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1253 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1259 $this->mLoadedItems
= true;
1262 if ( is_array( $data ) ) {
1263 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1264 $this->mGroups
= $data['user_groups'];
1266 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1267 $this->loadOptions( $data['user_properties'] );
1273 * Load the data for this user object from another user object.
1277 protected function loadFromUserObject( $user ) {
1279 $user->loadGroups();
1280 $user->loadOptions();
1281 foreach ( self
::$mCacheVars as $var ) {
1282 $this->$var = $user->$var;
1287 * Load the groups from the database if they aren't already loaded.
1289 private function loadGroups() {
1290 if ( is_null( $this->mGroups
) ) {
1291 $dbr = wfGetDB( DB_MASTER
);
1292 $res = $dbr->select( 'user_groups',
1293 array( 'ug_group' ),
1294 array( 'ug_user' => $this->mId
),
1296 $this->mGroups
= array();
1297 foreach ( $res as $row ) {
1298 $this->mGroups
[] = $row->ug_group
;
1304 * Load the user's password hashes from the database
1306 * This is usually called in a scenario where the actual User object was
1307 * loaded from the cache, and then password comparison needs to be performed.
1308 * Password hashes are not stored in memcached.
1312 private function loadPasswords() {
1313 if ( $this->getId() !== 0 && ( $this->mPassword
=== null ||
$this->mNewpassword
=== null ) ) {
1314 $this->loadFromRow( wfGetDB( DB_MASTER
)->selectRow(
1316 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1317 array( 'user_id' => $this->getId() ),
1324 * Add the user to the group if he/she meets given criteria.
1326 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1327 * possible to remove manually via Special:UserRights. In such case it
1328 * will not be re-added automatically. The user will also not lose the
1329 * group if they no longer meet the criteria.
1331 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1333 * @return array Array of groups the user has been promoted to.
1335 * @see $wgAutopromoteOnce
1337 public function addAutopromoteOnceGroups( $event ) {
1338 global $wgAutopromoteOnceLogInRC, $wgAuth;
1340 $toPromote = array();
1341 if ( $this->getId() ) {
1342 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1343 if ( count( $toPromote ) ) {
1344 $oldGroups = $this->getGroups(); // previous groups
1346 foreach ( $toPromote as $group ) {
1347 $this->addGroup( $group );
1349 // update groups in external authentication database
1350 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1352 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1354 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1355 $logEntry->setPerformer( $this );
1356 $logEntry->setTarget( $this->getUserPage() );
1357 $logEntry->setParameters( array(
1358 '4::oldgroups' => $oldGroups,
1359 '5::newgroups' => $newGroups,
1361 $logid = $logEntry->insert();
1362 if ( $wgAutopromoteOnceLogInRC ) {
1363 $logEntry->publish( $logid );
1371 * Clear various cached data stored in this object. The cache of the user table
1372 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1374 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1375 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1377 public function clearInstanceCache( $reloadFrom = false ) {
1378 $this->mNewtalk
= -1;
1379 $this->mDatePreference
= null;
1380 $this->mBlockedby
= -1; # Unset
1381 $this->mHash
= false;
1382 $this->mRights
= null;
1383 $this->mEffectiveGroups
= null;
1384 $this->mImplicitGroups
= null;
1385 $this->mGroups
= null;
1386 $this->mOptions
= null;
1387 $this->mOptionsLoaded
= false;
1388 $this->mEditCount
= null;
1390 if ( $reloadFrom ) {
1391 $this->mLoadedItems
= array();
1392 $this->mFrom
= $reloadFrom;
1397 * Combine the language default options with any site-specific options
1398 * and add the default language variants.
1400 * @return array Array of String options
1402 public static function getDefaultOptions() {
1403 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1405 static $defOpt = null;
1406 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1407 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1408 // mid-request and see that change reflected in the return value of this function.
1409 // Which is insane and would never happen during normal MW operation
1413 $defOpt = $wgDefaultUserOptions;
1414 // Default language setting
1415 $defOpt['language'] = $wgContLang->getCode();
1416 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1417 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1419 foreach ( SearchEngine
::searchableNamespaces() as $nsnum => $nsname ) {
1420 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1422 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1424 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1430 * Get a given default option value.
1432 * @param string $opt Name of option to retrieve
1433 * @return string Default option value
1435 public static function getDefaultOption( $opt ) {
1436 $defOpts = self
::getDefaultOptions();
1437 if ( isset( $defOpts[$opt] ) ) {
1438 return $defOpts[$opt];
1445 * Get blocking information
1446 * @param bool $bFromSlave Whether to check the slave database first.
1447 * To improve performance, non-critical checks are done against slaves.
1448 * Check when actually saving should be done against master.
1450 private function getBlockedStatus( $bFromSlave = true ) {
1451 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1453 if ( -1 != $this->mBlockedby
) {
1457 wfProfileIn( __METHOD__
);
1458 wfDebug( __METHOD__
. ": checking...\n" );
1460 // Initialize data...
1461 // Otherwise something ends up stomping on $this->mBlockedby when
1462 // things get lazy-loaded later, causing false positive block hits
1463 // due to -1 !== 0. Probably session-related... Nothing should be
1464 // overwriting mBlockedby, surely?
1467 # We only need to worry about passing the IP address to the Block generator if the
1468 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1469 # know which IP address they're actually coming from
1470 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1471 $ip = $this->getRequest()->getIP();
1477 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1480 if ( !$block instanceof Block
&& $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1481 && !in_array( $ip, $wgProxyWhitelist )
1484 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1486 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1487 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1488 $block->setTarget( $ip );
1489 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1491 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1492 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1493 $block->setTarget( $ip );
1497 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1498 if ( !$block instanceof Block
1499 && $wgApplyIpBlocksToXff
1501 && !$this->isAllowed( 'proxyunbannable' )
1502 && !in_array( $ip, $wgProxyWhitelist )
1504 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1505 $xff = array_map( 'trim', explode( ',', $xff ) );
1506 $xff = array_diff( $xff, array( $ip ) );
1507 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1508 $block = Block
::chooseBlock( $xffblocks, $xff );
1509 if ( $block instanceof Block
) {
1510 # Mangle the reason to alert the user that the block
1511 # originated from matching the X-Forwarded-For header.
1512 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1516 if ( $block instanceof Block
) {
1517 wfDebug( __METHOD__
. ": Found block.\n" );
1518 $this->mBlock
= $block;
1519 $this->mBlockedby
= $block->getByName();
1520 $this->mBlockreason
= $block->mReason
;
1521 $this->mHideName
= $block->mHideName
;
1522 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1524 $this->mBlockedby
= '';
1525 $this->mHideName
= 0;
1526 $this->mAllowUsertalk
= false;
1530 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1532 wfProfileOut( __METHOD__
);
1536 * Whether the given IP is in a DNS blacklist.
1538 * @param string $ip IP to check
1539 * @param bool $checkWhitelist Whether to check the whitelist first
1540 * @return bool True if blacklisted.
1542 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1543 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1545 if ( !$wgEnableDnsBlacklist ) {
1549 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1553 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1557 * Whether the given IP is in a given DNS blacklist.
1559 * @param string $ip IP to check
1560 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1561 * @return bool True if blacklisted.
1563 public function inDnsBlacklist( $ip, $bases ) {
1564 wfProfileIn( __METHOD__
);
1567 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1568 if ( IP
::isIPv4( $ip ) ) {
1569 // Reverse IP, bug 21255
1570 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1572 foreach ( (array)$bases as $base ) {
1574 // If we have an access key, use that too (ProjectHoneypot, etc.)
1575 if ( is_array( $base ) ) {
1576 if ( count( $base ) >= 2 ) {
1577 // Access key is 1, base URL is 0
1578 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1580 $host = "$ipReversed.{$base[0]}";
1583 $host = "$ipReversed.$base";
1587 $ipList = gethostbynamel( $host );
1590 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1594 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1599 wfProfileOut( __METHOD__
);
1604 * Check if an IP address is in the local proxy list
1610 public static function isLocallyBlockedProxy( $ip ) {
1611 global $wgProxyList;
1613 if ( !$wgProxyList ) {
1616 wfProfileIn( __METHOD__
);
1618 if ( !is_array( $wgProxyList ) ) {
1619 // Load from the specified file
1620 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1623 if ( !is_array( $wgProxyList ) ) {
1625 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1627 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1628 // Old-style flipped proxy list
1633 wfProfileOut( __METHOD__
);
1638 * Is this user subject to rate limiting?
1640 * @return bool True if rate limited
1642 public function isPingLimitable() {
1643 global $wgRateLimitsExcludedIPs;
1644 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1645 // No other good way currently to disable rate limits
1646 // for specific IPs. :P
1647 // But this is a crappy hack and should die.
1650 return !$this->isAllowed( 'noratelimit' );
1654 * Primitive rate limits: enforce maximum actions per time period
1655 * to put a brake on flooding.
1657 * The method generates both a generic profiling point and a per action one
1658 * (suffix being "-$action".
1660 * @note When using a shared cache like memcached, IP-address
1661 * last-hit counters will be shared across wikis.
1663 * @param string $action Action to enforce; 'edit' if unspecified
1664 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1665 * @return bool True if a rate limiter was tripped
1667 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1668 // Call the 'PingLimiter' hook
1670 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1674 global $wgRateLimits;
1675 if ( !isset( $wgRateLimits[$action] ) ) {
1679 // Some groups shouldn't trigger the ping limiter, ever
1680 if ( !$this->isPingLimitable() ) {
1685 wfProfileIn( __METHOD__
);
1686 wfProfileIn( __METHOD__
. '-' . $action );
1688 $limits = $wgRateLimits[$action];
1690 $id = $this->getId();
1693 if ( isset( $limits['anon'] ) && $id == 0 ) {
1694 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1697 if ( isset( $limits['user'] ) && $id != 0 ) {
1698 $userLimit = $limits['user'];
1700 if ( $this->isNewbie() ) {
1701 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1702 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1704 if ( isset( $limits['ip'] ) ) {
1705 $ip = $this->getRequest()->getIP();
1706 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1708 if ( isset( $limits['subnet'] ) ) {
1709 $ip = $this->getRequest()->getIP();
1712 if ( IP
::isIPv6( $ip ) ) {
1713 $parts = IP
::parseRange( "$ip/64" );
1714 $subnet = $parts[0];
1715 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1717 $subnet = $matches[1];
1719 if ( $subnet !== false ) {
1720 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1724 // Check for group-specific permissions
1725 // If more than one group applies, use the group with the highest limit
1726 foreach ( $this->getGroups() as $group ) {
1727 if ( isset( $limits[$group] ) ) {
1728 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1729 $userLimit = $limits[$group];
1733 // Set the user limit key
1734 if ( $userLimit !== false ) {
1735 list( $max, $period ) = $userLimit;
1736 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1737 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1741 foreach ( $keys as $key => $limit ) {
1742 list( $max, $period ) = $limit;
1743 $summary = "(limit $max in {$period}s)";
1744 $count = $wgMemc->get( $key );
1747 if ( $count >= $max ) {
1748 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1749 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1752 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1755 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1756 if ( $incrBy > 0 ) {
1757 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1760 if ( $incrBy > 0 ) {
1761 $wgMemc->incr( $key, $incrBy );
1765 wfProfileOut( __METHOD__
. '-' . $action );
1766 wfProfileOut( __METHOD__
);
1771 * Check if user is blocked
1773 * @param bool $bFromSlave Whether to check the slave database instead of
1774 * the master. Hacked from false due to horrible probs on site.
1775 * @return bool True if blocked, false otherwise
1777 public function isBlocked( $bFromSlave = true ) {
1778 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1782 * Get the block affecting the user, or null if the user is not blocked
1784 * @param bool $bFromSlave Whether to check the slave database instead of the master
1785 * @return Block|null
1787 public function getBlock( $bFromSlave = true ) {
1788 $this->getBlockedStatus( $bFromSlave );
1789 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1793 * Check if user is blocked from editing a particular article
1795 * @param Title $title Title to check
1796 * @param bool $bFromSlave Whether to check the slave database instead of the master
1799 public function isBlockedFrom( $title, $bFromSlave = false ) {
1800 global $wgBlockAllowsUTEdit;
1801 wfProfileIn( __METHOD__
);
1803 $blocked = $this->isBlocked( $bFromSlave );
1804 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1805 // If a user's name is suppressed, they cannot make edits anywhere
1806 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1807 && $title->getNamespace() == NS_USER_TALK
) {
1809 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1812 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1814 wfProfileOut( __METHOD__
);
1819 * If user is blocked, return the name of the user who placed the block
1820 * @return string Name of blocker
1822 public function blockedBy() {
1823 $this->getBlockedStatus();
1824 return $this->mBlockedby
;
1828 * If user is blocked, return the specified reason for the block
1829 * @return string Blocking reason
1831 public function blockedFor() {
1832 $this->getBlockedStatus();
1833 return $this->mBlockreason
;
1837 * If user is blocked, return the ID for the block
1838 * @return int Block ID
1840 public function getBlockId() {
1841 $this->getBlockedStatus();
1842 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
1846 * Check if user is blocked on all wikis.
1847 * Do not use for actual edit permission checks!
1848 * This is intended for quick UI checks.
1850 * @param string $ip IP address, uses current client if none given
1851 * @return bool True if blocked, false otherwise
1853 public function isBlockedGlobally( $ip = '' ) {
1854 if ( $this->mBlockedGlobally
!== null ) {
1855 return $this->mBlockedGlobally
;
1857 // User is already an IP?
1858 if ( IP
::isIPAddress( $this->getName() ) ) {
1859 $ip = $this->getName();
1861 $ip = $this->getRequest()->getIP();
1864 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1865 $this->mBlockedGlobally
= (bool)$blocked;
1866 return $this->mBlockedGlobally
;
1870 * Check if user account is locked
1872 * @return bool True if locked, false otherwise
1874 public function isLocked() {
1875 if ( $this->mLocked
!== null ) {
1876 return $this->mLocked
;
1879 StubObject
::unstub( $wgAuth );
1880 $authUser = $wgAuth->getUserInstance( $this );
1881 $this->mLocked
= (bool)$authUser->isLocked();
1882 return $this->mLocked
;
1886 * Check if user account is hidden
1888 * @return bool True if hidden, false otherwise
1890 public function isHidden() {
1891 if ( $this->mHideName
!== null ) {
1892 return $this->mHideName
;
1894 $this->getBlockedStatus();
1895 if ( !$this->mHideName
) {
1897 StubObject
::unstub( $wgAuth );
1898 $authUser = $wgAuth->getUserInstance( $this );
1899 $this->mHideName
= (bool)$authUser->isHidden();
1901 return $this->mHideName
;
1905 * Get the user's ID.
1906 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1908 public function getId() {
1909 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
1910 // Special case, we know the user is anonymous
1912 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1913 // Don't load if this was initialized from an ID
1920 * Set the user and reload all fields according to a given ID
1921 * @param int $v User ID to reload
1923 public function setId( $v ) {
1925 $this->clearInstanceCache( 'id' );
1929 * Get the user name, or the IP of an anonymous user
1930 * @return string User's name or IP address
1932 public function getName() {
1933 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1934 // Special case optimisation
1935 return $this->mName
;
1938 if ( $this->mName
=== false ) {
1940 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
1942 return $this->mName
;
1947 * Set the user name.
1949 * This does not reload fields from the database according to the given
1950 * name. Rather, it is used to create a temporary "nonexistent user" for
1951 * later addition to the database. It can also be used to set the IP
1952 * address for an anonymous user to something other than the current
1955 * @note User::newFromName() has roughly the same function, when the named user
1957 * @param string $str New user name to set
1959 public function setName( $str ) {
1961 $this->mName
= $str;
1965 * Get the user's name escaped by underscores.
1966 * @return string Username escaped by underscores.
1968 public function getTitleKey() {
1969 return str_replace( ' ', '_', $this->getName() );
1973 * Check if the user has new messages.
1974 * @return bool True if the user has new messages
1976 public function getNewtalk() {
1979 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1980 if ( $this->mNewtalk
=== -1 ) {
1981 $this->mNewtalk
= false; # reset talk page status
1983 // Check memcached separately for anons, who have no
1984 // entire User object stored in there.
1985 if ( !$this->mId
) {
1986 global $wgDisableAnonTalk;
1987 if ( $wgDisableAnonTalk ) {
1988 // Anon newtalk disabled by configuration.
1989 $this->mNewtalk
= false;
1992 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1993 $newtalk = $wgMemc->get( $key );
1994 if ( strval( $newtalk ) !== '' ) {
1995 $this->mNewtalk
= (bool)$newtalk;
1997 // Since we are caching this, make sure it is up to date by getting it
1999 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
2000 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
2004 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2008 return (bool)$this->mNewtalk
;
2012 * Return the data needed to construct links for new talk page message
2013 * alerts. If there are new messages, this will return an associative array
2014 * with the following data:
2015 * wiki: The database name of the wiki
2016 * link: Root-relative link to the user's talk page
2017 * rev: The last talk page revision that the user has seen or null. This
2018 * is useful for building diff links.
2019 * If there are no new messages, it returns an empty array.
2020 * @note This function was designed to accomodate multiple talk pages, but
2021 * currently only returns a single link and revision.
2024 public function getNewMessageLinks() {
2026 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2028 } elseif ( !$this->getNewtalk() ) {
2031 $utp = $this->getTalkPage();
2032 $dbr = wfGetDB( DB_SLAVE
);
2033 // Get the "last viewed rev" timestamp from the oldest message notification
2034 $timestamp = $dbr->selectField( 'user_newtalk',
2035 'MIN(user_last_timestamp)',
2036 $this->isAnon() ?
array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2038 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2039 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2043 * Get the revision ID for the last talk page revision viewed by the talk
2045 * @return int|null Revision ID or null
2047 public function getNewMessageRevisionId() {
2048 $newMessageRevisionId = null;
2049 $newMessageLinks = $this->getNewMessageLinks();
2050 if ( $newMessageLinks ) {
2051 // Note: getNewMessageLinks() never returns more than a single link
2052 // and it is always for the same wiki, but we double-check here in
2053 // case that changes some time in the future.
2054 if ( count( $newMessageLinks ) === 1
2055 && $newMessageLinks[0]['wiki'] === wfWikiID()
2056 && $newMessageLinks[0]['rev']
2058 $newMessageRevision = $newMessageLinks[0]['rev'];
2059 $newMessageRevisionId = $newMessageRevision->getId();
2062 return $newMessageRevisionId;
2066 * Internal uncached check for new messages
2069 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2070 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2071 * @param bool $fromMaster True to fetch from the master, false for a slave
2072 * @return bool True if the user has new messages
2074 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2075 if ( $fromMaster ) {
2076 $db = wfGetDB( DB_MASTER
);
2078 $db = wfGetDB( DB_SLAVE
);
2080 $ok = $db->selectField( 'user_newtalk', $field,
2081 array( $field => $id ), __METHOD__
);
2082 return $ok !== false;
2086 * Add or update the new messages flag
2087 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2088 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2089 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2090 * @return bool True if successful, false otherwise
2092 protected function updateNewtalk( $field, $id, $curRev = null ) {
2093 // Get timestamp of the talk page revision prior to the current one
2094 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2095 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2096 // Mark the user as having new messages since this revision
2097 $dbw = wfGetDB( DB_MASTER
);
2098 $dbw->insert( 'user_newtalk',
2099 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2102 if ( $dbw->affectedRows() ) {
2103 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2106 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2112 * Clear the new messages flag for the given user
2113 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2114 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2115 * @return bool True if successful, false otherwise
2117 protected function deleteNewtalk( $field, $id ) {
2118 $dbw = wfGetDB( DB_MASTER
);
2119 $dbw->delete( 'user_newtalk',
2120 array( $field => $id ),
2122 if ( $dbw->affectedRows() ) {
2123 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2126 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2132 * Update the 'You have new messages!' status.
2133 * @param bool $val Whether the user has new messages
2134 * @param Revision $curRev New, as yet unseen revision of the user talk
2135 * page. Ignored if null or !$val.
2137 public function setNewtalk( $val, $curRev = null ) {
2138 if ( wfReadOnly() ) {
2143 $this->mNewtalk
= $val;
2145 if ( $this->isAnon() ) {
2147 $id = $this->getName();
2150 $id = $this->getId();
2155 $changed = $this->updateNewtalk( $field, $id, $curRev );
2157 $changed = $this->deleteNewtalk( $field, $id );
2160 if ( $this->isAnon() ) {
2161 // Anons have a separate memcached space, since
2162 // user records aren't kept for them.
2163 $key = wfMemcKey( 'newtalk', 'ip', $id );
2164 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
2167 $this->invalidateCache();
2172 * Generate a current or new-future timestamp to be stored in the
2173 * user_touched field when we update things.
2174 * @return string Timestamp in TS_MW format
2176 private static function newTouchedTimestamp() {
2177 global $wgClockSkewFudge;
2178 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2182 * Clear user data from memcached.
2183 * Use after applying fun updates to the database; caller's
2184 * responsibility to update user_touched if appropriate.
2186 * Called implicitly from invalidateCache() and saveSettings().
2188 public function clearSharedCache() {
2192 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
2197 * Immediately touch the user data cache for this account.
2198 * Updates user_touched field, and removes account data from memcached
2199 * for reload on the next hit.
2201 public function invalidateCache() {
2202 if ( wfReadOnly() ) {
2207 $this->mTouched
= self
::newTouchedTimestamp();
2209 $dbw = wfGetDB( DB_MASTER
);
2210 $userid = $this->mId
;
2211 $touched = $this->mTouched
;
2212 $method = __METHOD__
;
2213 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2214 // Prevent contention slams by checking user_touched first
2215 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2216 $needsPurge = $dbw->selectField( 'user', '1',
2217 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2218 if ( $needsPurge ) {
2219 $dbw->update( 'user',
2220 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2221 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2226 $this->clearSharedCache();
2231 * Validate the cache for this account.
2232 * @param string $timestamp A timestamp in TS_MW format
2235 public function validateCache( $timestamp ) {
2237 return ( $timestamp >= $this->mTouched
);
2241 * Get the user touched timestamp
2242 * @return string Timestamp
2244 public function getTouched() {
2246 return $this->mTouched
;
2250 * Set the password and reset the random token.
2251 * Calls through to authentication plugin if necessary;
2252 * will have no effect if the auth plugin refuses to
2253 * pass the change through or if the legal password
2256 * As a special case, setting the password to null
2257 * wipes it, so the account cannot be logged in until
2258 * a new password is set, for instance via e-mail.
2260 * @param string $str New password to set
2261 * @throws PasswordError On failure
2265 public function setPassword( $str ) {
2268 if ( $str !== null ) {
2269 if ( !$wgAuth->allowPasswordChange() ) {
2270 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2273 if ( !$this->isValidPassword( $str ) ) {
2274 global $wgMinimalPasswordLength;
2275 $valid = $this->getPasswordValidity( $str );
2276 if ( is_array( $valid ) ) {
2277 $message = array_shift( $valid );
2281 $params = array( $wgMinimalPasswordLength );
2283 throw new PasswordError( wfMessage( $message, $params )->text() );
2287 if ( !$wgAuth->setPassword( $this, $str ) ) {
2288 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2291 $this->setInternalPassword( $str );
2297 * Set the password and reset the random token unconditionally.
2299 * @param string|null $str New password to set or null to set an invalid
2300 * password hash meaning that the user will not be able to log in
2301 * through the web interface.
2303 public function setInternalPassword( $str ) {
2306 $passwordFactory = self
::getPasswordFactory();
2307 if ( $str === null ) {
2308 $this->mPassword
= $passwordFactory->newFromCiphertext( null );
2310 $this->mPassword
= $passwordFactory->newFromPlaintext( $str );
2313 $this->mNewpassword
= $passwordFactory->newFromCiphertext( null );
2314 $this->mNewpassTime
= null;
2318 * Get the user's current token.
2319 * @param bool $forceCreation Force the generation of a new token if the
2320 * user doesn't have one (default=true for backwards compatibility).
2321 * @return string Token
2323 public function getToken( $forceCreation = true ) {
2325 if ( !$this->mToken
&& $forceCreation ) {
2328 return $this->mToken
;
2332 * Set the random token (used for persistent authentication)
2333 * Called from loadDefaults() among other places.
2335 * @param string|bool $token If specified, set the token to this value
2337 public function setToken( $token = false ) {
2340 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2342 $this->mToken
= $token;
2347 * Set the password for a password reminder or new account email
2349 * @param string $str New password to set or null to set an invalid
2350 * password hash meaning that the user will not be able to use it
2351 * @param bool $throttle If true, reset the throttle timestamp to the present
2353 public function setNewpassword( $str, $throttle = true ) {
2356 if ( $str === null ) {
2357 $this->mNewpassword
= '';
2358 $this->mNewpassTime
= null;
2360 $this->mNewpassword
= self
::getPasswordFactory()->newFromPlaintext( $str );
2362 $this->mNewpassTime
= wfTimestampNow();
2368 * Has password reminder email been sent within the last
2369 * $wgPasswordReminderResendTime hours?
2372 public function isPasswordReminderThrottled() {
2373 global $wgPasswordReminderResendTime;
2375 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
2378 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
2379 return time() < $expiry;
2383 * Get the user's e-mail address
2384 * @return string User's email address
2386 public function getEmail() {
2388 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
2389 return $this->mEmail
;
2393 * Get the timestamp of the user's e-mail authentication
2394 * @return string TS_MW timestamp
2396 public function getEmailAuthenticationTimestamp() {
2398 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2399 return $this->mEmailAuthenticated
;
2403 * Set the user's e-mail address
2404 * @param string $str New e-mail address
2406 public function setEmail( $str ) {
2408 if ( $str == $this->mEmail
) {
2411 $this->invalidateEmail();
2412 $this->mEmail
= $str;
2413 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
2417 * Set the user's e-mail address and a confirmation mail if needed.
2420 * @param string $str New e-mail address
2423 public function setEmailWithConfirmation( $str ) {
2424 global $wgEnableEmail, $wgEmailAuthentication;
2426 if ( !$wgEnableEmail ) {
2427 return Status
::newFatal( 'emaildisabled' );
2430 $oldaddr = $this->getEmail();
2431 if ( $str === $oldaddr ) {
2432 return Status
::newGood( true );
2435 $this->setEmail( $str );
2437 if ( $str !== '' && $wgEmailAuthentication ) {
2438 // Send a confirmation request to the new address if needed
2439 $type = $oldaddr != '' ?
'changed' : 'set';
2440 $result = $this->sendConfirmationMail( $type );
2441 if ( $result->isGood() ) {
2442 // Say the the caller that a confirmation mail has been sent
2443 $result->value
= 'eauth';
2446 $result = Status
::newGood( true );
2453 * Get the user's real name
2454 * @return string User's real name
2456 public function getRealName() {
2457 if ( !$this->isItemLoaded( 'realname' ) ) {
2461 return $this->mRealName
;
2465 * Set the user's real name
2466 * @param string $str New real name
2468 public function setRealName( $str ) {
2470 $this->mRealName
= $str;
2474 * Get the user's current setting for a given option.
2476 * @param string $oname The option to check
2477 * @param string $defaultOverride A default value returned if the option does not exist
2478 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2479 * @return string User's current value for the option
2480 * @see getBoolOption()
2481 * @see getIntOption()
2483 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2484 global $wgHiddenPrefs;
2485 $this->loadOptions();
2487 # We want 'disabled' preferences to always behave as the default value for
2488 # users, even if they have set the option explicitly in their settings (ie they
2489 # set it, and then it was disabled removing their ability to change it). But
2490 # we don't want to erase the preferences in the database in case the preference
2491 # is re-enabled again. So don't touch $mOptions, just override the returned value
2492 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2493 return self
::getDefaultOption( $oname );
2496 if ( array_key_exists( $oname, $this->mOptions
) ) {
2497 return $this->mOptions
[$oname];
2499 return $defaultOverride;
2504 * Get all user's options
2508 public function getOptions() {
2509 global $wgHiddenPrefs;
2510 $this->loadOptions();
2511 $options = $this->mOptions
;
2513 # We want 'disabled' preferences to always behave as the default value for
2514 # users, even if they have set the option explicitly in their settings (ie they
2515 # set it, and then it was disabled removing their ability to change it). But
2516 # we don't want to erase the preferences in the database in case the preference
2517 # is re-enabled again. So don't touch $mOptions, just override the returned value
2518 foreach ( $wgHiddenPrefs as $pref ) {
2519 $default = self
::getDefaultOption( $pref );
2520 if ( $default !== null ) {
2521 $options[$pref] = $default;
2529 * Get the user's current setting for a given option, as a boolean value.
2531 * @param string $oname The option to check
2532 * @return bool User's current value for the option
2535 public function getBoolOption( $oname ) {
2536 return (bool)$this->getOption( $oname );
2540 * Get the user's current setting for a given option, as an integer value.
2542 * @param string $oname The option to check
2543 * @param int $defaultOverride A default value returned if the option does not exist
2544 * @return int User's current value for the option
2547 public function getIntOption( $oname, $defaultOverride = 0 ) {
2548 $val = $this->getOption( $oname );
2550 $val = $defaultOverride;
2552 return intval( $val );
2556 * Set the given option for a user.
2558 * You need to call saveSettings() to actually write to the database.
2560 * @param string $oname The option to set
2561 * @param mixed $val New value to set
2563 public function setOption( $oname, $val ) {
2564 $this->loadOptions();
2566 // Explicitly NULL values should refer to defaults
2567 if ( is_null( $val ) ) {
2568 $val = self
::getDefaultOption( $oname );
2571 $this->mOptions
[$oname] = $val;
2575 * Get a token stored in the preferences (like the watchlist one),
2576 * resetting it if it's empty (and saving changes).
2578 * @param string $oname The option name to retrieve the token from
2579 * @return string|bool User's current value for the option, or false if this option is disabled.
2580 * @see resetTokenFromOption()
2583 public function getTokenFromOption( $oname ) {
2584 global $wgHiddenPrefs;
2585 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2589 $token = $this->getOption( $oname );
2591 $token = $this->resetTokenFromOption( $oname );
2592 $this->saveSettings();
2598 * Reset a token stored in the preferences (like the watchlist one).
2599 * *Does not* save user's preferences (similarly to setOption()).
2601 * @param string $oname The option name to reset the token in
2602 * @return string|bool New token value, or false if this option is disabled.
2603 * @see getTokenFromOption()
2606 public function resetTokenFromOption( $oname ) {
2607 global $wgHiddenPrefs;
2608 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2612 $token = MWCryptRand
::generateHex( 40 );
2613 $this->setOption( $oname, $token );
2618 * Return a list of the types of user options currently returned by
2619 * User::getOptionKinds().
2621 * Currently, the option kinds are:
2622 * - 'registered' - preferences which are registered in core MediaWiki or
2623 * by extensions using the UserGetDefaultOptions hook.
2624 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2625 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2626 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2627 * be used by user scripts.
2628 * - 'special' - "preferences" that are not accessible via User::getOptions
2629 * or User::setOptions.
2630 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2631 * These are usually legacy options, removed in newer versions.
2633 * The API (and possibly others) use this function to determine the possible
2634 * option types for validation purposes, so make sure to update this when a
2635 * new option kind is added.
2637 * @see User::getOptionKinds
2638 * @return array Option kinds
2640 public static function listOptionKinds() {
2643 'registered-multiselect',
2644 'registered-checkmatrix',
2652 * Return an associative array mapping preferences keys to the kind of a preference they're
2653 * used for. Different kinds are handled differently when setting or reading preferences.
2655 * See User::listOptionKinds for the list of valid option types that can be provided.
2657 * @see User::listOptionKinds
2658 * @param IContextSource $context
2659 * @param array $options Assoc. array with options keys to check as keys.
2660 * Defaults to $this->mOptions.
2661 * @return array The key => kind mapping data
2663 public function getOptionKinds( IContextSource
$context, $options = null ) {
2664 $this->loadOptions();
2665 if ( $options === null ) {
2666 $options = $this->mOptions
;
2669 $prefs = Preferences
::getPreferences( $this, $context );
2672 // Pull out the "special" options, so they don't get converted as
2673 // multiselect or checkmatrix.
2674 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2675 foreach ( $specialOptions as $name => $value ) {
2676 unset( $prefs[$name] );
2679 // Multiselect and checkmatrix options are stored in the database with
2680 // one key per option, each having a boolean value. Extract those keys.
2681 $multiselectOptions = array();
2682 foreach ( $prefs as $name => $info ) {
2683 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2684 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2685 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2686 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2688 foreach ( $opts as $value ) {
2689 $multiselectOptions["$prefix$value"] = true;
2692 unset( $prefs[$name] );
2695 $checkmatrixOptions = array();
2696 foreach ( $prefs as $name => $info ) {
2697 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2698 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2699 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2700 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2701 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2703 foreach ( $columns as $column ) {
2704 foreach ( $rows as $row ) {
2705 $checkmatrixOptions["$prefix-$column-$row"] = true;
2709 unset( $prefs[$name] );
2713 // $value is ignored
2714 foreach ( $options as $key => $value ) {
2715 if ( isset( $prefs[$key] ) ) {
2716 $mapping[$key] = 'registered';
2717 } elseif ( isset( $multiselectOptions[$key] ) ) {
2718 $mapping[$key] = 'registered-multiselect';
2719 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2720 $mapping[$key] = 'registered-checkmatrix';
2721 } elseif ( isset( $specialOptions[$key] ) ) {
2722 $mapping[$key] = 'special';
2723 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2724 $mapping[$key] = 'userjs';
2726 $mapping[$key] = 'unused';
2734 * Reset certain (or all) options to the site defaults
2736 * The optional parameter determines which kinds of preferences will be reset.
2737 * Supported values are everything that can be reported by getOptionKinds()
2738 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2740 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2741 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2742 * for backwards-compatibility.
2743 * @param IContextSource|null $context Context source used when $resetKinds
2744 * does not contain 'all', passed to getOptionKinds().
2745 * Defaults to RequestContext::getMain() when null.
2747 public function resetOptions(
2748 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2749 IContextSource
$context = null
2752 $defaultOptions = self
::getDefaultOptions();
2754 if ( !is_array( $resetKinds ) ) {
2755 $resetKinds = array( $resetKinds );
2758 if ( in_array( 'all', $resetKinds ) ) {
2759 $newOptions = $defaultOptions;
2761 if ( $context === null ) {
2762 $context = RequestContext
::getMain();
2765 $optionKinds = $this->getOptionKinds( $context );
2766 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
2767 $newOptions = array();
2769 // Use default values for the options that should be deleted, and
2770 // copy old values for the ones that shouldn't.
2771 foreach ( $this->mOptions
as $key => $value ) {
2772 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2773 if ( array_key_exists( $key, $defaultOptions ) ) {
2774 $newOptions[$key] = $defaultOptions[$key];
2777 $newOptions[$key] = $value;
2782 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions
, $resetKinds ) );
2784 $this->mOptions
= $newOptions;
2785 $this->mOptionsLoaded
= true;
2789 * Get the user's preferred date format.
2790 * @return string User's preferred date format
2792 public function getDatePreference() {
2793 // Important migration for old data rows
2794 if ( is_null( $this->mDatePreference
) ) {
2796 $value = $this->getOption( 'date' );
2797 $map = $wgLang->getDatePreferenceMigrationMap();
2798 if ( isset( $map[$value] ) ) {
2799 $value = $map[$value];
2801 $this->mDatePreference
= $value;
2803 return $this->mDatePreference
;
2807 * Determine based on the wiki configuration and the user's options,
2808 * whether this user must be over HTTPS no matter what.
2812 public function requiresHTTPS() {
2813 global $wgSecureLogin;
2814 if ( !$wgSecureLogin ) {
2817 $https = $this->getBoolOption( 'prefershttps' );
2818 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2820 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2827 * Get the user preferred stub threshold
2831 public function getStubThreshold() {
2832 global $wgMaxArticleSize; # Maximum article size, in Kb
2833 $threshold = $this->getIntOption( 'stubthreshold' );
2834 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2835 // If they have set an impossible value, disable the preference
2836 // so we can use the parser cache again.
2843 * Get the permissions this user has.
2844 * @return array Array of String permission names
2846 public function getRights() {
2847 if ( is_null( $this->mRights
) ) {
2848 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
2849 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
2850 // Force reindexation of rights when a hook has unset one of them
2851 $this->mRights
= array_values( array_unique( $this->mRights
) );
2853 return $this->mRights
;
2857 * Get the list of explicit group memberships this user has.
2858 * The implicit * and user groups are not included.
2859 * @return array Array of String internal group names
2861 public function getGroups() {
2863 $this->loadGroups();
2864 return $this->mGroups
;
2868 * Get the list of implicit group memberships this user has.
2869 * This includes all explicit groups, plus 'user' if logged in,
2870 * '*' for all accounts, and autopromoted groups
2871 * @param bool $recache Whether to avoid the cache
2872 * @return array Array of String internal group names
2874 public function getEffectiveGroups( $recache = false ) {
2875 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
2876 wfProfileIn( __METHOD__
);
2877 $this->mEffectiveGroups
= array_unique( array_merge(
2878 $this->getGroups(), // explicit groups
2879 $this->getAutomaticGroups( $recache ) // implicit groups
2881 // Hook for additional groups
2882 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
2883 // Force reindexation of groups when a hook has unset one of them
2884 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
2885 wfProfileOut( __METHOD__
);
2887 return $this->mEffectiveGroups
;
2891 * Get the list of implicit group memberships this user has.
2892 * This includes 'user' if logged in, '*' for all accounts,
2893 * and autopromoted groups
2894 * @param bool $recache Whether to avoid the cache
2895 * @return array Array of String internal group names
2897 public function getAutomaticGroups( $recache = false ) {
2898 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
2899 wfProfileIn( __METHOD__
);
2900 $this->mImplicitGroups
= array( '*' );
2901 if ( $this->getId() ) {
2902 $this->mImplicitGroups
[] = 'user';
2904 $this->mImplicitGroups
= array_unique( array_merge(
2905 $this->mImplicitGroups
,
2906 Autopromote
::getAutopromoteGroups( $this )
2910 // Assure data consistency with rights/groups,
2911 // as getEffectiveGroups() depends on this function
2912 $this->mEffectiveGroups
= null;
2914 wfProfileOut( __METHOD__
);
2916 return $this->mImplicitGroups
;
2920 * Returns the groups the user has belonged to.
2922 * The user may still belong to the returned groups. Compare with getGroups().
2924 * The function will not return groups the user had belonged to before MW 1.17
2926 * @return array Names of the groups the user has belonged to.
2928 public function getFormerGroups() {
2929 if ( is_null( $this->mFormerGroups
) ) {
2930 $dbr = wfGetDB( DB_MASTER
);
2931 $res = $dbr->select( 'user_former_groups',
2932 array( 'ufg_group' ),
2933 array( 'ufg_user' => $this->mId
),
2935 $this->mFormerGroups
= array();
2936 foreach ( $res as $row ) {
2937 $this->mFormerGroups
[] = $row->ufg_group
;
2940 return $this->mFormerGroups
;
2944 * Get the user's edit count.
2945 * @return int|null Null for anonymous users
2947 public function getEditCount() {
2948 if ( !$this->getId() ) {
2952 if ( $this->mEditCount
=== null ) {
2953 /* Populate the count, if it has not been populated yet */
2954 wfProfileIn( __METHOD__
);
2955 $dbr = wfGetDB( DB_SLAVE
);
2956 // check if the user_editcount field has been initialized
2957 $count = $dbr->selectField(
2958 'user', 'user_editcount',
2959 array( 'user_id' => $this->mId
),
2963 if ( $count === null ) {
2964 // it has not been initialized. do so.
2965 $count = $this->initEditCount();
2967 $this->mEditCount
= $count;
2968 wfProfileOut( __METHOD__
);
2970 return (int)$this->mEditCount
;
2974 * Add the user to the given group.
2975 * This takes immediate effect.
2976 * @param string $group Name of the group to add
2978 public function addGroup( $group ) {
2979 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2980 $dbw = wfGetDB( DB_MASTER
);
2981 if ( $this->getId() ) {
2982 $dbw->insert( 'user_groups',
2984 'ug_user' => $this->getID(),
2985 'ug_group' => $group,
2988 array( 'IGNORE' ) );
2991 $this->loadGroups();
2992 $this->mGroups
[] = $group;
2993 // In case loadGroups was not called before, we now have the right twice.
2994 // Get rid of the duplicate.
2995 $this->mGroups
= array_unique( $this->mGroups
);
2997 // Refresh the groups caches, and clear the rights cache so it will be
2998 // refreshed on the next call to $this->getRights().
2999 $this->getEffectiveGroups( true );
3000 $this->mRights
= null;
3002 $this->invalidateCache();
3006 * Remove the user from the given group.
3007 * This takes immediate effect.
3008 * @param string $group Name of the group to remove
3010 public function removeGroup( $group ) {
3012 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3013 $dbw = wfGetDB( DB_MASTER
);
3014 $dbw->delete( 'user_groups',
3016 'ug_user' => $this->getID(),
3017 'ug_group' => $group,
3019 // Remember that the user was in this group
3020 $dbw->insert( 'user_former_groups',
3022 'ufg_user' => $this->getID(),
3023 'ufg_group' => $group,
3026 array( 'IGNORE' ) );
3028 $this->loadGroups();
3029 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
3031 // Refresh the groups caches, and clear the rights cache so it will be
3032 // refreshed on the next call to $this->getRights().
3033 $this->getEffectiveGroups( true );
3034 $this->mRights
= null;
3036 $this->invalidateCache();
3040 * Get whether the user is logged in
3043 public function isLoggedIn() {
3044 return $this->getID() != 0;
3048 * Get whether the user is anonymous
3051 public function isAnon() {
3052 return !$this->isLoggedIn();
3056 * Check if user is allowed to access a feature / make an action
3058 * @internal param \String $varargs permissions to test
3059 * @return bool True if user is allowed to perform *any* of the given actions
3063 public function isAllowedAny( /*...*/ ) {
3064 $permissions = func_get_args();
3065 foreach ( $permissions as $permission ) {
3066 if ( $this->isAllowed( $permission ) ) {
3075 * @internal param $varargs string
3076 * @return bool True if the user is allowed to perform *all* of the given actions
3078 public function isAllowedAll( /*...*/ ) {
3079 $permissions = func_get_args();
3080 foreach ( $permissions as $permission ) {
3081 if ( !$this->isAllowed( $permission ) ) {
3089 * Internal mechanics of testing a permission
3090 * @param string $action
3093 public function isAllowed( $action = '' ) {
3094 if ( $action === '' ) {
3095 return true; // In the spirit of DWIM
3097 // Patrolling may not be enabled
3098 if ( $action === 'patrol' ||
$action === 'autopatrol' ) {
3099 global $wgUseRCPatrol, $wgUseNPPatrol;
3100 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3104 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3105 // by misconfiguration: 0 == 'foo'
3106 return in_array( $action, $this->getRights(), true );
3110 * Check whether to enable recent changes patrol features for this user
3111 * @return bool True or false
3113 public function useRCPatrol() {
3114 global $wgUseRCPatrol;
3115 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3119 * Check whether to enable new pages patrol features for this user
3120 * @return bool True or false
3122 public function useNPPatrol() {
3123 global $wgUseRCPatrol, $wgUseNPPatrol;
3125 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3126 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3131 * Get the WebRequest object to use with this object
3133 * @return WebRequest
3135 public function getRequest() {
3136 if ( $this->mRequest
) {
3137 return $this->mRequest
;
3145 * Get the current skin, loading it if required
3146 * @return Skin The current skin
3147 * @todo FIXME: Need to check the old failback system [AV]
3148 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3150 public function getSkin() {
3151 wfDeprecated( __METHOD__
, '1.18' );
3152 return RequestContext
::getMain()->getSkin();
3156 * Get a WatchedItem for this user and $title.
3158 * @since 1.22 $checkRights parameter added
3159 * @param Title $title
3160 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3161 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3162 * @return WatchedItem
3164 public function getWatchedItem( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3165 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3167 if ( isset( $this->mWatchedItems
[$key] ) ) {
3168 return $this->mWatchedItems
[$key];
3171 if ( count( $this->mWatchedItems
) >= self
::MAX_WATCHED_ITEMS_CACHE
) {
3172 $this->mWatchedItems
= array();
3175 $this->mWatchedItems
[$key] = WatchedItem
::fromUserTitle( $this, $title, $checkRights );
3176 return $this->mWatchedItems
[$key];
3180 * Check the watched status of an article.
3181 * @since 1.22 $checkRights parameter added
3182 * @param Title $title Title of the article to look at
3183 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3184 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3187 public function isWatched( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3188 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3193 * @since 1.22 $checkRights parameter added
3194 * @param Title $title Title of the article to look at
3195 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3196 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3198 public function addWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3199 $this->getWatchedItem( $title, $checkRights )->addWatch();
3200 $this->invalidateCache();
3204 * Stop watching an article.
3205 * @since 1.22 $checkRights parameter added
3206 * @param Title $title Title of the article to look at
3207 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3208 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3210 public function removeWatch( $title, $checkRights = WatchedItem
::CHECK_USER_RIGHTS
) {
3211 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3212 $this->invalidateCache();
3216 * Clear the user's notification timestamp for the given title.
3217 * If e-notif e-mails are on, they will receive notification mails on
3218 * the next change of the page if it's watched etc.
3219 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3220 * @param Title $title Title of the article to look at
3221 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3223 public function clearNotification( &$title, $oldid = 0 ) {
3224 global $wgUseEnotif, $wgShowUpdatedMarker;
3226 // Do nothing if the database is locked to writes
3227 if ( wfReadOnly() ) {
3231 // Do nothing if not allowed to edit the watchlist
3232 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3236 // If we're working on user's talk page, we should update the talk page message indicator
3237 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3238 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3242 $nextid = $oldid ?
$title->getNextRevisionID( $oldid ) : null;
3244 if ( !$oldid ||
!$nextid ) {
3245 // If we're looking at the latest revision, we should definitely clear it
3246 $this->setNewtalk( false );
3248 // Otherwise we should update its revision, if it's present
3249 if ( $this->getNewtalk() ) {
3250 // Naturally the other one won't clear by itself
3251 $this->setNewtalk( false );
3252 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3257 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3261 if ( $this->isAnon() ) {
3262 // Nothing else to do...
3266 // Only update the timestamp if the page is being watched.
3267 // The query to find out if it is watched is cached both in memcached and per-invocation,
3268 // and when it does have to be executed, it can be on a slave
3269 // If this is the user's newtalk page, we always update the timestamp
3271 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3275 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3279 * Resets all of the given user's page-change notification timestamps.
3280 * If e-notif e-mails are on, they will receive notification mails on
3281 * the next change of any watched page.
3282 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3284 public function clearAllNotifications() {
3285 if ( wfReadOnly() ) {
3289 // Do nothing if not allowed to edit the watchlist
3290 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3294 global $wgUseEnotif, $wgShowUpdatedMarker;
3295 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3296 $this->setNewtalk( false );
3299 $id = $this->getId();
3301 $dbw = wfGetDB( DB_MASTER
);
3302 $dbw->update( 'watchlist',
3303 array( /* SET */ 'wl_notificationtimestamp' => null ),
3304 array( /* WHERE */ 'wl_user' => $id ),
3307 // We also need to clear here the "you have new message" notification for the own user_talk page;
3308 // it's cleared one page view later in WikiPage::doViewUpdates().
3313 * Set a cookie on the user's client. Wrapper for
3314 * WebResponse::setCookie
3315 * @param string $name Name of the cookie to set
3316 * @param string $value Value to set
3317 * @param int $exp Expiration time, as a UNIX time value;
3318 * if 0 or not specified, use the default $wgCookieExpiration
3319 * @param bool $secure
3320 * true: Force setting the secure attribute when setting the cookie
3321 * false: Force NOT setting the secure attribute when setting the cookie
3322 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3323 * @param array $params Array of options sent passed to WebResponse::setcookie()
3325 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3326 $params['secure'] = $secure;
3327 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3331 * Clear a cookie on the user's client
3332 * @param string $name Name of the cookie to clear
3333 * @param bool $secure
3334 * true: Force setting the secure attribute when setting the cookie
3335 * false: Force NOT setting the secure attribute when setting the cookie
3336 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3337 * @param array $params Array of options sent passed to WebResponse::setcookie()
3339 protected function clearCookie( $name, $secure = null, $params = array() ) {
3340 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3344 * Set the default cookies for this session on the user's client.
3346 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3348 * @param bool $secure Whether to force secure/insecure cookies or use default
3349 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3351 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3352 if ( $request === null ) {
3353 $request = $this->getRequest();
3357 if ( 0 == $this->mId
) {
3360 if ( !$this->mToken
) {
3361 // When token is empty or NULL generate a new one and then save it to the database
3362 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3363 // Simply by setting every cell in the user_token column to NULL and letting them be
3364 // regenerated as users log back into the wiki.
3366 $this->saveSettings();
3369 'wsUserID' => $this->mId
,
3370 'wsToken' => $this->mToken
,
3371 'wsUserName' => $this->getName()
3374 'UserID' => $this->mId
,
3375 'UserName' => $this->getName(),
3377 if ( $rememberMe ) {
3378 $cookies['Token'] = $this->mToken
;
3380 $cookies['Token'] = false;
3383 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3385 foreach ( $session as $name => $value ) {
3386 $request->setSessionData( $name, $value );
3388 foreach ( $cookies as $name => $value ) {
3389 if ( $value === false ) {
3390 $this->clearCookie( $name );
3392 $this->setCookie( $name, $value, 0, $secure );
3397 * If wpStickHTTPS was selected, also set an insecure cookie that
3398 * will cause the site to redirect the user to HTTPS, if they access
3399 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3400 * as the one set by centralauth (bug 53538). Also set it to session, or
3401 * standard time setting, based on if rememberme was set.
3403 if ( $request->getCheck( 'wpStickHTTPS' ) ||
$this->requiresHTTPS() ) {
3407 $rememberMe ?
0 : null,
3409 array( 'prefix' => '' ) // no prefix
3415 * Log this user out.
3417 public function logout() {
3418 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3424 * Clear the user's cookies and session, and reset the instance cache.
3427 public function doLogout() {
3428 $this->clearInstanceCache( 'defaults' );
3430 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3432 $this->clearCookie( 'UserID' );
3433 $this->clearCookie( 'Token' );
3434 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3436 // Remember when user logged out, to prevent seeing cached pages
3437 $this->setCookie( 'LoggedOut', time(), time() +
86400 );
3441 * Save this user's settings into the database.
3442 * @todo Only rarely do all these fields need to be set!
3444 public function saveSettings() {
3448 $this->loadPasswords();
3449 if ( wfReadOnly() ) {
3452 if ( 0 == $this->mId
) {
3456 $this->mTouched
= self
::newTouchedTimestamp();
3457 if ( !$wgAuth->allowSetLocalPassword() ) {
3458 $this->mPassword
= self
::getPasswordFactory()->newFromCiphertext( null );
3461 $dbw = wfGetDB( DB_MASTER
);
3462 $dbw->update( 'user',
3464 'user_name' => $this->mName
,
3465 'user_password' => $this->mPassword
->toString(),
3466 'user_newpassword' => $this->mNewpassword
->toString(),
3467 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3468 'user_real_name' => $this->mRealName
,
3469 'user_email' => $this->mEmail
,
3470 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3471 'user_touched' => $dbw->timestamp( $this->mTouched
),
3472 'user_token' => strval( $this->mToken
),
3473 'user_email_token' => $this->mEmailToken
,
3474 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3475 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires
),
3476 ), array( /* WHERE */
3477 'user_id' => $this->mId
3481 $this->saveOptions();
3483 wfRunHooks( 'UserSaveSettings', array( $this ) );
3484 $this->clearSharedCache();
3485 $this->getUserPage()->invalidateCache();
3489 * If only this user's username is known, and it exists, return the user ID.
3492 public function idForName() {
3493 $s = trim( $this->getName() );
3498 $dbr = wfGetDB( DB_SLAVE
);
3499 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
3500 if ( $id === false ) {
3507 * Add a user to the database, return the user object
3509 * @param string $name Username to add
3510 * @param array $params Array of Strings Non-default parameters to save to
3511 * the database as user_* fields:
3512 * - password: The user's password hash. Password logins will be disabled
3513 * if this is omitted.
3514 * - newpassword: Hash for a temporary password that has been mailed to
3516 * - email: The user's email address.
3517 * - email_authenticated: The email authentication timestamp.
3518 * - real_name: The user's real name.
3519 * - options: An associative array of non-default options.
3520 * - token: Random authentication token. Do not set.
3521 * - registration: Registration timestamp. Do not set.
3523 * @return User|null User object, or null if the username already exists.
3525 public static function createNew( $name, $params = array() ) {
3528 $user->loadPasswords();
3529 $user->setToken(); // init token
3530 if ( isset( $params['options'] ) ) {
3531 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3532 unset( $params['options'] );
3534 $dbw = wfGetDB( DB_MASTER
);
3535 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3538 'user_id' => $seqVal,
3539 'user_name' => $name,
3540 'user_password' => $user->mPassword
->toString(),
3541 'user_newpassword' => $user->mNewpassword
->toString(),
3542 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime
),
3543 'user_email' => $user->mEmail
,
3544 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3545 'user_real_name' => $user->mRealName
,
3546 'user_token' => strval( $user->mToken
),
3547 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3548 'user_editcount' => 0,
3549 'user_touched' => $dbw->timestamp( self
::newTouchedTimestamp() ),
3551 foreach ( $params as $name => $value ) {
3552 $fields["user_$name"] = $value;
3554 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
3555 if ( $dbw->affectedRows() ) {
3556 $newUser = User
::newFromId( $dbw->insertId() );
3564 * Add this existing user object to the database. If the user already
3565 * exists, a fatal status object is returned, and the user object is
3566 * initialised with the data from the database.
3568 * Previously, this function generated a DB error due to a key conflict
3569 * if the user already existed. Many extension callers use this function
3570 * in code along the lines of:
3572 * $user = User::newFromName( $name );
3573 * if ( !$user->isLoggedIn() ) {
3574 * $user->addToDatabase();
3576 * // do something with $user...
3578 * However, this was vulnerable to a race condition (bug 16020). By
3579 * initialising the user object if the user exists, we aim to support this
3580 * calling sequence as far as possible.
3582 * Note that if the user exists, this function will acquire a write lock,
3583 * so it is still advisable to make the call conditional on isLoggedIn(),
3584 * and to commit the transaction after calling.
3586 * @throws MWException
3589 public function addToDatabase() {
3591 $this->loadPasswords();
3592 if ( !$this->mToken
) {
3593 $this->setToken(); // init token
3596 $this->mTouched
= self
::newTouchedTimestamp();
3598 $dbw = wfGetDB( DB_MASTER
);
3599 $inWrite = $dbw->writesOrCallbacksPending();
3600 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3601 $dbw->insert( 'user',
3603 'user_id' => $seqVal,
3604 'user_name' => $this->mName
,
3605 'user_password' => $this->mPassword
->toString(),
3606 'user_newpassword' => $this->mNewpassword
->toString(),
3607 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
3608 'user_email' => $this->mEmail
,
3609 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3610 'user_real_name' => $this->mRealName
,
3611 'user_token' => strval( $this->mToken
),
3612 'user_registration' => $dbw->timestamp( $this->mRegistration
),
3613 'user_editcount' => 0,
3614 'user_touched' => $dbw->timestamp( $this->mTouched
),
3618 if ( !$dbw->affectedRows() ) {
3619 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3620 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3622 // Can't commit due to pending writes that may need atomicity.
3623 // This may cause some lock contention unlike the case below.
3624 $options = array( 'LOCK IN SHARE MODE' );
3625 $flags = self
::READ_LOCKING
;
3627 // Often, this case happens early in views before any writes when
3628 // using CentralAuth. It's should be OK to commit and break the snapshot.
3629 $dbw->commit( __METHOD__
, 'flush' );
3633 $this->mId
= $dbw->selectField( 'user', 'user_id',
3634 array( 'user_name' => $this->mName
), __METHOD__
, $options );
3637 if ( $this->loadFromDatabase( $flags ) ) {
3642 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
3643 "to insert user '{$this->mName}' row, but it was not present in select!" );
3645 return Status
::newFatal( 'userexists' );
3647 $this->mId
= $dbw->insertId();
3649 // Clear instance cache other than user table data, which is already accurate
3650 $this->clearInstanceCache();
3652 $this->saveOptions();
3653 return Status
::newGood();
3657 * If this user is logged-in and blocked,
3658 * block any IP address they've successfully logged in from.
3659 * @return bool A block was spread
3661 public function spreadAnyEditBlock() {
3662 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3663 return $this->spreadBlock();
3669 * If this (non-anonymous) user is blocked,
3670 * block the IP address they've successfully logged in from.
3671 * @return bool A block was spread
3673 protected function spreadBlock() {
3674 wfDebug( __METHOD__
. "()\n" );
3676 if ( $this->mId
== 0 ) {
3680 $userblock = Block
::newFromTarget( $this->getName() );
3681 if ( !$userblock ) {
3685 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3689 * Get whether the user is explicitly blocked from account creation.
3690 * @return bool|Block
3692 public function isBlockedFromCreateAccount() {
3693 $this->getBlockedStatus();
3694 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
3695 return $this->mBlock
;
3698 # bug 13611: if the IP address the user is trying to create an account from is
3699 # blocked with createaccount disabled, prevent new account creation there even
3700 # when the user is logged in
3701 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3702 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
3704 return $this->mBlockedFromCreateAccount
instanceof Block
3705 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
3706 ?
$this->mBlockedFromCreateAccount
3711 * Get whether the user is blocked from using Special:Emailuser.
3714 public function isBlockedFromEmailuser() {
3715 $this->getBlockedStatus();
3716 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
3720 * Get whether the user is allowed to create an account.
3723 public function isAllowedToCreateAccount() {
3724 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3728 * Get this user's personal page title.
3730 * @return Title User's personal page title
3732 public function getUserPage() {
3733 return Title
::makeTitle( NS_USER
, $this->getName() );
3737 * Get this user's talk page title.
3739 * @return Title User's talk page title
3741 public function getTalkPage() {
3742 $title = $this->getUserPage();
3743 return $title->getTalkPage();
3747 * Determine whether the user is a newbie. Newbies are either
3748 * anonymous IPs, or the most recently created accounts.
3751 public function isNewbie() {
3752 return !$this->isAllowed( 'autoconfirmed' );
3756 * Check to see if the given clear-text password is one of the accepted passwords
3757 * @param string $password User password
3758 * @return bool True if the given password is correct, otherwise False
3760 public function checkPassword( $password ) {
3761 global $wgAuth, $wgLegacyEncoding;
3762 $this->loadPasswords();
3764 // Certain authentication plugins do NOT want to save
3765 // domain passwords in a mysql database, so we should
3766 // check this (in case $wgAuth->strict() is false).
3768 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3770 } elseif ( $wgAuth->strict() ) {
3771 // Auth plugin doesn't allow local authentication
3773 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3774 // Auth plugin doesn't allow local authentication for this user name
3778 $passwordFactory = self
::getPasswordFactory();
3779 if ( !$this->mPassword
->equals( $password ) ) {
3780 if ( $wgLegacyEncoding ) {
3781 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3782 // Check for this with iconv
3783 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3784 if ( $cp1252Password === $password ||
!$this->mPassword
->equals( $cp1252Password ) ) {
3792 if ( $passwordFactory->needsUpdate( $this->mPassword
) ) {
3793 $this->mPassword
= $passwordFactory->newFromPlaintext( $password );
3794 $this->saveSettings();
3801 * Check if the given clear-text password matches the temporary password
3802 * sent by e-mail for password reset operations.
3804 * @param string $plaintext
3806 * @return bool True if matches, false otherwise
3808 public function checkTemporaryPassword( $plaintext ) {
3809 global $wgNewPasswordExpiry;
3812 $this->loadPasswords();
3813 if ( $this->mNewpassword
->equals( $plaintext ) ) {
3814 if ( is_null( $this->mNewpassTime
) ) {
3817 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgNewPasswordExpiry;
3818 return ( time() < $expiry );
3825 * Alias for getEditToken.
3826 * @deprecated since 1.19, use getEditToken instead.
3828 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3829 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3830 * @return string The new edit token
3832 public function editToken( $salt = '', $request = null ) {
3833 wfDeprecated( __METHOD__
, '1.19' );
3834 return $this->getEditToken( $salt, $request );
3838 * Initialize (if necessary) and return a session token value
3839 * which can be used in edit forms to show that the user's
3840 * login credentials aren't being hijacked with a foreign form
3845 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3846 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3847 * @return string The new edit token
3849 public function getEditToken( $salt = '', $request = null ) {
3850 if ( $request == null ) {
3851 $request = $this->getRequest();
3854 if ( $this->isAnon() ) {
3855 return self
::EDIT_TOKEN_SUFFIX
;
3857 $token = $request->getSessionData( 'wsEditToken' );
3858 if ( $token === null ) {
3859 $token = MWCryptRand
::generateHex( 32 );
3860 $request->setSessionData( 'wsEditToken', $token );
3862 if ( is_array( $salt ) ) {
3863 $salt = implode( '|', $salt );
3865 return md5( $token . $salt ) . self
::EDIT_TOKEN_SUFFIX
;
3870 * Generate a looking random token for various uses.
3872 * @return string The new random token
3873 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3874 * wfRandomString for pseudo-randomness.
3876 public static function generateToken() {
3877 return MWCryptRand
::generateHex( 32 );
3881 * Check given value against the token value stored in the session.
3882 * A match should confirm that the form was submitted from the
3883 * user's own login session, not a form submission from a third-party
3886 * @param string $val Input value to compare
3887 * @param string $salt Optional function-specific data for hashing
3888 * @param WebRequest|null $request Object to use or null to use $wgRequest
3889 * @return bool Whether the token matches
3891 public function matchEditToken( $val, $salt = '', $request = null ) {
3892 $sessionToken = $this->getEditToken( $salt, $request );
3893 if ( $val != $sessionToken ) {
3894 wfDebug( "User::matchEditToken: broken session data\n" );
3897 return $val == $sessionToken;
3901 * Check given value against the token value stored in the session,
3902 * ignoring the suffix.
3904 * @param string $val Input value to compare
3905 * @param string $salt Optional function-specific data for hashing
3906 * @param WebRequest|null $request Object to use or null to use $wgRequest
3907 * @return bool Whether the token matches
3909 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3910 $sessionToken = $this->getEditToken( $salt, $request );
3911 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3915 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3916 * mail to the user's given address.
3918 * @param string $type Message to send, either "created", "changed" or "set"
3921 public function sendConfirmationMail( $type = 'created' ) {
3923 $expiration = null; // gets passed-by-ref and defined in next line.
3924 $token = $this->confirmationToken( $expiration );
3925 $url = $this->confirmationTokenUrl( $token );
3926 $invalidateURL = $this->invalidationTokenUrl( $token );
3927 $this->saveSettings();
3929 if ( $type == 'created' ||
$type === false ) {
3930 $message = 'confirmemail_body';
3931 } elseif ( $type === true ) {
3932 $message = 'confirmemail_body_changed';
3934 // Messages: confirmemail_body_changed, confirmemail_body_set
3935 $message = 'confirmemail_body_' . $type;
3938 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3939 wfMessage( $message,
3940 $this->getRequest()->getIP(),
3943 $wgLang->timeanddate( $expiration, false ),
3945 $wgLang->date( $expiration, false ),
3946 $wgLang->time( $expiration, false ) )->text() );
3950 * Send an e-mail to this user's account. Does not check for
3951 * confirmed status or validity.
3953 * @param string $subject Message subject
3954 * @param string $body Message body
3955 * @param string $from Optional From address; if unspecified, default
3956 * $wgPasswordSender will be used.
3957 * @param string $replyto Reply-To address
3960 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3961 if ( is_null( $from ) ) {
3962 global $wgPasswordSender;
3963 $sender = new MailAddress( $wgPasswordSender,
3964 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3966 $sender = new MailAddress( $from );
3969 $to = new MailAddress( $this );
3970 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
3974 * Generate, store, and return a new e-mail confirmation code.
3975 * A hash (unsalted, since it's used as a key) is stored.
3977 * @note Call saveSettings() after calling this function to commit
3978 * this change to the database.
3980 * @param string &$expiration Accepts the expiration time
3981 * @return string New token
3983 protected function confirmationToken( &$expiration ) {
3984 global $wgUserEmailConfirmationTokenExpiry;
3986 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
3987 $expiration = wfTimestamp( TS_MW
, $expires );
3989 $token = MWCryptRand
::generateHex( 32 );
3990 $hash = md5( $token );
3991 $this->mEmailToken
= $hash;
3992 $this->mEmailTokenExpires
= $expiration;
3997 * Return a URL the user can use to confirm their email address.
3998 * @param string $token Accepts the email confirmation token
3999 * @return string New token URL
4001 protected function confirmationTokenUrl( $token ) {
4002 return $this->getTokenUrl( 'ConfirmEmail', $token );
4006 * Return a URL the user can use to invalidate their email address.
4007 * @param string $token Accepts the email confirmation token
4008 * @return string New token URL
4010 protected function invalidationTokenUrl( $token ) {
4011 return $this->getTokenUrl( 'InvalidateEmail', $token );
4015 * Internal function to format the e-mail validation/invalidation URLs.
4016 * This uses a quickie hack to use the
4017 * hardcoded English names of the Special: pages, for ASCII safety.
4019 * @note Since these URLs get dropped directly into emails, using the
4020 * short English names avoids insanely long URL-encoded links, which
4021 * also sometimes can get corrupted in some browsers/mailers
4022 * (bug 6957 with Gmail and Internet Explorer).
4024 * @param string $page Special page
4025 * @param string $token Token
4026 * @return string Formatted URL
4028 protected function getTokenUrl( $page, $token ) {
4029 // Hack to bypass localization of 'Special:'
4030 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4031 return $title->getCanonicalURL();
4035 * Mark the e-mail address confirmed.
4037 * @note Call saveSettings() after calling this function to commit the change.
4041 public function confirmEmail() {
4042 // Check if it's already confirmed, so we don't touch the database
4043 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4044 if ( !$this->isEmailConfirmed() ) {
4045 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4046 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4052 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4053 * address if it was already confirmed.
4055 * @note Call saveSettings() after calling this function to commit the change.
4056 * @return bool Returns true
4058 public function invalidateEmail() {
4060 $this->mEmailToken
= null;
4061 $this->mEmailTokenExpires
= null;
4062 $this->setEmailAuthenticationTimestamp( null );
4064 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4069 * Set the e-mail authentication timestamp.
4070 * @param string $timestamp TS_MW timestamp
4072 public function setEmailAuthenticationTimestamp( $timestamp ) {
4074 $this->mEmailAuthenticated
= $timestamp;
4075 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
4079 * Is this user allowed to send e-mails within limits of current
4080 * site configuration?
4083 public function canSendEmail() {
4084 global $wgEnableEmail, $wgEnableUserEmail;
4085 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4088 $canSend = $this->isEmailConfirmed();
4089 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4094 * Is this user allowed to receive e-mails within limits of current
4095 * site configuration?
4098 public function canReceiveEmail() {
4099 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4103 * Is this user's e-mail address valid-looking and confirmed within
4104 * limits of the current site configuration?
4106 * @note If $wgEmailAuthentication is on, this may require the user to have
4107 * confirmed their address by returning a code or using a password
4108 * sent to the address from the wiki.
4112 public function isEmailConfirmed() {
4113 global $wgEmailAuthentication;
4116 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4117 if ( $this->isAnon() ) {
4120 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4123 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4133 * Check whether there is an outstanding request for e-mail confirmation.
4136 public function isEmailConfirmationPending() {
4137 global $wgEmailAuthentication;
4138 return $wgEmailAuthentication &&
4139 !$this->isEmailConfirmed() &&
4140 $this->mEmailToken
&&
4141 $this->mEmailTokenExpires
> wfTimestamp();
4145 * Get the timestamp of account creation.
4147 * @return string|bool|null Timestamp of account creation, false for
4148 * non-existent/anonymous user accounts, or null if existing account
4149 * but information is not in database.
4151 public function getRegistration() {
4152 if ( $this->isAnon() ) {
4156 return $this->mRegistration
;
4160 * Get the timestamp of the first edit
4162 * @return string|bool Timestamp of first edit, or false for
4163 * non-existent/anonymous user accounts.
4165 public function getFirstEditTimestamp() {
4166 if ( $this->getId() == 0 ) {
4167 return false; // anons
4169 $dbr = wfGetDB( DB_SLAVE
);
4170 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4171 array( 'rev_user' => $this->getId() ),
4173 array( 'ORDER BY' => 'rev_timestamp ASC' )
4176 return false; // no edits
4178 return wfTimestamp( TS_MW
, $time );
4182 * Get the permissions associated with a given list of groups
4184 * @param array $groups Array of Strings List of internal group names
4185 * @return array Array of Strings List of permission key names for given groups combined
4187 public static function getGroupPermissions( $groups ) {
4188 global $wgGroupPermissions, $wgRevokePermissions;
4190 // grant every granted permission first
4191 foreach ( $groups as $group ) {
4192 if ( isset( $wgGroupPermissions[$group] ) ) {
4193 $rights = array_merge( $rights,
4194 // array_filter removes empty items
4195 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4198 // now revoke the revoked permissions
4199 foreach ( $groups as $group ) {
4200 if ( isset( $wgRevokePermissions[$group] ) ) {
4201 $rights = array_diff( $rights,
4202 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4205 return array_unique( $rights );
4209 * Get all the groups who have a given permission
4211 * @param string $role Role to check
4212 * @return array Array of Strings List of internal group names with the given permission
4214 public static function getGroupsWithPermission( $role ) {
4215 global $wgGroupPermissions;
4216 $allowedGroups = array();
4217 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4218 if ( self
::groupHasPermission( $group, $role ) ) {
4219 $allowedGroups[] = $group;
4222 return $allowedGroups;
4226 * Check, if the given group has the given permission
4228 * If you're wanting to check whether all users have a permission, use
4229 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4233 * @param string $group Group to check
4234 * @param string $role Role to check
4237 public static function groupHasPermission( $group, $role ) {
4238 global $wgGroupPermissions, $wgRevokePermissions;
4239 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4240 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4244 * Check if all users have the given permission
4247 * @param string $right Right to check
4250 public static function isEveryoneAllowed( $right ) {
4251 global $wgGroupPermissions, $wgRevokePermissions;
4252 static $cache = array();
4254 // Use the cached results, except in unit tests which rely on
4255 // being able change the permission mid-request
4256 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4257 return $cache[$right];
4260 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4261 $cache[$right] = false;
4265 // If it's revoked anywhere, then everyone doesn't have it
4266 foreach ( $wgRevokePermissions as $rights ) {
4267 if ( isset( $rights[$right] ) && $rights[$right] ) {
4268 $cache[$right] = false;
4273 // Allow extensions (e.g. OAuth) to say false
4274 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4275 $cache[$right] = false;
4279 $cache[$right] = true;
4284 * Get the localized descriptive name for a group, if it exists
4286 * @param string $group Internal group name
4287 * @return string Localized descriptive group name
4289 public static function getGroupName( $group ) {
4290 $msg = wfMessage( "group-$group" );
4291 return $msg->isBlank() ?
$group : $msg->text();
4295 * Get the localized descriptive name for a member of a group, if it exists
4297 * @param string $group Internal group name
4298 * @param string $username Username for gender (since 1.19)
4299 * @return string Localized name for group member
4301 public static function getGroupMember( $group, $username = '#' ) {
4302 $msg = wfMessage( "group-$group-member", $username );
4303 return $msg->isBlank() ?
$group : $msg->text();
4307 * Return the set of defined explicit groups.
4308 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4309 * are not included, as they are defined automatically, not in the database.
4310 * @return array Array of internal group names
4312 public static function getAllGroups() {
4313 global $wgGroupPermissions, $wgRevokePermissions;
4315 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4316 self
::getImplicitGroups()
4321 * Get a list of all available permissions.
4322 * @return array Array of permission names
4324 public static function getAllRights() {
4325 if ( self
::$mAllRights === false ) {
4326 global $wgAvailableRights;
4327 if ( count( $wgAvailableRights ) ) {
4328 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4330 self
::$mAllRights = self
::$mCoreRights;
4332 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
4334 return self
::$mAllRights;
4338 * Get a list of implicit groups
4339 * @return array Array of Strings Array of internal group names
4341 public static function getImplicitGroups() {
4342 global $wgImplicitGroups;
4344 $groups = $wgImplicitGroups;
4345 # Deprecated, use $wgImplictGroups instead
4346 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4352 * Get the title of a page describing a particular group
4354 * @param string $group Internal group name
4355 * @return Title|bool Title of the page if it exists, false otherwise
4357 public static function getGroupPage( $group ) {
4358 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4359 if ( $msg->exists() ) {
4360 $title = Title
::newFromText( $msg->text() );
4361 if ( is_object( $title ) ) {
4369 * Create a link to the group in HTML, if available;
4370 * else return the group name.
4372 * @param string $group Internal name of the group
4373 * @param string $text The text of the link
4374 * @return string HTML link to the group
4376 public static function makeGroupLinkHTML( $group, $text = '' ) {
4377 if ( $text == '' ) {
4378 $text = self
::getGroupName( $group );
4380 $title = self
::getGroupPage( $group );
4382 return Linker
::link( $title, htmlspecialchars( $text ) );
4389 * Create a link to the group in Wikitext, if available;
4390 * else return the group name.
4392 * @param string $group Internal name of the group
4393 * @param string $text The text of the link
4394 * @return string Wikilink to the group
4396 public static function makeGroupLinkWiki( $group, $text = '' ) {
4397 if ( $text == '' ) {
4398 $text = self
::getGroupName( $group );
4400 $title = self
::getGroupPage( $group );
4402 $page = $title->getPrefixedText();
4403 return "[[$page|$text]]";
4410 * Returns an array of the groups that a particular group can add/remove.
4412 * @param string $group The group to check for whether it can add/remove
4413 * @return array Array( 'add' => array( addablegroups ),
4414 * 'remove' => array( removablegroups ),
4415 * 'add-self' => array( addablegroups to self),
4416 * 'remove-self' => array( removable groups from self) )
4418 public static function changeableByGroup( $group ) {
4419 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4423 'remove' => array(),
4424 'add-self' => array(),
4425 'remove-self' => array()
4428 if ( empty( $wgAddGroups[$group] ) ) {
4429 // Don't add anything to $groups
4430 } elseif ( $wgAddGroups[$group] === true ) {
4431 // You get everything
4432 $groups['add'] = self
::getAllGroups();
4433 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4434 $groups['add'] = $wgAddGroups[$group];
4437 // Same thing for remove
4438 if ( empty( $wgRemoveGroups[$group] ) ) {
4439 } elseif ( $wgRemoveGroups[$group] === true ) {
4440 $groups['remove'] = self
::getAllGroups();
4441 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4442 $groups['remove'] = $wgRemoveGroups[$group];
4445 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4446 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4447 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4448 if ( is_int( $key ) ) {
4449 $wgGroupsAddToSelf['user'][] = $value;
4454 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4455 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4456 if ( is_int( $key ) ) {
4457 $wgGroupsRemoveFromSelf['user'][] = $value;
4462 // Now figure out what groups the user can add to him/herself
4463 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4464 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4465 // No idea WHY this would be used, but it's there
4466 $groups['add-self'] = User
::getAllGroups();
4467 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4468 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4471 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4472 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4473 $groups['remove-self'] = User
::getAllGroups();
4474 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4475 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4482 * Returns an array of groups that this user can add and remove
4483 * @return array Array( 'add' => array( addablegroups ),
4484 * 'remove' => array( removablegroups ),
4485 * 'add-self' => array( addablegroups to self),
4486 * 'remove-self' => array( removable groups from self) )
4488 public function changeableGroups() {
4489 if ( $this->isAllowed( 'userrights' ) ) {
4490 // This group gives the right to modify everything (reverse-
4491 // compatibility with old "userrights lets you change
4493 // Using array_merge to make the groups reindexed
4494 $all = array_merge( User
::getAllGroups() );
4498 'add-self' => array(),
4499 'remove-self' => array()
4503 // Okay, it's not so simple, we will have to go through the arrays
4506 'remove' => array(),
4507 'add-self' => array(),
4508 'remove-self' => array()
4510 $addergroups = $this->getEffectiveGroups();
4512 foreach ( $addergroups as $addergroup ) {
4513 $groups = array_merge_recursive(
4514 $groups, $this->changeableByGroup( $addergroup )
4516 $groups['add'] = array_unique( $groups['add'] );
4517 $groups['remove'] = array_unique( $groups['remove'] );
4518 $groups['add-self'] = array_unique( $groups['add-self'] );
4519 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4525 * Increment the user's edit-count field.
4526 * Will have no effect for anonymous users.
4528 public function incEditCount() {
4529 if ( !$this->isAnon() ) {
4530 $dbw = wfGetDB( DB_MASTER
);
4533 array( 'user_editcount=user_editcount+1' ),
4534 array( 'user_id' => $this->getId() ),
4538 // Lazy initialization check...
4539 if ( $dbw->affectedRows() == 0 ) {
4540 // Now here's a goddamn hack...
4541 $dbr = wfGetDB( DB_SLAVE
);
4542 if ( $dbr !== $dbw ) {
4543 // If we actually have a slave server, the count is
4544 // at least one behind because the current transaction
4545 // has not been committed and replicated.
4546 $this->initEditCount( 1 );
4548 // But if DB_SLAVE is selecting the master, then the
4549 // count we just read includes the revision that was
4550 // just added in the working transaction.
4551 $this->initEditCount();
4555 // edit count in user cache too
4556 $this->invalidateCache();
4560 * Initialize user_editcount from data out of the revision table
4562 * @param int $add Edits to add to the count from the revision table
4563 * @return int Number of edits
4565 protected function initEditCount( $add = 0 ) {
4566 // Pull from a slave to be less cruel to servers
4567 // Accuracy isn't the point anyway here
4568 $dbr = wfGetDB( DB_SLAVE
);
4569 $count = (int)$dbr->selectField(
4572 array( 'rev_user' => $this->getId() ),
4575 $count = $count +
$add;
4577 $dbw = wfGetDB( DB_MASTER
);
4580 array( 'user_editcount' => $count ),
4581 array( 'user_id' => $this->getId() ),
4589 * Get the description of a given right
4591 * @param string $right Right to query
4592 * @return string Localized description of the right
4594 public static function getRightDescription( $right ) {
4595 $key = "right-$right";
4596 $msg = wfMessage( $key );
4597 return $msg->isBlank() ?
$right : $msg->text();
4601 * Make a new-style password hash
4603 * @param string $password Plain-text password
4604 * @param bool|string $salt Optional salt, may be random or the user ID.
4605 * If unspecified or false, will generate one automatically
4606 * @return string Password hash
4607 * @deprecated since 1.24, use Password class
4609 public static function crypt( $password, $salt = false ) {
4610 wfDeprecated( __METHOD__
, '1.24' );
4611 $hash = self
::getPasswordFactory()->newFromPlaintext( $password );
4612 return $hash->toString();
4616 * Compare a password hash with a plain-text password. Requires the user
4617 * ID if there's a chance that the hash is an old-style hash.
4619 * @param string $hash Password hash
4620 * @param string $password Plain-text password to compare
4621 * @param string|bool $userId User ID for old-style password salt
4624 * @deprecated since 1.24, use Password class
4626 public static function comparePasswords( $hash, $password, $userId = false ) {
4627 wfDeprecated( __METHOD__
, '1.24' );
4629 // Check for *really* old password hashes that don't even have a type
4630 // The old hash format was just an md5 hex hash, with no type information
4631 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4632 global $wgPasswordSalt;
4633 if ( $wgPasswordSalt ) {
4634 $password = ":B:{$userId}:{$hash}";
4636 $password = ":A:{$hash}";
4640 $hash = self
::getPasswordFactory()->newFromCiphertext( $hash );
4641 return $hash->equals( $password );
4645 * Add a newuser log entry for this user.
4646 * Before 1.19 the return value was always true.
4648 * @param string|bool $action Account creation type.
4649 * - String, one of the following values:
4650 * - 'create' for an anonymous user creating an account for himself.
4651 * This will force the action's performer to be the created user itself,
4652 * no matter the value of $wgUser
4653 * - 'create2' for a logged in user creating an account for someone else
4654 * - 'byemail' when the created user will receive its password by e-mail
4655 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4656 * - Boolean means whether the account was created by e-mail (deprecated):
4657 * - true will be converted to 'byemail'
4658 * - false will be converted to 'create' if this object is the same as
4659 * $wgUser and to 'create2' otherwise
4661 * @param string $reason User supplied reason
4663 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4665 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4666 global $wgUser, $wgNewUserLog;
4667 if ( empty( $wgNewUserLog ) ) {
4668 return true; // disabled
4671 if ( $action === true ) {
4672 $action = 'byemail';
4673 } elseif ( $action === false ) {
4674 if ( $this->getName() == $wgUser->getName() ) {
4677 $action = 'create2';
4681 if ( $action === 'create' ||
$action === 'autocreate' ) {
4684 $performer = $wgUser;
4687 $logEntry = new ManualLogEntry( 'newusers', $action );
4688 $logEntry->setPerformer( $performer );
4689 $logEntry->setTarget( $this->getUserPage() );
4690 $logEntry->setComment( $reason );
4691 $logEntry->setParameters( array(
4692 '4::userid' => $this->getId(),
4694 $logid = $logEntry->insert();
4696 if ( $action !== 'autocreate' ) {
4697 $logEntry->publish( $logid );
4704 * Add an autocreate newuser log entry for this user
4705 * Used by things like CentralAuth and perhaps other authplugins.
4706 * Consider calling addNewUserLogEntry() directly instead.
4710 public function addNewUserLogEntryAutoCreate() {
4711 $this->addNewUserLogEntry( 'autocreate' );
4717 * Load the user options either from cache, the database or an array
4719 * @param array $data Rows for the current user out of the user_properties table
4721 protected function loadOptions( $data = null ) {
4726 if ( $this->mOptionsLoaded
) {
4730 $this->mOptions
= self
::getDefaultOptions();
4732 if ( !$this->getId() ) {
4733 // For unlogged-in users, load language/variant options from request.
4734 // There's no need to do it for logged-in users: they can set preferences,
4735 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4736 // so don't override user's choice (especially when the user chooses site default).
4737 $variant = $wgContLang->getDefaultVariant();
4738 $this->mOptions
['variant'] = $variant;
4739 $this->mOptions
['language'] = $variant;
4740 $this->mOptionsLoaded
= true;
4744 // Maybe load from the object
4745 if ( !is_null( $this->mOptionOverrides
) ) {
4746 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4747 foreach ( $this->mOptionOverrides
as $key => $value ) {
4748 $this->mOptions
[$key] = $value;
4751 if ( !is_array( $data ) ) {
4752 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4753 // Load from database
4754 $dbr = wfGetDB( DB_SLAVE
);
4756 $res = $dbr->select(
4758 array( 'up_property', 'up_value' ),
4759 array( 'up_user' => $this->getId() ),
4763 $this->mOptionOverrides
= array();
4765 foreach ( $res as $row ) {
4766 $data[$row->up_property
] = $row->up_value
;
4769 foreach ( $data as $property => $value ) {
4770 $this->mOptionOverrides
[$property] = $value;
4771 $this->mOptions
[$property] = $value;
4775 $this->mOptionsLoaded
= true;
4777 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions
) );
4781 * Saves the non-default options for this user, as previously set e.g. via
4782 * setOption(), in the database's "user_properties" (preferences) table.
4783 * Usually used via saveSettings().
4785 protected function saveOptions() {
4786 $this->loadOptions();
4788 // Not using getOptions(), to keep hidden preferences in database
4789 $saveOptions = $this->mOptions
;
4791 // Allow hooks to abort, for instance to save to a global profile.
4792 // Reset options to default state before saving.
4793 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4797 $userId = $this->getId();
4799 $insert_rows = array(); // all the new preference rows
4800 foreach ( $saveOptions as $key => $value ) {
4801 // Don't bother storing default values
4802 $defaultOption = self
::getDefaultOption( $key );
4803 if ( ( $defaultOption === null && $value !== false && $value !== null )
4804 ||
$value != $defaultOption
4806 $insert_rows[] = array(
4807 'up_user' => $userId,
4808 'up_property' => $key,
4809 'up_value' => $value,
4814 $dbw = wfGetDB( DB_MASTER
);
4816 $res = $dbw->select( 'user_properties',
4817 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__
);
4819 // Find prior rows that need to be removed or updated. These rows will
4820 // all be deleted (the later so that INSERT IGNORE applies the new values).
4821 $keysDelete = array();
4822 foreach ( $res as $row ) {
4823 if ( !isset( $saveOptions[$row->up_property
] )
4824 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
4826 $keysDelete[] = $row->up_property
;
4830 if ( count( $keysDelete ) ) {
4831 // Do the DELETE by PRIMARY KEY for prior rows.
4832 // In the past a very large portion of calls to this function are for setting
4833 // 'rememberpassword' for new accounts (a preference that has since been removed).
4834 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4835 // caused gap locks on [max user ID,+infinity) which caused high contention since
4836 // updates would pile up on each other as they are for higher (newer) user IDs.
4837 // It might not be necessary these days, but it shouldn't hurt either.
4838 $dbw->delete( 'user_properties',
4839 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__
);
4841 // Insert the new preference rows
4842 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, array( 'IGNORE' ) );
4846 * Lazily instantiate and return a factory object for making passwords
4848 * @return PasswordFactory
4850 public static function getPasswordFactory() {
4851 if ( self
::$mPasswordFactory === null ) {
4852 self
::$mPasswordFactory = new PasswordFactory();
4853 self
::$mPasswordFactory->init( RequestContext
::getMain()->getConfig() );
4856 return self
::$mPasswordFactory;
4860 * Provide an array of HTML5 attributes to put on an input element
4861 * intended for the user to enter a new password. This may include
4862 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4864 * Do *not* use this when asking the user to enter his current password!
4865 * Regardless of configuration, users may have invalid passwords for whatever
4866 * reason (e.g., they were set before requirements were tightened up).
4867 * Only use it when asking for a new password, like on account creation or
4870 * Obviously, you still need to do server-side checking.
4872 * NOTE: A combination of bugs in various browsers means that this function
4873 * actually just returns array() unconditionally at the moment. May as
4874 * well keep it around for when the browser bugs get fixed, though.
4876 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4878 * @return array Array of HTML attributes suitable for feeding to
4879 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4880 * That will get confused by the boolean attribute syntax used.)
4882 public static function passwordChangeInputAttribs() {
4883 global $wgMinimalPasswordLength;
4885 if ( $wgMinimalPasswordLength == 0 ) {
4889 # Note that the pattern requirement will always be satisfied if the
4890 # input is empty, so we need required in all cases.
4892 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4893 # if e-mail confirmation is being used. Since HTML5 input validation
4894 # is b0rked anyway in some browsers, just return nothing. When it's
4895 # re-enabled, fix this code to not output required for e-mail
4897 #$ret = array( 'required' );
4900 # We can't actually do this right now, because Opera 9.6 will print out
4901 # the entered password visibly in its error message! When other
4902 # browsers add support for this attribute, or Opera fixes its support,
4903 # we can add support with a version check to avoid doing this on Opera
4904 # versions where it will be a problem. Reported to Opera as
4905 # DSK-262266, but they don't have a public bug tracker for us to follow.
4907 if ( $wgMinimalPasswordLength > 1 ) {
4908 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4909 $ret['title'] = wfMessage( 'passwordtooshort' )
4910 ->numParams( $wgMinimalPasswordLength )->text();
4918 * Return the list of user fields that should be selected to create
4919 * a new user object.
4922 public static function selectFields() {
4930 'user_email_authenticated',
4932 'user_email_token_expires',
4933 'user_registration',
4939 * Factory function for fatal permission-denied errors
4942 * @param string $permission User right required
4945 static function newFatalPermissionDeniedStatus( $permission ) {
4948 $groups = array_map(
4949 array( 'User', 'makeGroupLinkWiki' ),
4950 User
::getGroupsWithPermission( $permission )
4954 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4956 return Status
::newFatal( 'badaccess-group0' );