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 use MediaWiki\MediaWikiServices
;
25 use MediaWiki\Session\SessionManager
;
26 use MediaWiki\Session\Token
;
27 use MediaWiki\Auth\AuthManager
;
28 use MediaWiki\Auth\AuthenticationResponse
;
29 use MediaWiki\Auth\AuthenticationRequest
;
30 use Wikimedia\ScopedCallback
;
31 use Wikimedia\Rdbms\Database
;
32 use Wikimedia\Rdbms\DBExpectedError
;
35 * String Some punctuation to prevent editing from broken text-mangling proxies.
36 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
39 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
{
53 * @const int Number of characters in user_token field.
55 const TOKEN_LENGTH
= 32;
58 * @const string An invalid value for user_token
60 const INVALID_TOKEN
= '*** INVALID ***';
63 * Global constant made accessible as class constants so that autoloader
65 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
67 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
70 * @const int Serialized record version.
75 * Exclude user options that are set to their default value.
78 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
83 const CHECK_USER_RIGHTS
= true;
88 const IGNORE_USER_RIGHTS
= false;
91 * Array of Strings List of member variables which are saved to the
92 * shared cache (memcached). Any operation which changes the
93 * corresponding database fields must call a cache-clearing function.
96 protected static $mCacheVars = [
104 'mEmailAuthenticated',
106 'mEmailTokenExpires',
111 // user_properties table
116 * Array of Strings Core rights.
117 * Each of these should have a corresponding message of the form
121 protected static $mCoreRights = [
164 'move-categorypages',
165 'move-rootuserpages',
169 'override-export-depth',
191 'userrights-interwiki',
199 * String Cached results of getAllRights()
201 protected static $mAllRights = false;
203 /** Cache variables */
214 /** @var string TS_MW timestamp from the DB */
216 /** @var string TS_MW timestamp from cache */
217 protected $mQuickTouched;
221 public $mEmailAuthenticated;
223 protected $mEmailToken;
225 protected $mEmailTokenExpires;
227 protected $mRegistration;
229 protected $mEditCount;
231 * @var array No longer used since 1.29; use User::getGroups() instead
232 * @deprecated since 1.29
235 /** @var array Associative array of (group name => UserGroupMembership object) */
236 protected $mGroupMemberships;
238 protected $mOptionOverrides;
242 * Bool Whether the cache variables have been loaded.
245 public $mOptionsLoaded;
248 * Array with already loaded items or true if all items have been loaded.
250 protected $mLoadedItems = [];
254 * String Initialization data source if mLoadedItems!==true. May be one of:
255 * - 'defaults' anonymous user initialised from class defaults
256 * - 'name' initialise from mName
257 * - 'id' initialise from mId
258 * - 'session' log in from session if possible
260 * Use the User::newFrom*() family of functions to set this.
265 * Lazy-initialized variables, invalidated with clearInstanceCache
269 protected $mDatePreference;
277 protected $mBlockreason;
279 protected $mEffectiveGroups;
281 protected $mImplicitGroups;
283 protected $mFormerGroups;
285 protected $mGlobalBlock;
293 /** @var WebRequest */
300 protected $mAllowUsertalk;
303 private $mBlockedFromCreateAccount = false;
305 /** @var integer User::READ_* constant bitfield used to load data */
306 protected $queryFlagsUsed = self
::READ_NORMAL
;
308 /** @var string Indicates type of block (used for eventlogging)
309 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block',
312 public $blockTrigger = false;
314 public static $idCacheByName = [];
317 * Lightweight constructor for an anonymous user.
318 * Use the User::newFrom* factory functions for other kinds of users.
322 * @see newFromConfirmationCode()
323 * @see newFromSession()
326 public function __construct() {
327 $this->clearInstanceCache( 'defaults' );
333 public function __toString() {
334 return (string)$this->getName();
338 * Test if it's safe to load this User object.
340 * You should typically check this before using $wgUser or
341 * RequestContext::getUser in a method that might be called before the
342 * system has been fully initialized. If the object is unsafe, you should
343 * use an anonymous user:
345 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
351 public function isSafeToLoad() {
352 global $wgFullyInitialised;
354 // The user is safe to load if:
355 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
356 // * mLoadedItems === true (already loaded)
357 // * mFrom !== 'session' (sessions not involved at all)
359 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
360 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
364 * Load the user table data for this object from the source given by mFrom.
366 * @param integer $flags User::READ_* constant bitfield
368 public function load( $flags = self
::READ_NORMAL
) {
369 global $wgFullyInitialised;
371 if ( $this->mLoadedItems
=== true ) {
375 // Set it now to avoid infinite recursion in accessors
376 $oldLoadedItems = $this->mLoadedItems
;
377 $this->mLoadedItems
= true;
378 $this->queryFlagsUsed
= $flags;
380 // If this is called too early, things are likely to break.
381 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
382 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
383 ->warning( 'User::loadFromSession called before the end of Setup.php', [
384 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
386 $this->loadDefaults();
387 $this->mLoadedItems
= $oldLoadedItems;
391 switch ( $this->mFrom
) {
393 $this->loadDefaults();
396 // Make sure this thread sees its own changes
397 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
398 $flags |
= self
::READ_LATEST
;
399 $this->queryFlagsUsed
= $flags;
402 $this->mId
= self
::idFromName( $this->mName
, $flags );
404 // Nonexistent user placeholder object
405 $this->loadDefaults( $this->mName
);
407 $this->loadFromId( $flags );
411 $this->loadFromId( $flags );
414 if ( !$this->loadFromSession() ) {
415 // Loading from session failed. Load defaults.
416 $this->loadDefaults();
418 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
421 throw new UnexpectedValueException(
422 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
427 * Load user table data, given mId has already been set.
428 * @param integer $flags User::READ_* constant bitfield
429 * @return bool False if the ID does not exist, true otherwise
431 public function loadFromId( $flags = self
::READ_NORMAL
) {
432 if ( $this->mId
== 0 ) {
433 // Anonymous users are not in the database (don't need cache)
434 $this->loadDefaults();
438 // Try cache (unless this needs data from the master DB).
439 // NOTE: if this thread called saveSettings(), the cache was cleared.
440 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
442 if ( !$this->loadFromDatabase( $flags ) ) {
443 // Can't load from ID
447 $this->loadFromCache();
450 $this->mLoadedItems
= true;
451 $this->queryFlagsUsed
= $flags;
458 * @param string $wikiId
459 * @param integer $userId
461 public static function purge( $wikiId, $userId ) {
462 $cache = ObjectCache
::getMainWANInstance();
463 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
464 $cache->delete( $key );
469 * @param WANObjectCache $cache
472 protected function getCacheKey( WANObjectCache
$cache ) {
473 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
477 * @param WANObjectCache $cache
481 public function getMutableCacheKeys( WANObjectCache
$cache ) {
482 $id = $this->getId();
484 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
488 * Load user data from shared cache, given mId has already been set.
493 protected function loadFromCache() {
494 $cache = ObjectCache
::getMainWANInstance();
495 $data = $cache->getWithSetCallback(
496 $this->getCacheKey( $cache ),
498 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
499 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
500 wfDebug( "User: cache miss for user {$this->mId}\n" );
502 $this->loadFromDatabase( self
::READ_NORMAL
);
504 $this->loadOptions();
507 foreach ( self
::$mCacheVars as $name ) {
508 $data[$name] = $this->$name;
511 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
513 // if a user group membership is about to expire, the cache needs to
514 // expire at that time (T163691)
515 foreach ( $this->mGroupMemberships
as $ugm ) {
516 if ( $ugm->getExpiry() ) {
517 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
518 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
519 $ttl = $secondsUntilExpiry;
526 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
529 // Restore from cache
530 foreach ( self
::$mCacheVars as $name ) {
531 $this->$name = $data[$name];
537 /** @name newFrom*() static factory methods */
541 * Static factory method for creation from username.
543 * This is slightly less efficient than newFromId(), so use newFromId() if
544 * you have both an ID and a name handy.
546 * @param string $name Username, validated by Title::newFromText()
547 * @param string|bool $validate Validate username. Takes the same parameters as
548 * User::getCanonicalName(), except that true is accepted as an alias
549 * for 'valid', for BC.
551 * @return User|bool User object, or false if the username is invalid
552 * (e.g. if it contains illegal characters or is an IP address). If the
553 * username is not present in the database, the result will be a user object
554 * with a name, zero user ID and default settings.
556 public static function newFromName( $name, $validate = 'valid' ) {
557 if ( $validate === true ) {
560 $name = self
::getCanonicalName( $name, $validate );
561 if ( $name === false ) {
564 // Create unloaded user object
568 $u->setItemLoaded( 'name' );
574 * Static factory method for creation from a given user ID.
576 * @param int $id Valid user ID
577 * @return User The corresponding User object
579 public static function newFromId( $id ) {
583 $u->setItemLoaded( 'id' );
588 * Factory method to fetch whichever user has a given email confirmation code.
589 * This code is generated when an account is created or its e-mail address
592 * If the code is invalid or has expired, returns NULL.
594 * @param string $code Confirmation code
595 * @param int $flags User::READ_* bitfield
598 public static function newFromConfirmationCode( $code, $flags = 0 ) {
599 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
600 ?
wfGetDB( DB_MASTER
)
601 : wfGetDB( DB_REPLICA
);
603 $id = $db->selectField(
607 'user_email_token' => md5( $code ),
608 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
612 return $id ? User
::newFromId( $id ) : null;
616 * Create a new user object using data from session. If the login
617 * credentials are invalid, the result is an anonymous user.
619 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
622 public static function newFromSession( WebRequest
$request = null ) {
624 $user->mFrom
= 'session';
625 $user->mRequest
= $request;
630 * Create a new user object from a user row.
631 * The row should have the following fields from the user table in it:
632 * - either user_name or user_id to load further data if needed (or both)
634 * - all other fields (email, etc.)
635 * It is useless to provide the remaining fields if either user_id,
636 * user_name and user_real_name are not provided because the whole row
637 * will be loaded once more from the database when accessing them.
639 * @param stdClass $row A row from the user table
640 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
643 public static function newFromRow( $row, $data = null ) {
645 $user->loadFromRow( $row, $data );
650 * Static factory method for creation of a "system" user from username.
652 * A "system" user is an account that's used to attribute logged actions
653 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
654 * might include the 'Maintenance script' or 'Conversion script' accounts
655 * used by various scripts in the maintenance/ directory or accounts such
656 * as 'MediaWiki message delivery' used by the MassMessage extension.
658 * This can optionally create the user if it doesn't exist, and "steal" the
659 * account if it does exist.
661 * "Stealing" an existing user is intended to make it impossible for normal
662 * authentication processes to use the account, effectively disabling the
663 * account for normal use:
664 * - Email is invalidated, to prevent account recovery by emailing a
665 * temporary password and to disassociate the account from the existing
667 * - The token is set to a magic invalid value, to kill existing sessions
668 * and to prevent $this->setToken() calls from resetting the token to a
670 * - SessionManager is instructed to prevent new sessions for the user, to
671 * do things like deauthorizing OAuth consumers.
672 * - AuthManager is instructed to revoke access, to invalidate or remove
673 * passwords and other credentials.
675 * @param string $name Username
676 * @param array $options Options are:
677 * - validate: As for User::getCanonicalName(), default 'valid'
678 * - create: Whether to create the user if it doesn't already exist, default true
679 * - steal: Whether to "disable" the account for normal use if it already
680 * exists, default false
684 public static function newSystemUser( $name, $options = [] ) {
686 'validate' => 'valid',
691 $name = self
::getCanonicalName( $name, $options['validate'] );
692 if ( $name === false ) {
696 $dbr = wfGetDB( DB_REPLICA
);
697 $row = $dbr->selectRow(
699 self
::selectFields(),
700 [ 'user_name' => $name ],
704 // Try the master database...
705 $dbw = wfGetDB( DB_MASTER
);
706 $row = $dbw->selectRow(
708 self
::selectFields(),
709 [ 'user_name' => $name ],
715 // No user. Create it?
716 return $options['create']
717 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
721 $user = self
::newFromRow( $row );
723 // A user is considered to exist as a non-system user if it can
724 // authenticate, or has an email set, or has a non-invalid token.
725 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
726 AuthManager
::singleton()->userCanAuthenticate( $name )
728 // User exists. Steal it?
729 if ( !$options['steal'] ) {
733 AuthManager
::singleton()->revokeAccessForUser( $name );
735 $user->invalidateEmail();
736 $user->mToken
= self
::INVALID_TOKEN
;
737 $user->saveSettings();
738 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
747 * Get the username corresponding to a given user ID
748 * @param int $id User ID
749 * @return string|bool The corresponding username
751 public static function whoIs( $id ) {
752 return UserCache
::singleton()->getProp( $id, 'name' );
756 * Get the real name of a user given their user ID
758 * @param int $id User ID
759 * @return string|bool The corresponding user's real name
761 public static function whoIsReal( $id ) {
762 return UserCache
::singleton()->getProp( $id, 'real_name' );
766 * Get database id given a user name
767 * @param string $name Username
768 * @param integer $flags User::READ_* constant bitfield
769 * @return int|null The corresponding user's ID, or null if user is nonexistent
771 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
772 $nt = Title
::makeTitleSafe( NS_USER
, $name );
773 if ( is_null( $nt ) ) {
778 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
779 return self
::$idCacheByName[$name];
782 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
783 $db = wfGetDB( $index );
788 [ 'user_name' => $nt->getText() ],
793 if ( $s === false ) {
796 $result = $s->user_id
;
799 self
::$idCacheByName[$name] = $result;
801 if ( count( self
::$idCacheByName ) > 1000 ) {
802 self
::$idCacheByName = [];
809 * Reset the cache used in idFromName(). For use in tests.
811 public static function resetIdByNameCache() {
812 self
::$idCacheByName = [];
816 * Does the string match an anonymous IP address?
818 * This function exists for username validation, in order to reject
819 * usernames which are similar in form to IP addresses. Strings such
820 * as 300.300.300.300 will return true because it looks like an IP
821 * address, despite not being strictly valid.
823 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
824 * address because the usemod software would "cloak" anonymous IP
825 * addresses like this, if we allowed accounts like this to be created
826 * new users could get the old edits of these anonymous users.
828 * @param string $name Name to match
831 public static function isIP( $name ) {
832 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
833 || IP
::isIPv6( $name );
837 * Is the input a valid username?
839 * Checks if the input is a valid username, we don't want an empty string,
840 * an IP address, anything that contains slashes (would mess up subpages),
841 * is longer than the maximum allowed username size or doesn't begin with
844 * @param string $name Name to match
847 public static function isValidUserName( $name ) {
848 global $wgContLang, $wgMaxNameChars;
851 || User
::isIP( $name )
852 ||
strpos( $name, '/' ) !== false
853 ||
strlen( $name ) > $wgMaxNameChars
854 ||
$name != $wgContLang->ucfirst( $name )
859 // Ensure that the name can't be misresolved as a different title,
860 // such as with extra namespace keys at the start.
861 $parsed = Title
::newFromText( $name );
862 if ( is_null( $parsed )
863 ||
$parsed->getNamespace()
864 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
868 // Check an additional blacklist of troublemaker characters.
869 // Should these be merged into the title char list?
870 $unicodeBlacklist = '/[' .
871 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
872 '\x{00a0}' . # non-breaking space
873 '\x{2000}-\x{200f}' . # various whitespace
874 '\x{2028}-\x{202f}' . # breaks and control chars
875 '\x{3000}' . # ideographic space
876 '\x{e000}-\x{f8ff}' . # private use
878 if ( preg_match( $unicodeBlacklist, $name ) ) {
886 * Usernames which fail to pass this function will be blocked
887 * from user login and new account registrations, but may be used
888 * internally by batch processes.
890 * If an account already exists in this form, login will be blocked
891 * by a failure to pass this function.
893 * @param string $name Name to match
896 public static function isUsableName( $name ) {
897 global $wgReservedUsernames;
898 // Must be a valid username, obviously ;)
899 if ( !self
::isValidUserName( $name ) ) {
903 static $reservedUsernames = false;
904 if ( !$reservedUsernames ) {
905 $reservedUsernames = $wgReservedUsernames;
906 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
909 // Certain names may be reserved for batch processes.
910 foreach ( $reservedUsernames as $reserved ) {
911 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
912 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
914 if ( $reserved == $name ) {
922 * Return the users who are members of the given group(s). In case of multiple groups,
923 * users who are members of at least one of them are returned.
925 * @param string|array $groups A single group name or an array of group names
926 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
927 * records; larger values are ignored.
928 * @param int $after ID the user to start after
929 * @return UserArrayFromResult
931 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
932 if ( $groups === [] ) {
933 return UserArrayFromResult
::newFromIDs( [] );
936 $groups = array_unique( (array)$groups );
937 $limit = min( 5000, $limit );
939 $conds = [ 'ug_group' => $groups ];
940 if ( $after !== null ) {
941 $conds[] = 'ug_user > ' . (int)$after;
944 $dbr = wfGetDB( DB_REPLICA
);
945 $ids = $dbr->selectFieldValues(
952 'ORDER BY' => 'ug_user',
956 return UserArray
::newFromIDs( $ids );
960 * Usernames which fail to pass this function will be blocked
961 * from new account registrations, but may be used internally
962 * either by batch processes or by user accounts which have
963 * already been created.
965 * Additional blacklisting may be added here rather than in
966 * isValidUserName() to avoid disrupting existing accounts.
968 * @param string $name String to match
971 public static function isCreatableName( $name ) {
972 global $wgInvalidUsernameCharacters;
974 // Ensure that the username isn't longer than 235 bytes, so that
975 // (at least for the builtin skins) user javascript and css files
976 // will work. (T25080)
977 if ( strlen( $name ) > 235 ) {
978 wfDebugLog( 'username', __METHOD__
.
979 ": '$name' invalid due to length" );
983 // Preg yells if you try to give it an empty string
984 if ( $wgInvalidUsernameCharacters !== '' ) {
985 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
986 wfDebugLog( 'username', __METHOD__
.
987 ": '$name' invalid due to wgInvalidUsernameCharacters" );
992 return self
::isUsableName( $name );
996 * Is the input a valid password for this user?
998 * @param string $password Desired password
1001 public function isValidPassword( $password ) {
1002 // simple boolean wrapper for getPasswordValidity
1003 return $this->getPasswordValidity( $password ) === true;
1007 * Given unvalidated password input, return error message on failure.
1009 * @param string $password Desired password
1010 * @return bool|string|array True on success, string or array of error message on failure
1012 public function getPasswordValidity( $password ) {
1013 $result = $this->checkPasswordValidity( $password );
1014 if ( $result->isGood() ) {
1018 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1019 $messages[] = $error['message'];
1021 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1022 $messages[] = $warning['message'];
1024 if ( count( $messages ) === 1 ) {
1025 return $messages[0];
1032 * Check if this is a valid password for this user
1034 * Create a Status object based on the password's validity.
1035 * The Status should be set to fatal if the user should not
1036 * be allowed to log in, and should have any errors that
1037 * would block changing the password.
1039 * If the return value of this is not OK, the password
1040 * should not be checked. If the return value is not Good,
1041 * the password can be checked, but the user should not be
1042 * able to set their password to this.
1044 * @param string $password Desired password
1048 public function checkPasswordValidity( $password ) {
1049 global $wgPasswordPolicy;
1051 $upp = new UserPasswordPolicy(
1052 $wgPasswordPolicy['policies'],
1053 $wgPasswordPolicy['checks']
1056 $status = Status
::newGood();
1057 $result = false; // init $result to false for the internal checks
1059 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1060 $status->error( $result );
1064 if ( $result === false ) {
1065 $status->merge( $upp->checkUserPassword( $this, $password ) );
1067 } elseif ( $result === true ) {
1070 $status->error( $result );
1071 return $status; // the isValidPassword hook set a string $result and returned true
1076 * Given unvalidated user input, return a canonical username, or false if
1077 * the username is invalid.
1078 * @param string $name User input
1079 * @param string|bool $validate Type of validation to use:
1080 * - false No validation
1081 * - 'valid' Valid for batch processes
1082 * - 'usable' Valid for batch processes and login
1083 * - 'creatable' Valid for batch processes, login and account creation
1085 * @throws InvalidArgumentException
1086 * @return bool|string
1088 public static function getCanonicalName( $name, $validate = 'valid' ) {
1089 // Force usernames to capital
1091 $name = $wgContLang->ucfirst( $name );
1093 # Reject names containing '#'; these will be cleaned up
1094 # with title normalisation, but then it's too late to
1096 if ( strpos( $name, '#' ) !== false ) {
1100 // Clean up name according to title rules,
1101 // but only when validation is requested (T14654)
1102 $t = ( $validate !== false ) ?
1103 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1104 // Check for invalid titles
1105 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1109 // Reject various classes of invalid names
1110 $name = AuthManager
::callLegacyAuthPlugin(
1111 'getCanonicalName', [ $t->getText() ], $t->getText()
1114 switch ( $validate ) {
1118 if ( !User
::isValidUserName( $name ) ) {
1123 if ( !User
::isUsableName( $name ) ) {
1128 if ( !User
::isCreatableName( $name ) ) {
1133 throw new InvalidArgumentException(
1134 'Invalid parameter value for $validate in ' . __METHOD__
);
1140 * Return a random password.
1142 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1143 * @return string New random password
1145 public static function randomPassword() {
1146 global $wgMinimalPasswordLength;
1147 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1151 * Set cached properties to default.
1153 * @note This no longer clears uncached lazy-initialised properties;
1154 * the constructor does that instead.
1156 * @param string|bool $name
1158 public function loadDefaults( $name = false ) {
1160 $this->mName
= $name;
1161 $this->mRealName
= '';
1163 $this->mOptionOverrides
= null;
1164 $this->mOptionsLoaded
= false;
1166 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1167 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1168 if ( $loggedOut !== 0 ) {
1169 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1171 $this->mTouched
= '1'; # Allow any pages to be cached
1174 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1175 $this->mEmailAuthenticated
= null;
1176 $this->mEmailToken
= '';
1177 $this->mEmailTokenExpires
= null;
1178 $this->mRegistration
= wfTimestamp( TS_MW
);
1179 $this->mGroupMemberships
= [];
1181 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1185 * Return whether an item has been loaded.
1187 * @param string $item Item to check. Current possibilities:
1191 * @param string $all 'all' to check if the whole object has been loaded
1192 * or any other string to check if only the item is available (e.g.
1196 public function isItemLoaded( $item, $all = 'all' ) {
1197 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1198 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1202 * Set that an item has been loaded
1204 * @param string $item
1206 protected function setItemLoaded( $item ) {
1207 if ( is_array( $this->mLoadedItems
) ) {
1208 $this->mLoadedItems
[$item] = true;
1213 * Load user data from the session.
1215 * @return bool True if the user is logged in, false otherwise.
1217 private function loadFromSession() {
1220 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1221 if ( $result !== null ) {
1225 // MediaWiki\Session\Session already did the necessary authentication of the user
1226 // returned here, so just use it if applicable.
1227 $session = $this->getRequest()->getSession();
1228 $user = $session->getUser();
1229 if ( $user->isLoggedIn() ) {
1230 $this->loadFromUserObject( $user );
1232 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1233 // every session load, because an autoblocked editor might not edit again from the same
1234 // IP address after being blocked.
1235 $config = RequestContext
::getMain()->getConfig();
1236 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1237 $block = $this->getBlock();
1238 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1240 && $block->getType() === Block
::TYPE_USER
1241 && $block->isAutoblocking();
1242 if ( $shouldSetCookie ) {
1243 wfDebug( __METHOD__
. ': User is autoblocked, setting cookie to track' );
1244 $block->setCookie( $this->getRequest()->response() );
1248 // Other code expects these to be set in the session, so set them.
1249 $session->set( 'wsUserID', $this->getId() );
1250 $session->set( 'wsUserName', $this->getName() );
1251 $session->set( 'wsToken', $this->getToken() );
1258 * Load user and user_group data from the database.
1259 * $this->mId must be set, this is how the user is identified.
1261 * @param integer $flags User::READ_* constant bitfield
1262 * @return bool True if the user exists, false if the user is anonymous
1264 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1266 $this->mId
= intval( $this->mId
);
1268 if ( !$this->mId
) {
1269 // Anonymous users are not in the database
1270 $this->loadDefaults();
1274 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1275 $db = wfGetDB( $index );
1277 $s = $db->selectRow(
1279 self
::selectFields(),
1280 [ 'user_id' => $this->mId
],
1285 $this->queryFlagsUsed
= $flags;
1286 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1288 if ( $s !== false ) {
1289 // Initialise user table data
1290 $this->loadFromRow( $s );
1291 $this->mGroupMemberships
= null; // deferred
1292 $this->getEditCount(); // revalidation for nulls
1297 $this->loadDefaults();
1303 * Initialize this object from a row from the user table.
1305 * @param stdClass $row Row from the user table to load.
1306 * @param array $data Further user data to load into the object
1308 * user_groups Array of arrays or stdClass result rows out of the user_groups
1309 * table. Previously you were supposed to pass an array of strings
1310 * here, but we also need expiry info nowadays, so an array of
1311 * strings is ignored.
1312 * user_properties Array with properties out of the user_properties table
1314 protected function loadFromRow( $row, $data = null ) {
1317 $this->mGroupMemberships
= null; // deferred
1319 if ( isset( $row->user_name
) ) {
1320 $this->mName
= $row->user_name
;
1321 $this->mFrom
= 'name';
1322 $this->setItemLoaded( 'name' );
1327 if ( isset( $row->user_real_name
) ) {
1328 $this->mRealName
= $row->user_real_name
;
1329 $this->setItemLoaded( 'realname' );
1334 if ( isset( $row->user_id
) ) {
1335 $this->mId
= intval( $row->user_id
);
1336 $this->mFrom
= 'id';
1337 $this->setItemLoaded( 'id' );
1342 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1343 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1346 if ( isset( $row->user_editcount
) ) {
1347 $this->mEditCount
= $row->user_editcount
;
1352 if ( isset( $row->user_touched
) ) {
1353 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1358 if ( isset( $row->user_token
) ) {
1359 // The definition for the column is binary(32), so trim the NULs
1360 // that appends. The previous definition was char(32), so trim
1362 $this->mToken
= rtrim( $row->user_token
, " \0" );
1363 if ( $this->mToken
=== '' ) {
1364 $this->mToken
= null;
1370 if ( isset( $row->user_email
) ) {
1371 $this->mEmail
= $row->user_email
;
1372 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1373 $this->mEmailToken
= $row->user_email_token
;
1374 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1375 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1381 $this->mLoadedItems
= true;
1384 if ( is_array( $data ) ) {
1385 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1386 if ( !count( $data['user_groups'] ) ) {
1387 $this->mGroupMemberships
= [];
1389 $firstGroup = reset( $data['user_groups'] );
1390 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1391 $this->mGroupMemberships
= [];
1392 foreach ( $data['user_groups'] as $row ) {
1393 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1394 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1399 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1400 $this->loadOptions( $data['user_properties'] );
1406 * Load the data for this user object from another user object.
1410 protected function loadFromUserObject( $user ) {
1412 foreach ( self
::$mCacheVars as $var ) {
1413 $this->$var = $user->$var;
1418 * Load the groups from the database if they aren't already loaded.
1420 private function loadGroups() {
1421 if ( is_null( $this->mGroupMemberships
) ) {
1422 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1423 ?
wfGetDB( DB_MASTER
)
1424 : wfGetDB( DB_REPLICA
);
1425 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1431 * Add the user to the group if he/she meets given criteria.
1433 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1434 * possible to remove manually via Special:UserRights. In such case it
1435 * will not be re-added automatically. The user will also not lose the
1436 * group if they no longer meet the criteria.
1438 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1440 * @return array Array of groups the user has been promoted to.
1442 * @see $wgAutopromoteOnce
1444 public function addAutopromoteOnceGroups( $event ) {
1445 global $wgAutopromoteOnceLogInRC;
1447 if ( wfReadOnly() ||
!$this->getId() ) {
1451 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1452 if ( !count( $toPromote ) ) {
1456 if ( !$this->checkAndSetTouched() ) {
1457 return []; // raced out (bug T48834)
1460 $oldGroups = $this->getGroups(); // previous groups
1461 foreach ( $toPromote as $group ) {
1462 $this->addGroup( $group );
1464 // update groups in external authentication database
1465 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1466 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1468 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1470 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1471 $logEntry->setPerformer( $this );
1472 $logEntry->setTarget( $this->getUserPage() );
1473 $logEntry->setParameters( [
1474 '4::oldgroups' => $oldGroups,
1475 '5::newgroups' => $newGroups,
1477 $logid = $logEntry->insert();
1478 if ( $wgAutopromoteOnceLogInRC ) {
1479 $logEntry->publish( $logid );
1486 * Builds update conditions. Additional conditions may be added to $conditions to
1487 * protected against race conditions using a compare-and-set (CAS) mechanism
1488 * based on comparing $this->mTouched with the user_touched field.
1490 * @param Database $db
1491 * @param array $conditions WHERE conditions for use with Database::update
1492 * @return array WHERE conditions for use with Database::update
1494 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1495 if ( $this->mTouched
) {
1496 // CAS check: only update if the row wasn't changed sicne it was loaded.
1497 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1504 * Bump user_touched if it didn't change since this object was loaded
1506 * On success, the mTouched field is updated.
1507 * The user serialization cache is always cleared.
1509 * @return bool Whether user_touched was actually updated
1512 protected function checkAndSetTouched() {
1515 if ( !$this->mId
) {
1516 return false; // anon
1519 // Get a new user_touched that is higher than the old one
1520 $newTouched = $this->newTouchedTimestamp();
1522 $dbw = wfGetDB( DB_MASTER
);
1523 $dbw->update( 'user',
1524 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1525 $this->makeUpdateConditions( $dbw, [
1526 'user_id' => $this->mId
,
1530 $success = ( $dbw->affectedRows() > 0 );
1533 $this->mTouched
= $newTouched;
1534 $this->clearSharedCache();
1536 // Clears on failure too since that is desired if the cache is stale
1537 $this->clearSharedCache( 'refresh' );
1544 * Clear various cached data stored in this object. The cache of the user table
1545 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1547 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1548 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1550 public function clearInstanceCache( $reloadFrom = false ) {
1551 $this->mNewtalk
= -1;
1552 $this->mDatePreference
= null;
1553 $this->mBlockedby
= -1; # Unset
1554 $this->mHash
= false;
1555 $this->mRights
= null;
1556 $this->mEffectiveGroups
= null;
1557 $this->mImplicitGroups
= null;
1558 $this->mGroupMemberships
= null;
1559 $this->mOptions
= null;
1560 $this->mOptionsLoaded
= false;
1561 $this->mEditCount
= null;
1563 if ( $reloadFrom ) {
1564 $this->mLoadedItems
= [];
1565 $this->mFrom
= $reloadFrom;
1570 * Combine the language default options with any site-specific options
1571 * and add the default language variants.
1573 * @return array Array of String options
1575 public static function getDefaultOptions() {
1576 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1578 static $defOpt = null;
1579 static $defOptLang = null;
1581 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1582 // $wgContLang does not change (and should not change) mid-request,
1583 // but the unit tests change it anyway, and expect this method to
1584 // return values relevant to the current $wgContLang.
1588 $defOpt = $wgDefaultUserOptions;
1589 // Default language setting
1590 $defOptLang = $wgContLang->getCode();
1591 $defOpt['language'] = $defOptLang;
1592 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1593 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1596 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1597 // since extensions may change the set of searchable namespaces depending
1598 // on user groups/permissions.
1599 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1600 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1602 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1604 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1610 * Get a given default option value.
1612 * @param string $opt Name of option to retrieve
1613 * @return string Default option value
1615 public static function getDefaultOption( $opt ) {
1616 $defOpts = self
::getDefaultOptions();
1617 if ( isset( $defOpts[$opt] ) ) {
1618 return $defOpts[$opt];
1625 * Get blocking information
1626 * @param bool $bFromSlave Whether to check the replica DB first.
1627 * To improve performance, non-critical checks are done against replica DBs.
1628 * Check when actually saving should be done against master.
1630 private function getBlockedStatus( $bFromSlave = true ) {
1631 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1633 if ( -1 != $this->mBlockedby
) {
1637 wfDebug( __METHOD__
. ": checking...\n" );
1639 // Initialize data...
1640 // Otherwise something ends up stomping on $this->mBlockedby when
1641 // things get lazy-loaded later, causing false positive block hits
1642 // due to -1 !== 0. Probably session-related... Nothing should be
1643 // overwriting mBlockedby, surely?
1646 # We only need to worry about passing the IP address to the Block generator if the
1647 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1648 # know which IP address they're actually coming from
1650 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1651 // $wgUser->getName() only works after the end of Setup.php. Until
1652 // then, assume it's a logged-out user.
1653 $globalUserName = $wgUser->isSafeToLoad()
1654 ?
$wgUser->getName()
1655 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1656 if ( $this->getName() === $globalUserName ) {
1657 $ip = $this->getRequest()->getIP();
1662 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1665 if ( !$block instanceof Block
) {
1666 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1670 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1672 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1673 $block = new Block( [
1674 'byText' => wfMessage( 'proxyblocker' )->text(),
1675 'reason' => wfMessage( 'proxyblockreason' )->text(),
1677 'systemBlock' => 'proxy',
1679 $this->blockTrigger
= 'proxy-block';
1680 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1681 $block = new Block( [
1682 'byText' => wfMessage( 'sorbs' )->text(),
1683 'reason' => wfMessage( 'sorbsreason' )->text(),
1685 'systemBlock' => 'dnsbl',
1687 $this->blockTrigger
= 'openproxy-block';
1691 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1692 if ( !$block instanceof Block
1693 && $wgApplyIpBlocksToXff
1695 && !in_array( $ip, $wgProxyWhitelist )
1697 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1698 $xff = array_map( 'trim', explode( ',', $xff ) );
1699 $xff = array_diff( $xff, [ $ip ] );
1700 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1701 $block = Block
::chooseBlock( $xffblocks, $xff );
1702 if ( $block instanceof Block
) {
1703 # Mangle the reason to alert the user that the block
1704 # originated from matching the X-Forwarded-For header.
1705 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1706 $this->blockTrigger
= 'xff-block';
1710 if ( !$block instanceof Block
1713 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1715 $block = new Block( [
1717 'byText' => 'MediaWiki default',
1718 'reason' => wfMessage( 'softblockrangesreason', $ip )->text(),
1720 'systemBlock' => 'wgSoftBlockRanges',
1722 $this->blockTrigger
= 'config-block';
1725 if ( $block instanceof Block
) {
1726 wfDebug( __METHOD__
. ": Found block.\n" );
1727 $this->mBlock
= $block;
1728 $this->mBlockedby
= $block->getByName();
1729 $this->mBlockreason
= $block->mReason
;
1730 $this->mHideName
= $block->mHideName
;
1731 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1733 $this->mBlockedby
= '';
1734 $this->mHideName
= 0;
1735 $this->mAllowUsertalk
= false;
1736 $this->blockTrigger
= false;
1739 // Avoid PHP 7.1 warning of passing $this by reference
1742 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1746 * Try to load a Block from an ID given in a cookie value.
1747 * @param string|null $blockCookieVal The cookie value to check.
1748 * @return Block|bool The Block object, or false if none could be loaded.
1750 protected function getBlockFromCookieValue( $blockCookieVal ) {
1751 // Make sure there's something to check. The cookie value must start with a number.
1752 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1755 // Load the Block from the ID in the cookie.
1756 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1757 if ( $blockCookieId !== null ) {
1758 // An ID was found in the cookie.
1759 $tmpBlock = Block
::newFromID( $blockCookieId );
1760 if ( $tmpBlock instanceof Block
) {
1761 // Check the validity of the block.
1762 $blockIsValid = $tmpBlock->getType() == Block
::TYPE_USER
1763 && !$tmpBlock->isExpired()
1764 && $tmpBlock->isAutoblocking();
1765 $config = RequestContext
::getMain()->getConfig();
1766 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1767 if ( $blockIsValid && $useBlockCookie ) {
1769 $this->blockTrigger
= 'cookie-block';
1772 // If the block is not valid, remove the cookie.
1773 Block
::clearCookie( $this->getRequest()->response() );
1776 // If the block doesn't exist, remove the cookie.
1777 Block
::clearCookie( $this->getRequest()->response() );
1784 * Whether the given IP is in a DNS blacklist.
1786 * @param string $ip IP to check
1787 * @param bool $checkWhitelist Whether to check the whitelist first
1788 * @return bool True if blacklisted.
1790 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1791 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1793 if ( !$wgEnableDnsBlacklist ) {
1797 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1801 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1805 * Whether the given IP is in a given DNS blacklist.
1807 * @param string $ip IP to check
1808 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1809 * @return bool True if blacklisted.
1811 public function inDnsBlacklist( $ip, $bases ) {
1813 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1814 if ( IP
::isIPv4( $ip ) ) {
1815 // Reverse IP, T23255
1816 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1818 foreach ( (array)$bases as $base ) {
1820 // If we have an access key, use that too (ProjectHoneypot, etc.)
1822 if ( is_array( $base ) ) {
1823 if ( count( $base ) >= 2 ) {
1824 // Access key is 1, base URL is 0
1825 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1827 $host = "$ipReversed.{$base[0]}";
1829 $basename = $base[0];
1831 $host = "$ipReversed.$base";
1835 $ipList = gethostbynamel( $host );
1838 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1842 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1851 * Check if an IP address is in the local proxy list
1857 public static function isLocallyBlockedProxy( $ip ) {
1858 global $wgProxyList;
1860 if ( !$wgProxyList ) {
1864 if ( !is_array( $wgProxyList ) ) {
1865 // Load values from the specified file
1866 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1869 $resultProxyList = [];
1870 $deprecatedIPEntries = [];
1872 // backward compatibility: move all ip addresses in keys to values
1873 foreach ( $wgProxyList as $key => $value ) {
1874 $keyIsIP = IP
::isIPAddress( $key );
1875 $valueIsIP = IP
::isIPAddress( $value );
1876 if ( $keyIsIP && !$valueIsIP ) {
1877 $deprecatedIPEntries[] = $key;
1878 $resultProxyList[] = $key;
1879 } elseif ( $keyIsIP && $valueIsIP ) {
1880 $deprecatedIPEntries[] = $key;
1881 $resultProxyList[] = $key;
1882 $resultProxyList[] = $value;
1884 $resultProxyList[] = $value;
1888 if ( $deprecatedIPEntries ) {
1890 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1891 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1894 $proxyListIPSet = new IPSet( $resultProxyList );
1895 return $proxyListIPSet->match( $ip );
1899 * Is this user subject to rate limiting?
1901 * @return bool True if rate limited
1903 public function isPingLimitable() {
1904 global $wgRateLimitsExcludedIPs;
1905 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1906 // No other good way currently to disable rate limits
1907 // for specific IPs. :P
1908 // But this is a crappy hack and should die.
1911 return !$this->isAllowed( 'noratelimit' );
1915 * Primitive rate limits: enforce maximum actions per time period
1916 * to put a brake on flooding.
1918 * The method generates both a generic profiling point and a per action one
1919 * (suffix being "-$action".
1921 * @note When using a shared cache like memcached, IP-address
1922 * last-hit counters will be shared across wikis.
1924 * @param string $action Action to enforce; 'edit' if unspecified
1925 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1926 * @return bool True if a rate limiter was tripped
1928 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1929 // Avoid PHP 7.1 warning of passing $this by reference
1931 // Call the 'PingLimiter' hook
1933 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1937 global $wgRateLimits;
1938 if ( !isset( $wgRateLimits[$action] ) ) {
1942 $limits = array_merge(
1943 [ '&can-bypass' => true ],
1944 $wgRateLimits[$action]
1947 // Some groups shouldn't trigger the ping limiter, ever
1948 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1953 $id = $this->getId();
1955 $isNewbie = $this->isNewbie();
1956 $cache = ObjectCache
::getLocalClusterInstance();
1960 if ( isset( $limits['anon'] ) ) {
1961 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1964 // limits for logged-in users
1965 if ( isset( $limits['user'] ) ) {
1966 $userLimit = $limits['user'];
1968 // limits for newbie logged-in users
1969 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1970 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1974 // limits for anons and for newbie logged-in users
1977 if ( isset( $limits['ip'] ) ) {
1978 $ip = $this->getRequest()->getIP();
1979 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1981 // subnet-based limits
1982 if ( isset( $limits['subnet'] ) ) {
1983 $ip = $this->getRequest()->getIP();
1984 $subnet = IP
::getSubnet( $ip );
1985 if ( $subnet !== false ) {
1986 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1991 // Check for group-specific permissions
1992 // If more than one group applies, use the group with the highest limit ratio (max/period)
1993 foreach ( $this->getGroups() as $group ) {
1994 if ( isset( $limits[$group] ) ) {
1995 if ( $userLimit === false
1996 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1998 $userLimit = $limits[$group];
2003 // Set the user limit key
2004 if ( $userLimit !== false ) {
2005 list( $max, $period ) = $userLimit;
2006 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2007 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2010 // ip-based limits for all ping-limitable users
2011 if ( isset( $limits['ip-all'] ) ) {
2012 $ip = $this->getRequest()->getIP();
2013 // ignore if user limit is more permissive
2014 if ( $isNewbie ||
$userLimit === false
2015 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2016 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2020 // subnet-based limits for all ping-limitable users
2021 if ( isset( $limits['subnet-all'] ) ) {
2022 $ip = $this->getRequest()->getIP();
2023 $subnet = IP
::getSubnet( $ip );
2024 if ( $subnet !== false ) {
2025 // ignore if user limit is more permissive
2026 if ( $isNewbie ||
$userLimit === false
2027 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2028 > $userLimit[0] / $userLimit[1] ) {
2029 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2035 foreach ( $keys as $key => $limit ) {
2036 list( $max, $period ) = $limit;
2037 $summary = "(limit $max in {$period}s)";
2038 $count = $cache->get( $key );
2041 if ( $count >= $max ) {
2042 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2043 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2046 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2049 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2050 if ( $incrBy > 0 ) {
2051 $cache->add( $key, 0, intval( $period ) ); // first ping
2054 if ( $incrBy > 0 ) {
2055 $cache->incr( $key, $incrBy );
2063 * Check if user is blocked
2065 * @param bool $bFromSlave Whether to check the replica DB instead of
2066 * the master. Hacked from false due to horrible probs on site.
2067 * @return bool True if blocked, false otherwise
2069 public function isBlocked( $bFromSlave = true ) {
2070 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2074 * Get the block affecting the user, or null if the user is not blocked
2076 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2077 * @return Block|null
2079 public function getBlock( $bFromSlave = true ) {
2080 $this->getBlockedStatus( $bFromSlave );
2081 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2085 * Check if user is blocked from editing a particular article
2087 * @param Title $title Title to check
2088 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2091 public function isBlockedFrom( $title, $bFromSlave = false ) {
2092 global $wgBlockAllowsUTEdit;
2094 $blocked = $this->isBlocked( $bFromSlave );
2095 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2096 // If a user's name is suppressed, they cannot make edits anywhere
2097 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2098 && $title->getNamespace() == NS_USER_TALK
) {
2100 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2103 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2109 * If user is blocked, return the name of the user who placed the block
2110 * @return string Name of blocker
2112 public function blockedBy() {
2113 $this->getBlockedStatus();
2114 return $this->mBlockedby
;
2118 * If user is blocked, return the specified reason for the block
2119 * @return string Blocking reason
2121 public function blockedFor() {
2122 $this->getBlockedStatus();
2123 return $this->mBlockreason
;
2127 * If user is blocked, return the ID for the block
2128 * @return int Block ID
2130 public function getBlockId() {
2131 $this->getBlockedStatus();
2132 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2136 * Check if user is blocked on all wikis.
2137 * Do not use for actual edit permission checks!
2138 * This is intended for quick UI checks.
2140 * @param string $ip IP address, uses current client if none given
2141 * @return bool True if blocked, false otherwise
2143 public function isBlockedGlobally( $ip = '' ) {
2144 return $this->getGlobalBlock( $ip ) instanceof Block
;
2148 * Check if user is blocked on all wikis.
2149 * Do not use for actual edit permission checks!
2150 * This is intended for quick UI checks.
2152 * @param string $ip IP address, uses current client if none given
2153 * @return Block|null Block object if blocked, null otherwise
2154 * @throws FatalError
2155 * @throws MWException
2157 public function getGlobalBlock( $ip = '' ) {
2158 if ( $this->mGlobalBlock
!== null ) {
2159 return $this->mGlobalBlock ?
: null;
2161 // User is already an IP?
2162 if ( IP
::isIPAddress( $this->getName() ) ) {
2163 $ip = $this->getName();
2165 $ip = $this->getRequest()->getIP();
2167 // Avoid PHP 7.1 warning of passing $this by reference
2171 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2173 if ( $blocked && $block === null ) {
2174 // back-compat: UserIsBlockedGlobally didn't have $block param first
2175 $block = new Block( [
2177 'systemBlock' => 'global-block'
2181 $this->mGlobalBlock
= $blocked ?
$block : false;
2182 return $this->mGlobalBlock ?
: null;
2186 * Check if user account is locked
2188 * @return bool True if locked, false otherwise
2190 public function isLocked() {
2191 if ( $this->mLocked
!== null ) {
2192 return $this->mLocked
;
2194 // Avoid PHP 7.1 warning of passing $this by reference
2196 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2197 $this->mLocked
= $authUser && $authUser->isLocked();
2198 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2199 return $this->mLocked
;
2203 * Check if user account is hidden
2205 * @return bool True if hidden, false otherwise
2207 public function isHidden() {
2208 if ( $this->mHideName
!== null ) {
2209 return $this->mHideName
;
2211 $this->getBlockedStatus();
2212 if ( !$this->mHideName
) {
2213 // Avoid PHP 7.1 warning of passing $this by reference
2215 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2216 $this->mHideName
= $authUser && $authUser->isHidden();
2217 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2219 return $this->mHideName
;
2223 * Get the user's ID.
2224 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2226 public function getId() {
2227 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2228 // Special case, we know the user is anonymous
2230 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2231 // Don't load if this was initialized from an ID
2235 return (int)$this->mId
;
2239 * Set the user and reload all fields according to a given ID
2240 * @param int $v User ID to reload
2242 public function setId( $v ) {
2244 $this->clearInstanceCache( 'id' );
2248 * Get the user name, or the IP of an anonymous user
2249 * @return string User's name or IP address
2251 public function getName() {
2252 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2253 // Special case optimisation
2254 return $this->mName
;
2257 if ( $this->mName
=== false ) {
2259 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2261 return $this->mName
;
2266 * Set the user name.
2268 * This does not reload fields from the database according to the given
2269 * name. Rather, it is used to create a temporary "nonexistent user" for
2270 * later addition to the database. It can also be used to set the IP
2271 * address for an anonymous user to something other than the current
2274 * @note User::newFromName() has roughly the same function, when the named user
2276 * @param string $str New user name to set
2278 public function setName( $str ) {
2280 $this->mName
= $str;
2284 * Get the user's name escaped by underscores.
2285 * @return string Username escaped by underscores.
2287 public function getTitleKey() {
2288 return str_replace( ' ', '_', $this->getName() );
2292 * Check if the user has new messages.
2293 * @return bool True if the user has new messages
2295 public function getNewtalk() {
2298 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2299 if ( $this->mNewtalk
=== -1 ) {
2300 $this->mNewtalk
= false; # reset talk page status
2302 // Check memcached separately for anons, who have no
2303 // entire User object stored in there.
2304 if ( !$this->mId
) {
2305 global $wgDisableAnonTalk;
2306 if ( $wgDisableAnonTalk ) {
2307 // Anon newtalk disabled by configuration.
2308 $this->mNewtalk
= false;
2310 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2313 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2317 return (bool)$this->mNewtalk
;
2321 * Return the data needed to construct links for new talk page message
2322 * alerts. If there are new messages, this will return an associative array
2323 * with the following data:
2324 * wiki: The database name of the wiki
2325 * link: Root-relative link to the user's talk page
2326 * rev: The last talk page revision that the user has seen or null. This
2327 * is useful for building diff links.
2328 * If there are no new messages, it returns an empty array.
2329 * @note This function was designed to accomodate multiple talk pages, but
2330 * currently only returns a single link and revision.
2333 public function getNewMessageLinks() {
2334 // Avoid PHP 7.1 warning of passing $this by reference
2337 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2339 } elseif ( !$this->getNewtalk() ) {
2342 $utp = $this->getTalkPage();
2343 $dbr = wfGetDB( DB_REPLICA
);
2344 // Get the "last viewed rev" timestamp from the oldest message notification
2345 $timestamp = $dbr->selectField( 'user_newtalk',
2346 'MIN(user_last_timestamp)',
2347 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2349 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2350 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2354 * Get the revision ID for the last talk page revision viewed by the talk
2356 * @return int|null Revision ID or null
2358 public function getNewMessageRevisionId() {
2359 $newMessageRevisionId = null;
2360 $newMessageLinks = $this->getNewMessageLinks();
2361 if ( $newMessageLinks ) {
2362 // Note: getNewMessageLinks() never returns more than a single link
2363 // and it is always for the same wiki, but we double-check here in
2364 // case that changes some time in the future.
2365 if ( count( $newMessageLinks ) === 1
2366 && $newMessageLinks[0]['wiki'] === wfWikiID()
2367 && $newMessageLinks[0]['rev']
2369 /** @var Revision $newMessageRevision */
2370 $newMessageRevision = $newMessageLinks[0]['rev'];
2371 $newMessageRevisionId = $newMessageRevision->getId();
2374 return $newMessageRevisionId;
2378 * Internal uncached check for new messages
2381 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2382 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2383 * @return bool True if the user has new messages
2385 protected function checkNewtalk( $field, $id ) {
2386 $dbr = wfGetDB( DB_REPLICA
);
2388 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2390 return $ok !== false;
2394 * Add or update the new messages flag
2395 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2396 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2397 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2398 * @return bool True if successful, false otherwise
2400 protected function updateNewtalk( $field, $id, $curRev = null ) {
2401 // Get timestamp of the talk page revision prior to the current one
2402 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2403 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2404 // Mark the user as having new messages since this revision
2405 $dbw = wfGetDB( DB_MASTER
);
2406 $dbw->insert( 'user_newtalk',
2407 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2410 if ( $dbw->affectedRows() ) {
2411 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2414 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2420 * Clear the new messages flag for the given user
2421 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2422 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2423 * @return bool True if successful, false otherwise
2425 protected function deleteNewtalk( $field, $id ) {
2426 $dbw = wfGetDB( DB_MASTER
);
2427 $dbw->delete( 'user_newtalk',
2430 if ( $dbw->affectedRows() ) {
2431 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2434 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2440 * Update the 'You have new messages!' status.
2441 * @param bool $val Whether the user has new messages
2442 * @param Revision $curRev New, as yet unseen revision of the user talk
2443 * page. Ignored if null or !$val.
2445 public function setNewtalk( $val, $curRev = null ) {
2446 if ( wfReadOnly() ) {
2451 $this->mNewtalk
= $val;
2453 if ( $this->isAnon() ) {
2455 $id = $this->getName();
2458 $id = $this->getId();
2462 $changed = $this->updateNewtalk( $field, $id, $curRev );
2464 $changed = $this->deleteNewtalk( $field, $id );
2468 $this->invalidateCache();
2473 * Generate a current or new-future timestamp to be stored in the
2474 * user_touched field when we update things.
2475 * @return string Timestamp in TS_MW format
2477 private function newTouchedTimestamp() {
2478 global $wgClockSkewFudge;
2480 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2481 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2482 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2489 * Clear user data from memcached
2491 * Use after applying updates to the database; caller's
2492 * responsibility to update user_touched if appropriate.
2494 * Called implicitly from invalidateCache() and saveSettings().
2496 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2498 public function clearSharedCache( $mode = 'changed' ) {
2499 if ( !$this->getId() ) {
2503 $cache = ObjectCache
::getMainWANInstance();
2504 $key = $this->getCacheKey( $cache );
2505 if ( $mode === 'refresh' ) {
2506 $cache->delete( $key, 1 );
2508 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2509 function() use ( $cache, $key ) {
2510 $cache->delete( $key );
2518 * Immediately touch the user data cache for this account
2520 * Calls touch() and removes account data from memcached
2522 public function invalidateCache() {
2524 $this->clearSharedCache();
2528 * Update the "touched" timestamp for the user
2530 * This is useful on various login/logout events when making sure that
2531 * a browser or proxy that has multiple tenants does not suffer cache
2532 * pollution where the new user sees the old users content. The value
2533 * of getTouched() is checked when determining 304 vs 200 responses.
2534 * Unlike invalidateCache(), this preserves the User object cache and
2535 * avoids database writes.
2539 public function touch() {
2540 $id = $this->getId();
2542 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2543 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2544 $cache->touchCheckKey( $key );
2545 $this->mQuickTouched
= null;
2550 * Validate the cache for this account.
2551 * @param string $timestamp A timestamp in TS_MW format
2554 public function validateCache( $timestamp ) {
2555 return ( $timestamp >= $this->getTouched() );
2559 * Get the user touched timestamp
2561 * Use this value only to validate caches via inequalities
2562 * such as in the case of HTTP If-Modified-Since response logic
2564 * @return string TS_MW Timestamp
2566 public function getTouched() {
2570 if ( $this->mQuickTouched
=== null ) {
2571 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2572 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2574 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2577 return max( $this->mTouched
, $this->mQuickTouched
);
2580 return $this->mTouched
;
2584 * Get the user_touched timestamp field (time of last DB updates)
2585 * @return string TS_MW Timestamp
2588 public function getDBTouched() {
2591 return $this->mTouched
;
2595 * Set the password and reset the random token.
2596 * Calls through to authentication plugin if necessary;
2597 * will have no effect if the auth plugin refuses to
2598 * pass the change through or if the legal password
2601 * As a special case, setting the password to null
2602 * wipes it, so the account cannot be logged in until
2603 * a new password is set, for instance via e-mail.
2605 * @deprecated since 1.27, use AuthManager instead
2606 * @param string $str New password to set
2607 * @throws PasswordError On failure
2610 public function setPassword( $str ) {
2611 return $this->setPasswordInternal( $str );
2615 * Set the password and reset the random token unconditionally.
2617 * @deprecated since 1.27, use AuthManager instead
2618 * @param string|null $str New password to set or null to set an invalid
2619 * password hash meaning that the user will not be able to log in
2620 * through the web interface.
2622 public function setInternalPassword( $str ) {
2623 $this->setPasswordInternal( $str );
2627 * Actually set the password and such
2628 * @since 1.27 cannot set a password for a user not in the database
2629 * @param string|null $str New password to set or null to set an invalid
2630 * password hash meaning that the user will not be able to log in
2631 * through the web interface.
2632 * @return bool Success
2634 private function setPasswordInternal( $str ) {
2635 $manager = AuthManager
::singleton();
2637 // If the user doesn't exist yet, fail
2638 if ( !$manager->userExists( $this->getName() ) ) {
2639 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2642 $status = $this->changeAuthenticationData( [
2643 'username' => $this->getName(),
2647 if ( !$status->isGood() ) {
2648 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2649 ->info( __METHOD__
. ': Password change rejected: '
2650 . $status->getWikiText( null, null, 'en' ) );
2654 $this->setOption( 'watchlisttoken', false );
2655 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2661 * Changes credentials of the user.
2663 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2664 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2665 * e.g. when no provider handled the change.
2667 * @param array $data A set of authentication data in fieldname => value format. This is the
2668 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2672 public function changeAuthenticationData( array $data ) {
2673 $manager = AuthManager
::singleton();
2674 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2675 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2677 $status = Status
::newGood( 'ignored' );
2678 foreach ( $reqs as $req ) {
2679 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2681 if ( $status->getValue() === 'ignored' ) {
2682 $status->warning( 'authenticationdatachange-ignored' );
2685 if ( $status->isGood() ) {
2686 foreach ( $reqs as $req ) {
2687 $manager->changeAuthenticationData( $req );
2694 * Get the user's current token.
2695 * @param bool $forceCreation Force the generation of a new token if the
2696 * user doesn't have one (default=true for backwards compatibility).
2697 * @return string|null Token
2699 public function getToken( $forceCreation = true ) {
2700 global $wgAuthenticationTokenVersion;
2703 if ( !$this->mToken
&& $forceCreation ) {
2707 if ( !$this->mToken
) {
2708 // The user doesn't have a token, return null to indicate that.
2710 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2711 // We return a random value here so existing token checks are very
2713 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2714 } elseif ( $wgAuthenticationTokenVersion === null ) {
2715 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2716 return $this->mToken
;
2718 // $wgAuthenticationTokenVersion in use, so hmac it.
2719 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2721 // The raw hash can be overly long. Shorten it up.
2722 $len = max( 32, self
::TOKEN_LENGTH
);
2723 if ( strlen( $ret ) < $len ) {
2724 // Should never happen, even md5 is 128 bits
2725 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2727 return substr( $ret, -$len );
2732 * Set the random token (used for persistent authentication)
2733 * Called from loadDefaults() among other places.
2735 * @param string|bool $token If specified, set the token to this value
2737 public function setToken( $token = false ) {
2739 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2740 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2741 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2742 } elseif ( !$token ) {
2743 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2745 $this->mToken
= $token;
2750 * Set the password for a password reminder or new account email
2752 * @deprecated Removed in 1.27. Use PasswordReset instead.
2753 * @param string $str New password to set or null to set an invalid
2754 * password hash meaning that the user will not be able to use it
2755 * @param bool $throttle If true, reset the throttle timestamp to the present
2757 public function setNewpassword( $str, $throttle = true ) {
2758 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2762 * Get the user's e-mail address
2763 * @return string User's email address
2765 public function getEmail() {
2767 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2768 return $this->mEmail
;
2772 * Get the timestamp of the user's e-mail authentication
2773 * @return string TS_MW timestamp
2775 public function getEmailAuthenticationTimestamp() {
2777 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2778 return $this->mEmailAuthenticated
;
2782 * Set the user's e-mail address
2783 * @param string $str New e-mail address
2785 public function setEmail( $str ) {
2787 if ( $str == $this->mEmail
) {
2790 $this->invalidateEmail();
2791 $this->mEmail
= $str;
2792 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2796 * Set the user's e-mail address and a confirmation mail if needed.
2799 * @param string $str New e-mail address
2802 public function setEmailWithConfirmation( $str ) {
2803 global $wgEnableEmail, $wgEmailAuthentication;
2805 if ( !$wgEnableEmail ) {
2806 return Status
::newFatal( 'emaildisabled' );
2809 $oldaddr = $this->getEmail();
2810 if ( $str === $oldaddr ) {
2811 return Status
::newGood( true );
2814 $type = $oldaddr != '' ?
'changed' : 'set';
2815 $notificationResult = null;
2817 if ( $wgEmailAuthentication ) {
2818 // Send the user an email notifying the user of the change in registered
2819 // email address on their previous email address
2820 if ( $type == 'changed' ) {
2821 $change = $str != '' ?
'changed' : 'removed';
2822 $notificationResult = $this->sendMail(
2823 wfMessage( 'notificationemail_subject_' . $change )->text(),
2824 wfMessage( 'notificationemail_body_' . $change,
2825 $this->getRequest()->getIP(),
2832 $this->setEmail( $str );
2834 if ( $str !== '' && $wgEmailAuthentication ) {
2835 // Send a confirmation request to the new address if needed
2836 $result = $this->sendConfirmationMail( $type );
2838 if ( $notificationResult !== null ) {
2839 $result->merge( $notificationResult );
2842 if ( $result->isGood() ) {
2843 // Say to the caller that a confirmation and notification mail has been sent
2844 $result->value
= 'eauth';
2847 $result = Status
::newGood( true );
2854 * Get the user's real name
2855 * @return string User's real name
2857 public function getRealName() {
2858 if ( !$this->isItemLoaded( 'realname' ) ) {
2862 return $this->mRealName
;
2866 * Set the user's real name
2867 * @param string $str New real name
2869 public function setRealName( $str ) {
2871 $this->mRealName
= $str;
2875 * Get the user's current setting for a given option.
2877 * @param string $oname The option to check
2878 * @param string $defaultOverride A default value returned if the option does not exist
2879 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2880 * @return string|null User's current value for the option
2881 * @see getBoolOption()
2882 * @see getIntOption()
2884 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2885 global $wgHiddenPrefs;
2886 $this->loadOptions();
2888 # We want 'disabled' preferences to always behave as the default value for
2889 # users, even if they have set the option explicitly in their settings (ie they
2890 # set it, and then it was disabled removing their ability to change it). But
2891 # we don't want to erase the preferences in the database in case the preference
2892 # is re-enabled again. So don't touch $mOptions, just override the returned value
2893 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2894 return self
::getDefaultOption( $oname );
2897 if ( array_key_exists( $oname, $this->mOptions
) ) {
2898 return $this->mOptions
[$oname];
2900 return $defaultOverride;
2905 * Get all user's options
2907 * @param int $flags Bitwise combination of:
2908 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2909 * to the default value. (Since 1.25)
2912 public function getOptions( $flags = 0 ) {
2913 global $wgHiddenPrefs;
2914 $this->loadOptions();
2915 $options = $this->mOptions
;
2917 # We want 'disabled' preferences to always behave as the default value for
2918 # users, even if they have set the option explicitly in their settings (ie they
2919 # set it, and then it was disabled removing their ability to change it). But
2920 # we don't want to erase the preferences in the database in case the preference
2921 # is re-enabled again. So don't touch $mOptions, just override the returned value
2922 foreach ( $wgHiddenPrefs as $pref ) {
2923 $default = self
::getDefaultOption( $pref );
2924 if ( $default !== null ) {
2925 $options[$pref] = $default;
2929 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2930 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2937 * Get the user's current setting for a given option, as a boolean value.
2939 * @param string $oname The option to check
2940 * @return bool User's current value for the option
2943 public function getBoolOption( $oname ) {
2944 return (bool)$this->getOption( $oname );
2948 * Get the user's current setting for a given option, as an integer value.
2950 * @param string $oname The option to check
2951 * @param int $defaultOverride A default value returned if the option does not exist
2952 * @return int User's current value for the option
2955 public function getIntOption( $oname, $defaultOverride = 0 ) {
2956 $val = $this->getOption( $oname );
2958 $val = $defaultOverride;
2960 return intval( $val );
2964 * Set the given option for a user.
2966 * You need to call saveSettings() to actually write to the database.
2968 * @param string $oname The option to set
2969 * @param mixed $val New value to set
2971 public function setOption( $oname, $val ) {
2972 $this->loadOptions();
2974 // Explicitly NULL values should refer to defaults
2975 if ( is_null( $val ) ) {
2976 $val = self
::getDefaultOption( $oname );
2979 $this->mOptions
[$oname] = $val;
2983 * Get a token stored in the preferences (like the watchlist one),
2984 * resetting it if it's empty (and saving changes).
2986 * @param string $oname The option name to retrieve the token from
2987 * @return string|bool User's current value for the option, or false if this option is disabled.
2988 * @see resetTokenFromOption()
2990 * @deprecated since 1.26 Applications should use the OAuth extension
2992 public function getTokenFromOption( $oname ) {
2993 global $wgHiddenPrefs;
2995 $id = $this->getId();
2996 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3000 $token = $this->getOption( $oname );
3002 // Default to a value based on the user token to avoid space
3003 // wasted on storing tokens for all users. When this option
3004 // is set manually by the user, only then is it stored.
3005 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3012 * Reset a token stored in the preferences (like the watchlist one).
3013 * *Does not* save user's preferences (similarly to setOption()).
3015 * @param string $oname The option name to reset the token in
3016 * @return string|bool New token value, or false if this option is disabled.
3017 * @see getTokenFromOption()
3020 public function resetTokenFromOption( $oname ) {
3021 global $wgHiddenPrefs;
3022 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3026 $token = MWCryptRand
::generateHex( 40 );
3027 $this->setOption( $oname, $token );
3032 * Return a list of the types of user options currently returned by
3033 * User::getOptionKinds().
3035 * Currently, the option kinds are:
3036 * - 'registered' - preferences which are registered in core MediaWiki or
3037 * by extensions using the UserGetDefaultOptions hook.
3038 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3039 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3040 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3041 * be used by user scripts.
3042 * - 'special' - "preferences" that are not accessible via User::getOptions
3043 * or User::setOptions.
3044 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3045 * These are usually legacy options, removed in newer versions.
3047 * The API (and possibly others) use this function to determine the possible
3048 * option types for validation purposes, so make sure to update this when a
3049 * new option kind is added.
3051 * @see User::getOptionKinds
3052 * @return array Option kinds
3054 public static function listOptionKinds() {
3057 'registered-multiselect',
3058 'registered-checkmatrix',
3066 * Return an associative array mapping preferences keys to the kind of a preference they're
3067 * used for. Different kinds are handled differently when setting or reading preferences.
3069 * See User::listOptionKinds for the list of valid option types that can be provided.
3071 * @see User::listOptionKinds
3072 * @param IContextSource $context
3073 * @param array $options Assoc. array with options keys to check as keys.
3074 * Defaults to $this->mOptions.
3075 * @return array The key => kind mapping data
3077 public function getOptionKinds( IContextSource
$context, $options = null ) {
3078 $this->loadOptions();
3079 if ( $options === null ) {
3080 $options = $this->mOptions
;
3083 $prefs = Preferences
::getPreferences( $this, $context );
3086 // Pull out the "special" options, so they don't get converted as
3087 // multiselect or checkmatrix.
3088 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
3089 foreach ( $specialOptions as $name => $value ) {
3090 unset( $prefs[$name] );
3093 // Multiselect and checkmatrix options are stored in the database with
3094 // one key per option, each having a boolean value. Extract those keys.
3095 $multiselectOptions = [];
3096 foreach ( $prefs as $name => $info ) {
3097 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3098 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3099 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3100 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3102 foreach ( $opts as $value ) {
3103 $multiselectOptions["$prefix$value"] = true;
3106 unset( $prefs[$name] );
3109 $checkmatrixOptions = [];
3110 foreach ( $prefs as $name => $info ) {
3111 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3112 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3113 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3114 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3115 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
3117 foreach ( $columns as $column ) {
3118 foreach ( $rows as $row ) {
3119 $checkmatrixOptions["$prefix$column-$row"] = true;
3123 unset( $prefs[$name] );
3127 // $value is ignored
3128 foreach ( $options as $key => $value ) {
3129 if ( isset( $prefs[$key] ) ) {
3130 $mapping[$key] = 'registered';
3131 } elseif ( isset( $multiselectOptions[$key] ) ) {
3132 $mapping[$key] = 'registered-multiselect';
3133 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3134 $mapping[$key] = 'registered-checkmatrix';
3135 } elseif ( isset( $specialOptions[$key] ) ) {
3136 $mapping[$key] = 'special';
3137 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3138 $mapping[$key] = 'userjs';
3140 $mapping[$key] = 'unused';
3148 * Reset certain (or all) options to the site defaults
3150 * The optional parameter determines which kinds of preferences will be reset.
3151 * Supported values are everything that can be reported by getOptionKinds()
3152 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3154 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3155 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3156 * for backwards-compatibility.
3157 * @param IContextSource|null $context Context source used when $resetKinds
3158 * does not contain 'all', passed to getOptionKinds().
3159 * Defaults to RequestContext::getMain() when null.
3161 public function resetOptions(
3162 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3163 IContextSource
$context = null
3166 $defaultOptions = self
::getDefaultOptions();
3168 if ( !is_array( $resetKinds ) ) {
3169 $resetKinds = [ $resetKinds ];
3172 if ( in_array( 'all', $resetKinds ) ) {
3173 $newOptions = $defaultOptions;
3175 if ( $context === null ) {
3176 $context = RequestContext
::getMain();
3179 $optionKinds = $this->getOptionKinds( $context );
3180 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3183 // Use default values for the options that should be deleted, and
3184 // copy old values for the ones that shouldn't.
3185 foreach ( $this->mOptions
as $key => $value ) {
3186 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3187 if ( array_key_exists( $key, $defaultOptions ) ) {
3188 $newOptions[$key] = $defaultOptions[$key];
3191 $newOptions[$key] = $value;
3196 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3198 $this->mOptions
= $newOptions;
3199 $this->mOptionsLoaded
= true;
3203 * Get the user's preferred date format.
3204 * @return string User's preferred date format
3206 public function getDatePreference() {
3207 // Important migration for old data rows
3208 if ( is_null( $this->mDatePreference
) ) {
3210 $value = $this->getOption( 'date' );
3211 $map = $wgLang->getDatePreferenceMigrationMap();
3212 if ( isset( $map[$value] ) ) {
3213 $value = $map[$value];
3215 $this->mDatePreference
= $value;
3217 return $this->mDatePreference
;
3221 * Determine based on the wiki configuration and the user's options,
3222 * whether this user must be over HTTPS no matter what.
3226 public function requiresHTTPS() {
3227 global $wgSecureLogin;
3228 if ( !$wgSecureLogin ) {
3231 $https = $this->getBoolOption( 'prefershttps' );
3232 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3234 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3241 * Get the user preferred stub threshold
3245 public function getStubThreshold() {
3246 global $wgMaxArticleSize; # Maximum article size, in Kb
3247 $threshold = $this->getIntOption( 'stubthreshold' );
3248 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3249 // If they have set an impossible value, disable the preference
3250 // so we can use the parser cache again.
3257 * Get the permissions this user has.
3258 * @return string[] permission names
3260 public function getRights() {
3261 if ( is_null( $this->mRights
) ) {
3262 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3263 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3265 // Deny any rights denied by the user's session, unless this
3266 // endpoint has no sessions.
3267 if ( !defined( 'MW_NO_SESSION' ) ) {
3268 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3269 if ( $allowedRights !== null ) {
3270 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3274 // Force reindexation of rights when a hook has unset one of them
3275 $this->mRights
= array_values( array_unique( $this->mRights
) );
3277 // If block disables login, we should also remove any
3278 // extra rights blocked users might have, in case the
3279 // blocked user has a pre-existing session (T129738).
3280 // This is checked here for cases where people only call
3281 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3282 // to give a better error message in the common case.
3283 $config = RequestContext
::getMain()->getConfig();
3285 $this->isLoggedIn() &&
3286 $config->get( 'BlockDisablesLogin' ) &&
3290 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3293 return $this->mRights
;
3297 * Get the list of explicit group memberships this user has.
3298 * The implicit * and user groups are not included.
3299 * @return array Array of String internal group names
3301 public function getGroups() {
3303 $this->loadGroups();
3304 return array_keys( $this->mGroupMemberships
);
3308 * Get the list of explicit group memberships this user has, stored as
3309 * UserGroupMembership objects. Implicit groups are not included.
3311 * @return array Associative array of (group name as string => UserGroupMembership object)
3314 public function getGroupMemberships() {
3316 $this->loadGroups();
3317 return $this->mGroupMemberships
;
3321 * Get the list of implicit group memberships this user has.
3322 * This includes all explicit groups, plus 'user' if logged in,
3323 * '*' for all accounts, and autopromoted groups
3324 * @param bool $recache Whether to avoid the cache
3325 * @return array Array of String internal group names
3327 public function getEffectiveGroups( $recache = false ) {
3328 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3329 $this->mEffectiveGroups
= array_unique( array_merge(
3330 $this->getGroups(), // explicit groups
3331 $this->getAutomaticGroups( $recache ) // implicit groups
3333 // Avoid PHP 7.1 warning of passing $this by reference
3335 // Hook for additional groups
3336 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3337 // Force reindexation of groups when a hook has unset one of them
3338 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3340 return $this->mEffectiveGroups
;
3344 * Get the list of implicit group memberships this user has.
3345 * This includes 'user' if logged in, '*' for all accounts,
3346 * and autopromoted groups
3347 * @param bool $recache Whether to avoid the cache
3348 * @return array Array of String internal group names
3350 public function getAutomaticGroups( $recache = false ) {
3351 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3352 $this->mImplicitGroups
= [ '*' ];
3353 if ( $this->getId() ) {
3354 $this->mImplicitGroups
[] = 'user';
3356 $this->mImplicitGroups
= array_unique( array_merge(
3357 $this->mImplicitGroups
,
3358 Autopromote
::getAutopromoteGroups( $this )
3362 // Assure data consistency with rights/groups,
3363 // as getEffectiveGroups() depends on this function
3364 $this->mEffectiveGroups
= null;
3367 return $this->mImplicitGroups
;
3371 * Returns the groups the user has belonged to.
3373 * The user may still belong to the returned groups. Compare with getGroups().
3375 * The function will not return groups the user had belonged to before MW 1.17
3377 * @return array Names of the groups the user has belonged to.
3379 public function getFormerGroups() {
3382 if ( is_null( $this->mFormerGroups
) ) {
3383 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3384 ?
wfGetDB( DB_MASTER
)
3385 : wfGetDB( DB_REPLICA
);
3386 $res = $db->select( 'user_former_groups',
3388 [ 'ufg_user' => $this->mId
],
3390 $this->mFormerGroups
= [];
3391 foreach ( $res as $row ) {
3392 $this->mFormerGroups
[] = $row->ufg_group
;
3396 return $this->mFormerGroups
;
3400 * Get the user's edit count.
3401 * @return int|null Null for anonymous users
3403 public function getEditCount() {
3404 if ( !$this->getId() ) {
3408 if ( $this->mEditCount
=== null ) {
3409 /* Populate the count, if it has not been populated yet */
3410 $dbr = wfGetDB( DB_REPLICA
);
3411 // check if the user_editcount field has been initialized
3412 $count = $dbr->selectField(
3413 'user', 'user_editcount',
3414 [ 'user_id' => $this->mId
],
3418 if ( $count === null ) {
3419 // it has not been initialized. do so.
3420 $count = $this->initEditCount();
3422 $this->mEditCount
= $count;
3424 return (int)$this->mEditCount
;
3428 * Add the user to the given group. This takes immediate effect.
3429 * If the user is already in the group, the expiry time will be updated to the new
3430 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3433 * @param string $group Name of the group to add
3434 * @param string $expiry Optional expiry timestamp in any format acceptable to
3435 * wfTimestamp(), or null if the group assignment should not expire
3438 public function addGroup( $group, $expiry = null ) {
3440 $this->loadGroups();
3443 $expiry = wfTimestamp( TS_MW
, $expiry );
3446 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3450 // create the new UserGroupMembership and put it in the DB
3451 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3452 if ( !$ugm->insert( true ) ) {
3456 $this->mGroupMemberships
[$group] = $ugm;
3458 // Refresh the groups caches, and clear the rights cache so it will be
3459 // refreshed on the next call to $this->getRights().
3460 $this->getEffectiveGroups( true );
3461 $this->mRights
= null;
3463 $this->invalidateCache();
3469 * Remove the user from the given group.
3470 * This takes immediate effect.
3471 * @param string $group Name of the group to remove
3474 public function removeGroup( $group ) {
3477 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3481 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3482 // delete the membership entry
3483 if ( !$ugm ||
!$ugm->delete() ) {
3487 $this->loadGroups();
3488 unset( $this->mGroupMemberships
[$group] );
3490 // Refresh the groups caches, and clear the rights cache so it will be
3491 // refreshed on the next call to $this->getRights().
3492 $this->getEffectiveGroups( true );
3493 $this->mRights
= null;
3495 $this->invalidateCache();
3501 * Get whether the user is logged in
3504 public function isLoggedIn() {
3505 return $this->getId() != 0;
3509 * Get whether the user is anonymous
3512 public function isAnon() {
3513 return !$this->isLoggedIn();
3517 * @return bool Whether this user is flagged as being a bot role account
3520 public function isBot() {
3521 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3526 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3532 * Check if user is allowed to access a feature / make an action
3534 * @param string ... Permissions to test
3535 * @return bool True if user is allowed to perform *any* of the given actions
3537 public function isAllowedAny() {
3538 $permissions = func_get_args();
3539 foreach ( $permissions as $permission ) {
3540 if ( $this->isAllowed( $permission ) ) {
3549 * @param string ... Permissions to test
3550 * @return bool True if the user is allowed to perform *all* of the given actions
3552 public function isAllowedAll() {
3553 $permissions = func_get_args();
3554 foreach ( $permissions as $permission ) {
3555 if ( !$this->isAllowed( $permission ) ) {
3563 * Internal mechanics of testing a permission
3564 * @param string $action
3567 public function isAllowed( $action = '' ) {
3568 if ( $action === '' ) {
3569 return true; // In the spirit of DWIM
3571 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3572 // by misconfiguration: 0 == 'foo'
3573 return in_array( $action, $this->getRights(), true );
3577 * Check whether to enable recent changes patrol features for this user
3578 * @return bool True or false
3580 public function useRCPatrol() {
3581 global $wgUseRCPatrol;
3582 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3586 * Check whether to enable new pages patrol features for this user
3587 * @return bool True or false
3589 public function useNPPatrol() {
3590 global $wgUseRCPatrol, $wgUseNPPatrol;
3592 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3593 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3598 * Check whether to enable new files patrol features for this user
3599 * @return bool True or false
3601 public function useFilePatrol() {
3602 global $wgUseRCPatrol, $wgUseFilePatrol;
3604 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3605 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3610 * Get the WebRequest object to use with this object
3612 * @return WebRequest
3614 public function getRequest() {
3615 if ( $this->mRequest
) {
3616 return $this->mRequest
;
3624 * Check the watched status of an article.
3625 * @since 1.22 $checkRights parameter added
3626 * @param Title $title Title of the article to look at
3627 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3628 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3631 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3632 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3633 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3640 * @since 1.22 $checkRights parameter added
3641 * @param Title $title Title of the article to look at
3642 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3643 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3645 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3646 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3647 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3649 [ $title->getSubjectPage(), $title->getTalkPage() ]
3652 $this->invalidateCache();
3656 * Stop watching an article.
3657 * @since 1.22 $checkRights parameter added
3658 * @param Title $title Title of the article to look at
3659 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3660 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3662 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3663 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3664 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3665 $store->removeWatch( $this, $title->getSubjectPage() );
3666 $store->removeWatch( $this, $title->getTalkPage() );
3668 $this->invalidateCache();
3672 * Clear the user's notification timestamp for the given title.
3673 * If e-notif e-mails are on, they will receive notification mails on
3674 * the next change of the page if it's watched etc.
3675 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3676 * @param Title $title Title of the article to look at
3677 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3679 public function clearNotification( &$title, $oldid = 0 ) {
3680 global $wgUseEnotif, $wgShowUpdatedMarker;
3682 // Do nothing if the database is locked to writes
3683 if ( wfReadOnly() ) {
3687 // Do nothing if not allowed to edit the watchlist
3688 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3692 // If we're working on user's talk page, we should update the talk page message indicator
3693 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3694 // Avoid PHP 7.1 warning of passing $this by reference
3696 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3700 // Try to update the DB post-send and only if needed...
3701 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3702 if ( !$this->getNewtalk() ) {
3703 return; // no notifications to clear
3706 // Delete the last notifications (they stack up)
3707 $this->setNewtalk( false );
3709 // If there is a new, unseen, revision, use its timestamp
3711 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3714 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3719 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3723 if ( $this->isAnon() ) {
3724 // Nothing else to do...
3728 // Only update the timestamp if the page is being watched.
3729 // The query to find out if it is watched is cached both in memcached and per-invocation,
3730 // and when it does have to be executed, it can be on a replica DB
3731 // If this is the user's newtalk page, we always update the timestamp
3733 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3737 MediaWikiServices
::getInstance()->getWatchedItemStore()
3738 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3742 * Resets all of the given user's page-change notification timestamps.
3743 * If e-notif e-mails are on, they will receive notification mails on
3744 * the next change of any watched page.
3745 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3747 public function clearAllNotifications() {
3748 global $wgUseEnotif, $wgShowUpdatedMarker;
3749 // Do nothing if not allowed to edit the watchlist
3750 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3754 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3755 $this->setNewtalk( false );
3759 $id = $this->getId();
3764 $dbw = wfGetDB( DB_MASTER
);
3765 $asOfTimes = array_unique( $dbw->selectFieldValues(
3767 'wl_notificationtimestamp',
3768 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3770 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3772 if ( !$asOfTimes ) {
3775 // Immediately update the most recent touched rows, which hopefully covers what
3776 // the user sees on the watchlist page before pressing "mark all pages visited"....
3779 [ 'wl_notificationtimestamp' => null ],
3780 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3783 // ...and finish the older ones in a post-send update with lag checks...
3784 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3787 function () use ( $dbw, $id ) {
3788 global $wgUpdateRowsPerQuery;
3790 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3791 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3792 $asOfTimes = array_unique( $dbw->selectFieldValues(
3794 'wl_notificationtimestamp',
3795 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3798 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3801 [ 'wl_notificationtimestamp' => null ],
3802 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3805 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3809 // We also need to clear here the "you have new message" notification for the own
3810 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3814 * Compute experienced level based on edit count and registration date.
3816 * @return string 'newcomer', 'learner', or 'experienced'
3818 public function getExperienceLevel() {
3819 global $wgLearnerEdits,
3820 $wgExperiencedUserEdits,
3821 $wgLearnerMemberSince,
3822 $wgExperiencedUserMemberSince;
3824 if ( $this->isAnon() ) {
3828 $editCount = $this->getEditCount();
3829 $registration = $this->getRegistration();
3831 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3832 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3835 $editCount < $wgLearnerEdits ||
3836 $registration > $learnerRegistration
3840 $editCount > $wgExperiencedUserEdits &&
3841 $registration <= $experiencedRegistration
3843 return 'experienced';
3850 * Set a cookie on the user's client. Wrapper for
3851 * WebResponse::setCookie
3852 * @deprecated since 1.27
3853 * @param string $name Name of the cookie to set
3854 * @param string $value Value to set
3855 * @param int $exp Expiration time, as a UNIX time value;
3856 * if 0 or not specified, use the default $wgCookieExpiration
3857 * @param bool $secure
3858 * true: Force setting the secure attribute when setting the cookie
3859 * false: Force NOT setting the secure attribute when setting the cookie
3860 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3861 * @param array $params Array of options sent passed to WebResponse::setcookie()
3862 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3865 protected function setCookie(
3866 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3868 wfDeprecated( __METHOD__
, '1.27' );
3869 if ( $request === null ) {
3870 $request = $this->getRequest();
3872 $params['secure'] = $secure;
3873 $request->response()->setCookie( $name, $value, $exp, $params );
3877 * Clear a cookie on the user's client
3878 * @deprecated since 1.27
3879 * @param string $name Name of the cookie to clear
3880 * @param bool $secure
3881 * true: Force setting the secure attribute when setting the cookie
3882 * false: Force NOT setting the secure attribute when setting the cookie
3883 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3884 * @param array $params Array of options sent passed to WebResponse::setcookie()
3886 protected function clearCookie( $name, $secure = null, $params = [] ) {
3887 wfDeprecated( __METHOD__
, '1.27' );
3888 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3892 * Set an extended login cookie on the user's client. The expiry of the cookie
3893 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3896 * @see User::setCookie
3898 * @deprecated since 1.27
3899 * @param string $name Name of the cookie to set
3900 * @param string $value Value to set
3901 * @param bool $secure
3902 * true: Force setting the secure attribute when setting the cookie
3903 * false: Force NOT setting the secure attribute when setting the cookie
3904 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3906 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3907 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3909 wfDeprecated( __METHOD__
, '1.27' );
3912 $exp +
= $wgExtendedLoginCookieExpiration !== null
3913 ?
$wgExtendedLoginCookieExpiration
3914 : $wgCookieExpiration;
3916 $this->setCookie( $name, $value, $exp, $secure );
3920 * Persist this user's session (e.g. set cookies)
3922 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3924 * @param bool $secure Whether to force secure/insecure cookies or use default
3925 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3927 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3929 if ( 0 == $this->mId
) {
3933 $session = $this->getRequest()->getSession();
3934 if ( $request && $session->getRequest() !== $request ) {
3935 $session = $session->sessionWithRequest( $request );
3937 $delay = $session->delaySave();
3939 if ( !$session->getUser()->equals( $this ) ) {
3940 if ( !$session->canSetUser() ) {
3941 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3942 ->warning( __METHOD__
.
3943 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3947 $session->setUser( $this );
3950 $session->setRememberUser( $rememberMe );
3951 if ( $secure !== null ) {
3952 $session->setForceHTTPS( $secure );
3955 $session->persist();
3957 ScopedCallback
::consume( $delay );
3961 * Log this user out.
3963 public function logout() {
3964 // Avoid PHP 7.1 warning of passing $this by reference
3966 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3972 * Clear the user's session, and reset the instance cache.
3975 public function doLogout() {
3976 $session = $this->getRequest()->getSession();
3977 if ( !$session->canSetUser() ) {
3978 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3979 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3980 $error = 'immutable';
3981 } elseif ( !$session->getUser()->equals( $this ) ) {
3982 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3983 ->warning( __METHOD__
.
3984 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3986 // But we still may as well make this user object anon
3987 $this->clearInstanceCache( 'defaults' );
3988 $error = 'wronguser';
3990 $this->clearInstanceCache( 'defaults' );
3991 $delay = $session->delaySave();
3992 $session->unpersist(); // Clear cookies (T127436)
3993 $session->setLoggedOutTimestamp( time() );
3994 $session->setUser( new User
);
3995 $session->set( 'wsUserID', 0 ); // Other code expects this
3996 $session->resetAllTokens();
3997 ScopedCallback
::consume( $delay );
4000 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4001 'event' => 'logout',
4002 'successful' => $error === false,
4003 'status' => $error ?
: 'success',
4008 * Save this user's settings into the database.
4009 * @todo Only rarely do all these fields need to be set!
4011 public function saveSettings() {
4012 if ( wfReadOnly() ) {
4013 // @TODO: caller should deal with this instead!
4014 // This should really just be an exception.
4015 MWExceptionHandler
::logException( new DBExpectedError(
4017 "Could not update user with ID '{$this->mId}'; DB is read-only."
4023 if ( 0 == $this->mId
) {
4027 // Get a new user_touched that is higher than the old one.
4028 // This will be used for a CAS check as a last-resort safety
4029 // check against race conditions and replica DB lag.
4030 $newTouched = $this->newTouchedTimestamp();
4032 $dbw = wfGetDB( DB_MASTER
);
4033 $dbw->update( 'user',
4035 'user_name' => $this->mName
,
4036 'user_real_name' => $this->mRealName
,
4037 'user_email' => $this->mEmail
,
4038 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4039 'user_touched' => $dbw->timestamp( $newTouched ),
4040 'user_token' => strval( $this->mToken
),
4041 'user_email_token' => $this->mEmailToken
,
4042 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4043 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4044 'user_id' => $this->mId
,
4048 if ( !$dbw->affectedRows() ) {
4049 // Maybe the problem was a missed cache update; clear it to be safe
4050 $this->clearSharedCache( 'refresh' );
4051 // User was changed in the meantime or loaded with stale data
4052 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4053 throw new MWException(
4054 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
4055 " the version of the user to be saved is older than the current version."
4059 $this->mTouched
= $newTouched;
4060 $this->saveOptions();
4062 Hooks
::run( 'UserSaveSettings', [ $this ] );
4063 $this->clearSharedCache();
4064 $this->getUserPage()->invalidateCache();
4068 * If only this user's username is known, and it exists, return the user ID.
4070 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4073 public function idForName( $flags = 0 ) {
4074 $s = trim( $this->getName() );
4079 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4080 ?
wfGetDB( DB_MASTER
)
4081 : wfGetDB( DB_REPLICA
);
4083 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4084 ?
[ 'LOCK IN SHARE MODE' ]
4087 $id = $db->selectField( 'user',
4088 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4094 * Add a user to the database, return the user object
4096 * @param string $name Username to add
4097 * @param array $params Array of Strings Non-default parameters to save to
4098 * the database as user_* fields:
4099 * - email: The user's email address.
4100 * - email_authenticated: The email authentication timestamp.
4101 * - real_name: The user's real name.
4102 * - options: An associative array of non-default options.
4103 * - token: Random authentication token. Do not set.
4104 * - registration: Registration timestamp. Do not set.
4106 * @return User|null User object, or null if the username already exists.
4108 public static function createNew( $name, $params = [] ) {
4109 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4110 if ( isset( $params[$field] ) ) {
4111 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4112 unset( $params[$field] );
4118 $user->setToken(); // init token
4119 if ( isset( $params['options'] ) ) {
4120 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4121 unset( $params['options'] );
4123 $dbw = wfGetDB( DB_MASTER
);
4124 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4126 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4129 'user_id' => $seqVal,
4130 'user_name' => $name,
4131 'user_password' => $noPass,
4132 'user_newpassword' => $noPass,
4133 'user_email' => $user->mEmail
,
4134 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4135 'user_real_name' => $user->mRealName
,
4136 'user_token' => strval( $user->mToken
),
4137 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4138 'user_editcount' => 0,
4139 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4141 foreach ( $params as $name => $value ) {
4142 $fields["user_$name"] = $value;
4144 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
4145 if ( $dbw->affectedRows() ) {
4146 $newUser = User
::newFromId( $dbw->insertId() );
4154 * Add this existing user object to the database. If the user already
4155 * exists, a fatal status object is returned, and the user object is
4156 * initialised with the data from the database.
4158 * Previously, this function generated a DB error due to a key conflict
4159 * if the user already existed. Many extension callers use this function
4160 * in code along the lines of:
4162 * $user = User::newFromName( $name );
4163 * if ( !$user->isLoggedIn() ) {
4164 * $user->addToDatabase();
4166 * // do something with $user...
4168 * However, this was vulnerable to a race condition (T18020). By
4169 * initialising the user object if the user exists, we aim to support this
4170 * calling sequence as far as possible.
4172 * Note that if the user exists, this function will acquire a write lock,
4173 * so it is still advisable to make the call conditional on isLoggedIn(),
4174 * and to commit the transaction after calling.
4176 * @throws MWException
4179 public function addToDatabase() {
4181 if ( !$this->mToken
) {
4182 $this->setToken(); // init token
4185 if ( !is_string( $this->mName
) ) {
4186 throw new RuntimeException( "User name field is not set." );
4189 $this->mTouched
= $this->newTouchedTimestamp();
4191 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4193 $dbw = wfGetDB( DB_MASTER
);
4194 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4195 $dbw->insert( 'user',
4197 'user_id' => $seqVal,
4198 'user_name' => $this->mName
,
4199 'user_password' => $noPass,
4200 'user_newpassword' => $noPass,
4201 'user_email' => $this->mEmail
,
4202 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4203 'user_real_name' => $this->mRealName
,
4204 'user_token' => strval( $this->mToken
),
4205 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4206 'user_editcount' => 0,
4207 'user_touched' => $dbw->timestamp( $this->mTouched
),
4211 if ( !$dbw->affectedRows() ) {
4212 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4213 $this->mId
= $dbw->selectField(
4216 [ 'user_name' => $this->mName
],
4218 [ 'LOCK IN SHARE MODE' ]
4222 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4227 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4228 "to insert user '{$this->mName}' row, but it was not present in select!" );
4230 return Status
::newFatal( 'userexists' );
4232 $this->mId
= $dbw->insertId();
4233 self
::$idCacheByName[$this->mName
] = $this->mId
;
4235 // Clear instance cache other than user table data, which is already accurate
4236 $this->clearInstanceCache();
4238 $this->saveOptions();
4239 return Status
::newGood();
4243 * If this user is logged-in and blocked,
4244 * block any IP address they've successfully logged in from.
4245 * @return bool A block was spread
4247 public function spreadAnyEditBlock() {
4248 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4249 return $this->spreadBlock();
4256 * If this (non-anonymous) user is blocked,
4257 * block the IP address they've successfully logged in from.
4258 * @return bool A block was spread
4260 protected function spreadBlock() {
4261 wfDebug( __METHOD__
. "()\n" );
4263 if ( $this->mId
== 0 ) {
4267 $userblock = Block
::newFromTarget( $this->getName() );
4268 if ( !$userblock ) {
4272 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4276 * Get whether the user is explicitly blocked from account creation.
4277 * @return bool|Block
4279 public function isBlockedFromCreateAccount() {
4280 $this->getBlockedStatus();
4281 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4282 return $this->mBlock
;
4285 # T15611: if the IP address the user is trying to create an account from is
4286 # blocked with createaccount disabled, prevent new account creation there even
4287 # when the user is logged in
4288 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4289 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4291 return $this->mBlockedFromCreateAccount
instanceof Block
4292 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4293 ?
$this->mBlockedFromCreateAccount
4298 * Get whether the user is blocked from using Special:Emailuser.
4301 public function isBlockedFromEmailuser() {
4302 $this->getBlockedStatus();
4303 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4307 * Get whether the user is allowed to create an account.
4310 public function isAllowedToCreateAccount() {
4311 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4315 * Get this user's personal page title.
4317 * @return Title User's personal page title
4319 public function getUserPage() {
4320 return Title
::makeTitle( NS_USER
, $this->getName() );
4324 * Get this user's talk page title.
4326 * @return Title User's talk page title
4328 public function getTalkPage() {
4329 $title = $this->getUserPage();
4330 return $title->getTalkPage();
4334 * Determine whether the user is a newbie. Newbies are either
4335 * anonymous IPs, or the most recently created accounts.
4338 public function isNewbie() {
4339 return !$this->isAllowed( 'autoconfirmed' );
4343 * Check to see if the given clear-text password is one of the accepted passwords
4344 * @deprecated since 1.27, use AuthManager instead
4345 * @param string $password User password
4346 * @return bool True if the given password is correct, otherwise False
4348 public function checkPassword( $password ) {
4349 $manager = AuthManager
::singleton();
4350 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4351 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4353 'username' => $this->getName(),
4354 'password' => $password,
4357 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4358 switch ( $res->status
) {
4359 case AuthenticationResponse
::PASS
:
4361 case AuthenticationResponse
::FAIL
:
4362 // Hope it's not a PreAuthenticationProvider that failed...
4363 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4364 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4367 throw new BadMethodCallException(
4368 'AuthManager returned a response unsupported by ' . __METHOD__
4374 * Check if the given clear-text password matches the temporary password
4375 * sent by e-mail for password reset operations.
4377 * @deprecated since 1.27, use AuthManager instead
4378 * @param string $plaintext
4379 * @return bool True if matches, false otherwise
4381 public function checkTemporaryPassword( $plaintext ) {
4382 // Can't check the temporary password individually.
4383 return $this->checkPassword( $plaintext );
4387 * Initialize (if necessary) and return a session token value
4388 * which can be used in edit forms to show that the user's
4389 * login credentials aren't being hijacked with a foreign form
4393 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4394 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4395 * @return MediaWiki\Session\Token The new edit token
4397 public function getEditTokenObject( $salt = '', $request = null ) {
4398 if ( $this->isAnon() ) {
4399 return new LoggedOutEditToken();
4403 $request = $this->getRequest();
4405 return $request->getSession()->getToken( $salt );
4409 * Initialize (if necessary) and return a session token value
4410 * which can be used in edit forms to show that the user's
4411 * login credentials aren't being hijacked with a foreign form
4414 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4417 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4418 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4419 * @return string The new edit token
4421 public function getEditToken( $salt = '', $request = null ) {
4422 return $this->getEditTokenObject( $salt, $request )->toString();
4426 * Get the embedded timestamp from a token.
4427 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4428 * @param string $val Input token
4431 public static function getEditTokenTimestamp( $val ) {
4432 wfDeprecated( __METHOD__
, '1.27' );
4433 return MediaWiki\Session\Token
::getTimestamp( $val );
4437 * Check given value against the token value stored in the session.
4438 * A match should confirm that the form was submitted from the
4439 * user's own login session, not a form submission from a third-party
4442 * @param string $val Input value to compare
4443 * @param string $salt Optional function-specific data for hashing
4444 * @param WebRequest|null $request Object to use or null to use $wgRequest
4445 * @param int $maxage Fail tokens older than this, in seconds
4446 * @return bool Whether the token matches
4448 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4449 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4453 * Check given value against the token value stored in the session,
4454 * ignoring the suffix.
4456 * @param string $val Input value to compare
4457 * @param string $salt Optional function-specific data for hashing
4458 * @param WebRequest|null $request Object to use or null to use $wgRequest
4459 * @param int $maxage Fail tokens older than this, in seconds
4460 * @return bool Whether the token matches
4462 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4463 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4464 return $this->matchEditToken( $val, $salt, $request, $maxage );
4468 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4469 * mail to the user's given address.
4471 * @param string $type Message to send, either "created", "changed" or "set"
4474 public function sendConfirmationMail( $type = 'created' ) {
4476 $expiration = null; // gets passed-by-ref and defined in next line.
4477 $token = $this->confirmationToken( $expiration );
4478 $url = $this->confirmationTokenUrl( $token );
4479 $invalidateURL = $this->invalidationTokenUrl( $token );
4480 $this->saveSettings();
4482 if ( $type == 'created' ||
$type === false ) {
4483 $message = 'confirmemail_body';
4484 } elseif ( $type === true ) {
4485 $message = 'confirmemail_body_changed';
4487 // Messages: confirmemail_body_changed, confirmemail_body_set
4488 $message = 'confirmemail_body_' . $type;
4491 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4492 wfMessage( $message,
4493 $this->getRequest()->getIP(),
4496 $wgLang->userTimeAndDate( $expiration, $this ),
4498 $wgLang->userDate( $expiration, $this ),
4499 $wgLang->userTime( $expiration, $this ) )->text() );
4503 * Send an e-mail to this user's account. Does not check for
4504 * confirmed status or validity.
4506 * @param string $subject Message subject
4507 * @param string $body Message body
4508 * @param User|null $from Optional sending user; if unspecified, default
4509 * $wgPasswordSender will be used.
4510 * @param string $replyto Reply-To address
4513 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4514 global $wgPasswordSender;
4516 if ( $from instanceof User
) {
4517 $sender = MailAddress
::newFromUser( $from );
4519 $sender = new MailAddress( $wgPasswordSender,
4520 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4522 $to = MailAddress
::newFromUser( $this );
4524 return UserMailer
::send( $to, $sender, $subject, $body, [
4525 'replyTo' => $replyto,
4530 * Generate, store, and return a new e-mail confirmation code.
4531 * A hash (unsalted, since it's used as a key) is stored.
4533 * @note Call saveSettings() after calling this function to commit
4534 * this change to the database.
4536 * @param string &$expiration Accepts the expiration time
4537 * @return string New token
4539 protected function confirmationToken( &$expiration ) {
4540 global $wgUserEmailConfirmationTokenExpiry;
4542 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4543 $expiration = wfTimestamp( TS_MW
, $expires );
4545 $token = MWCryptRand
::generateHex( 32 );
4546 $hash = md5( $token );
4547 $this->mEmailToken
= $hash;
4548 $this->mEmailTokenExpires
= $expiration;
4553 * Return a URL the user can use to confirm their email address.
4554 * @param string $token Accepts the email confirmation token
4555 * @return string New token URL
4557 protected function confirmationTokenUrl( $token ) {
4558 return $this->getTokenUrl( 'ConfirmEmail', $token );
4562 * Return a URL the user can use to invalidate their email address.
4563 * @param string $token Accepts the email confirmation token
4564 * @return string New token URL
4566 protected function invalidationTokenUrl( $token ) {
4567 return $this->getTokenUrl( 'InvalidateEmail', $token );
4571 * Internal function to format the e-mail validation/invalidation URLs.
4572 * This uses a quickie hack to use the
4573 * hardcoded English names of the Special: pages, for ASCII safety.
4575 * @note Since these URLs get dropped directly into emails, using the
4576 * short English names avoids insanely long URL-encoded links, which
4577 * also sometimes can get corrupted in some browsers/mailers
4578 * (T8957 with Gmail and Internet Explorer).
4580 * @param string $page Special page
4581 * @param string $token Token
4582 * @return string Formatted URL
4584 protected function getTokenUrl( $page, $token ) {
4585 // Hack to bypass localization of 'Special:'
4586 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4587 return $title->getCanonicalURL();
4591 * Mark the e-mail address confirmed.
4593 * @note Call saveSettings() after calling this function to commit the change.
4597 public function confirmEmail() {
4598 // Check if it's already confirmed, so we don't touch the database
4599 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4600 if ( !$this->isEmailConfirmed() ) {
4601 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4602 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4608 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4609 * address if it was already confirmed.
4611 * @note Call saveSettings() after calling this function to commit the change.
4612 * @return bool Returns true
4614 public function invalidateEmail() {
4616 $this->mEmailToken
= null;
4617 $this->mEmailTokenExpires
= null;
4618 $this->setEmailAuthenticationTimestamp( null );
4620 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4625 * Set the e-mail authentication timestamp.
4626 * @param string $timestamp TS_MW timestamp
4628 public function setEmailAuthenticationTimestamp( $timestamp ) {
4630 $this->mEmailAuthenticated
= $timestamp;
4631 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4635 * Is this user allowed to send e-mails within limits of current
4636 * site configuration?
4639 public function canSendEmail() {
4640 global $wgEnableEmail, $wgEnableUserEmail;
4641 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4644 $canSend = $this->isEmailConfirmed();
4645 // Avoid PHP 7.1 warning of passing $this by reference
4647 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4652 * Is this user allowed to receive e-mails within limits of current
4653 * site configuration?
4656 public function canReceiveEmail() {
4657 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4661 * Is this user's e-mail address valid-looking and confirmed within
4662 * limits of the current site configuration?
4664 * @note If $wgEmailAuthentication is on, this may require the user to have
4665 * confirmed their address by returning a code or using a password
4666 * sent to the address from the wiki.
4670 public function isEmailConfirmed() {
4671 global $wgEmailAuthentication;
4673 // Avoid PHP 7.1 warning of passing $this by reference
4676 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4677 if ( $this->isAnon() ) {
4680 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4683 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4693 * Check whether there is an outstanding request for e-mail confirmation.
4696 public function isEmailConfirmationPending() {
4697 global $wgEmailAuthentication;
4698 return $wgEmailAuthentication &&
4699 !$this->isEmailConfirmed() &&
4700 $this->mEmailToken
&&
4701 $this->mEmailTokenExpires
> wfTimestamp();
4705 * Get the timestamp of account creation.
4707 * @return string|bool|null Timestamp of account creation, false for
4708 * non-existent/anonymous user accounts, or null if existing account
4709 * but information is not in database.
4711 public function getRegistration() {
4712 if ( $this->isAnon() ) {
4716 return $this->mRegistration
;
4720 * Get the timestamp of the first edit
4722 * @return string|bool Timestamp of first edit, or false for
4723 * non-existent/anonymous user accounts.
4725 public function getFirstEditTimestamp() {
4726 if ( $this->getId() == 0 ) {
4727 return false; // anons
4729 $dbr = wfGetDB( DB_REPLICA
);
4730 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4731 [ 'rev_user' => $this->getId() ],
4733 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4736 return false; // no edits
4738 return wfTimestamp( TS_MW
, $time );
4742 * Get the permissions associated with a given list of groups
4744 * @param array $groups Array of Strings List of internal group names
4745 * @return array Array of Strings List of permission key names for given groups combined
4747 public static function getGroupPermissions( $groups ) {
4748 global $wgGroupPermissions, $wgRevokePermissions;
4750 // grant every granted permission first
4751 foreach ( $groups as $group ) {
4752 if ( isset( $wgGroupPermissions[$group] ) ) {
4753 $rights = array_merge( $rights,
4754 // array_filter removes empty items
4755 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4758 // now revoke the revoked permissions
4759 foreach ( $groups as $group ) {
4760 if ( isset( $wgRevokePermissions[$group] ) ) {
4761 $rights = array_diff( $rights,
4762 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4765 return array_unique( $rights );
4769 * Get all the groups who have a given permission
4771 * @param string $role Role to check
4772 * @return array Array of Strings List of internal group names with the given permission
4774 public static function getGroupsWithPermission( $role ) {
4775 global $wgGroupPermissions;
4776 $allowedGroups = [];
4777 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4778 if ( self
::groupHasPermission( $group, $role ) ) {
4779 $allowedGroups[] = $group;
4782 return $allowedGroups;
4786 * Check, if the given group has the given permission
4788 * If you're wanting to check whether all users have a permission, use
4789 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4793 * @param string $group Group to check
4794 * @param string $role Role to check
4797 public static function groupHasPermission( $group, $role ) {
4798 global $wgGroupPermissions, $wgRevokePermissions;
4799 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4800 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4804 * Check if all users may be assumed to have the given permission
4806 * We generally assume so if the right is granted to '*' and isn't revoked
4807 * on any group. It doesn't attempt to take grants or other extension
4808 * limitations on rights into account in the general case, though, as that
4809 * would require it to always return false and defeat the purpose.
4810 * Specifically, session-based rights restrictions (such as OAuth or bot
4811 * passwords) are applied based on the current session.
4814 * @param string $right Right to check
4817 public static function isEveryoneAllowed( $right ) {
4818 global $wgGroupPermissions, $wgRevokePermissions;
4821 // Use the cached results, except in unit tests which rely on
4822 // being able change the permission mid-request
4823 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4824 return $cache[$right];
4827 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4828 $cache[$right] = false;
4832 // If it's revoked anywhere, then everyone doesn't have it
4833 foreach ( $wgRevokePermissions as $rights ) {
4834 if ( isset( $rights[$right] ) && $rights[$right] ) {
4835 $cache[$right] = false;
4840 // Remove any rights that aren't allowed to the global-session user,
4841 // unless there are no sessions for this endpoint.
4842 if ( !defined( 'MW_NO_SESSION' ) ) {
4843 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4844 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4845 $cache[$right] = false;
4850 // Allow extensions to say false
4851 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4852 $cache[$right] = false;
4856 $cache[$right] = true;
4861 * Get the localized descriptive name for a group, if it exists
4862 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
4864 * @param string $group Internal group name
4865 * @return string Localized descriptive group name
4867 public static function getGroupName( $group ) {
4868 wfDeprecated( __METHOD__
, '1.29' );
4869 return UserGroupMembership
::getGroupName( $group );
4873 * Get the localized descriptive name for a member of a group, if it exists
4874 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
4876 * @param string $group Internal group name
4877 * @param string $username Username for gender (since 1.19)
4878 * @return string Localized name for group member
4880 public static function getGroupMember( $group, $username = '#' ) {
4881 wfDeprecated( __METHOD__
, '1.29' );
4882 return UserGroupMembership
::getGroupMemberName( $group, $username );
4886 * Return the set of defined explicit groups.
4887 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4888 * are not included, as they are defined automatically, not in the database.
4889 * @return array Array of internal group names
4891 public static function getAllGroups() {
4892 global $wgGroupPermissions, $wgRevokePermissions;
4894 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4895 self
::getImplicitGroups()
4900 * Get a list of all available permissions.
4901 * @return string[] Array of permission names
4903 public static function getAllRights() {
4904 if ( self
::$mAllRights === false ) {
4905 global $wgAvailableRights;
4906 if ( count( $wgAvailableRights ) ) {
4907 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4909 self
::$mAllRights = self
::$mCoreRights;
4911 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4913 return self
::$mAllRights;
4917 * Get a list of implicit groups
4918 * @return array Array of Strings Array of internal group names
4920 public static function getImplicitGroups() {
4921 global $wgImplicitGroups;
4923 $groups = $wgImplicitGroups;
4924 # Deprecated, use $wgImplicitGroups instead
4925 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4931 * Get the title of a page describing a particular group
4932 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
4934 * @param string $group Internal group name
4935 * @return Title|bool Title of the page if it exists, false otherwise
4937 public static function getGroupPage( $group ) {
4938 wfDeprecated( __METHOD__
, '1.29' );
4939 return UserGroupMembership
::getGroupPage( $group );
4943 * Create a link to the group in HTML, if available;
4944 * else return the group name.
4945 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4946 * make the link yourself if you need custom text
4948 * @param string $group Internal name of the group
4949 * @param string $text The text of the link
4950 * @return string HTML link to the group
4952 public static function makeGroupLinkHTML( $group, $text = '' ) {
4953 wfDeprecated( __METHOD__
, '1.29' );
4955 if ( $text == '' ) {
4956 $text = UserGroupMembership
::getGroupName( $group );
4958 $title = UserGroupMembership
::getGroupPage( $group );
4960 return Linker
::link( $title, htmlspecialchars( $text ) );
4962 return htmlspecialchars( $text );
4967 * Create a link to the group in Wikitext, if available;
4968 * else return the group name.
4969 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
4970 * make the link yourself if you need custom text
4972 * @param string $group Internal name of the group
4973 * @param string $text The text of the link
4974 * @return string Wikilink to the group
4976 public static function makeGroupLinkWiki( $group, $text = '' ) {
4977 wfDeprecated( __METHOD__
, '1.29' );
4979 if ( $text == '' ) {
4980 $text = UserGroupMembership
::getGroupName( $group );
4982 $title = UserGroupMembership
::getGroupPage( $group );
4984 $page = $title->getFullText();
4985 return "[[$page|$text]]";
4992 * Returns an array of the groups that a particular group can add/remove.
4994 * @param string $group The group to check for whether it can add/remove
4995 * @return array Array( 'add' => array( addablegroups ),
4996 * 'remove' => array( removablegroups ),
4997 * 'add-self' => array( addablegroups to self),
4998 * 'remove-self' => array( removable groups from self) )
5000 public static function changeableByGroup( $group ) {
5001 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5010 if ( empty( $wgAddGroups[$group] ) ) {
5011 // Don't add anything to $groups
5012 } elseif ( $wgAddGroups[$group] === true ) {
5013 // You get everything
5014 $groups['add'] = self
::getAllGroups();
5015 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5016 $groups['add'] = $wgAddGroups[$group];
5019 // Same thing for remove
5020 if ( empty( $wgRemoveGroups[$group] ) ) {
5022 } elseif ( $wgRemoveGroups[$group] === true ) {
5023 $groups['remove'] = self
::getAllGroups();
5024 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5025 $groups['remove'] = $wgRemoveGroups[$group];
5028 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5029 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5030 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5031 if ( is_int( $key ) ) {
5032 $wgGroupsAddToSelf['user'][] = $value;
5037 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5038 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5039 if ( is_int( $key ) ) {
5040 $wgGroupsRemoveFromSelf['user'][] = $value;
5045 // Now figure out what groups the user can add to him/herself
5046 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5048 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5049 // No idea WHY this would be used, but it's there
5050 $groups['add-self'] = User
::getAllGroups();
5051 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5052 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5055 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5057 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5058 $groups['remove-self'] = User
::getAllGroups();
5059 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5060 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5067 * Returns an array of groups that this user can add and remove
5068 * @return array Array( 'add' => array( addablegroups ),
5069 * 'remove' => array( removablegroups ),
5070 * 'add-self' => array( addablegroups to self),
5071 * 'remove-self' => array( removable groups from self) )
5073 public function changeableGroups() {
5074 if ( $this->isAllowed( 'userrights' ) ) {
5075 // This group gives the right to modify everything (reverse-
5076 // compatibility with old "userrights lets you change
5078 // Using array_merge to make the groups reindexed
5079 $all = array_merge( User
::getAllGroups() );
5088 // Okay, it's not so simple, we will have to go through the arrays
5095 $addergroups = $this->getEffectiveGroups();
5097 foreach ( $addergroups as $addergroup ) {
5098 $groups = array_merge_recursive(
5099 $groups, $this->changeableByGroup( $addergroup )
5101 $groups['add'] = array_unique( $groups['add'] );
5102 $groups['remove'] = array_unique( $groups['remove'] );
5103 $groups['add-self'] = array_unique( $groups['add-self'] );
5104 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5110 * Deferred version of incEditCountImmediate()
5112 * This function, rather than incEditCountImmediate(), should be used for
5113 * most cases as it avoids potential deadlocks caused by concurrent editing.
5115 public function incEditCount() {
5116 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5118 $this->incEditCountImmediate();
5125 * Increment the user's edit-count field.
5126 * Will have no effect for anonymous users.
5129 public function incEditCountImmediate() {
5130 if ( $this->isAnon() ) {
5134 $dbw = wfGetDB( DB_MASTER
);
5135 // No rows will be "affected" if user_editcount is NULL
5138 [ 'user_editcount=user_editcount+1' ],
5139 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5142 // Lazy initialization check...
5143 if ( $dbw->affectedRows() == 0 ) {
5144 // Now here's a goddamn hack...
5145 $dbr = wfGetDB( DB_REPLICA
);
5146 if ( $dbr !== $dbw ) {
5147 // If we actually have a replica DB server, the count is
5148 // at least one behind because the current transaction
5149 // has not been committed and replicated.
5150 $this->mEditCount
= $this->initEditCount( 1 );
5152 // But if DB_REPLICA is selecting the master, then the
5153 // count we just read includes the revision that was
5154 // just added in the working transaction.
5155 $this->mEditCount
= $this->initEditCount();
5158 if ( $this->mEditCount
=== null ) {
5159 $this->getEditCount();
5160 $dbr = wfGetDB( DB_REPLICA
);
5161 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5163 $this->mEditCount++
;
5166 // Edit count in user cache too
5167 $this->invalidateCache();
5171 * Initialize user_editcount from data out of the revision table
5173 * @param int $add Edits to add to the count from the revision table
5174 * @return int Number of edits
5176 protected function initEditCount( $add = 0 ) {
5177 // Pull from a replica DB to be less cruel to servers
5178 // Accuracy isn't the point anyway here
5179 $dbr = wfGetDB( DB_REPLICA
);
5180 $count = (int)$dbr->selectField(
5183 [ 'rev_user' => $this->getId() ],
5186 $count = $count +
$add;
5188 $dbw = wfGetDB( DB_MASTER
);
5191 [ 'user_editcount' => $count ],
5192 [ 'user_id' => $this->getId() ],
5200 * Get the description of a given right
5203 * @param string $right Right to query
5204 * @return string Localized description of the right
5206 public static function getRightDescription( $right ) {
5207 $key = "right-$right";
5208 $msg = wfMessage( $key );
5209 return $msg->isDisabled() ?
$right : $msg->text();
5213 * Get the name of a given grant
5216 * @param string $grant Grant to query
5217 * @return string Localized name of the grant
5219 public static function getGrantName( $grant ) {
5220 $key = "grant-$grant";
5221 $msg = wfMessage( $key );
5222 return $msg->isDisabled() ?
$grant : $msg->text();
5226 * Add a newuser log entry for this user.
5227 * Before 1.19 the return value was always true.
5229 * @deprecated since 1.27, AuthManager handles logging
5230 * @param string|bool $action Account creation type.
5231 * - String, one of the following values:
5232 * - 'create' for an anonymous user creating an account for himself.
5233 * This will force the action's performer to be the created user itself,
5234 * no matter the value of $wgUser
5235 * - 'create2' for a logged in user creating an account for someone else
5236 * - 'byemail' when the created user will receive its password by e-mail
5237 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5238 * - Boolean means whether the account was created by e-mail (deprecated):
5239 * - true will be converted to 'byemail'
5240 * - false will be converted to 'create' if this object is the same as
5241 * $wgUser and to 'create2' otherwise
5242 * @param string $reason User supplied reason
5245 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5246 return true; // disabled
5250 * Add an autocreate newuser log entry for this user
5251 * Used by things like CentralAuth and perhaps other authplugins.
5252 * Consider calling addNewUserLogEntry() directly instead.
5254 * @deprecated since 1.27, AuthManager handles logging
5257 public function addNewUserLogEntryAutoCreate() {
5258 $this->addNewUserLogEntry( 'autocreate' );
5264 * Load the user options either from cache, the database or an array
5266 * @param array $data Rows for the current user out of the user_properties table
5268 protected function loadOptions( $data = null ) {
5273 if ( $this->mOptionsLoaded
) {
5277 $this->mOptions
= self
::getDefaultOptions();
5279 if ( !$this->getId() ) {
5280 // For unlogged-in users, load language/variant options from request.
5281 // There's no need to do it for logged-in users: they can set preferences,
5282 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5283 // so don't override user's choice (especially when the user chooses site default).
5284 $variant = $wgContLang->getDefaultVariant();
5285 $this->mOptions
['variant'] = $variant;
5286 $this->mOptions
['language'] = $variant;
5287 $this->mOptionsLoaded
= true;
5291 // Maybe load from the object
5292 if ( !is_null( $this->mOptionOverrides
) ) {
5293 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5294 foreach ( $this->mOptionOverrides
as $key => $value ) {
5295 $this->mOptions
[$key] = $value;
5298 if ( !is_array( $data ) ) {
5299 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5300 // Load from database
5301 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5302 ?
wfGetDB( DB_MASTER
)
5303 : wfGetDB( DB_REPLICA
);
5305 $res = $dbr->select(
5307 [ 'up_property', 'up_value' ],
5308 [ 'up_user' => $this->getId() ],
5312 $this->mOptionOverrides
= [];
5314 foreach ( $res as $row ) {
5315 // Convert '0' to 0. PHP's boolean conversion considers them both
5316 // false, but e.g. JavaScript considers the former as true.
5317 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5318 // and convert all values here.
5319 if ( $row->up_value
=== '0' ) {
5322 $data[$row->up_property
] = $row->up_value
;
5325 foreach ( $data as $property => $value ) {
5326 $this->mOptionOverrides
[$property] = $value;
5327 $this->mOptions
[$property] = $value;
5331 $this->mOptionsLoaded
= true;
5333 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5337 * Saves the non-default options for this user, as previously set e.g. via
5338 * setOption(), in the database's "user_properties" (preferences) table.
5339 * Usually used via saveSettings().
5341 protected function saveOptions() {
5342 $this->loadOptions();
5344 // Not using getOptions(), to keep hidden preferences in database
5345 $saveOptions = $this->mOptions
;
5347 // Allow hooks to abort, for instance to save to a global profile.
5348 // Reset options to default state before saving.
5349 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5353 $userId = $this->getId();
5355 $insert_rows = []; // all the new preference rows
5356 foreach ( $saveOptions as $key => $value ) {
5357 // Don't bother storing default values
5358 $defaultOption = self
::getDefaultOption( $key );
5359 if ( ( $defaultOption === null && $value !== false && $value !== null )
5360 ||
$value != $defaultOption
5363 'up_user' => $userId,
5364 'up_property' => $key,
5365 'up_value' => $value,
5370 $dbw = wfGetDB( DB_MASTER
);
5372 $res = $dbw->select( 'user_properties',
5373 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5375 // Find prior rows that need to be removed or updated. These rows will
5376 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5378 foreach ( $res as $row ) {
5379 if ( !isset( $saveOptions[$row->up_property
] )
5380 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5382 $keysDelete[] = $row->up_property
;
5386 if ( count( $keysDelete ) ) {
5387 // Do the DELETE by PRIMARY KEY for prior rows.
5388 // In the past a very large portion of calls to this function are for setting
5389 // 'rememberpassword' for new accounts (a preference that has since been removed).
5390 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5391 // caused gap locks on [max user ID,+infinity) which caused high contention since
5392 // updates would pile up on each other as they are for higher (newer) user IDs.
5393 // It might not be necessary these days, but it shouldn't hurt either.
5394 $dbw->delete( 'user_properties',
5395 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5397 // Insert the new preference rows
5398 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5402 * Lazily instantiate and return a factory object for making passwords
5404 * @deprecated since 1.27, create a PasswordFactory directly instead
5405 * @return PasswordFactory
5407 public static function getPasswordFactory() {
5408 wfDeprecated( __METHOD__
, '1.27' );
5409 $ret = new PasswordFactory();
5410 $ret->init( RequestContext
::getMain()->getConfig() );
5415 * Provide an array of HTML5 attributes to put on an input element
5416 * intended for the user to enter a new password. This may include
5417 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5419 * Do *not* use this when asking the user to enter his current password!
5420 * Regardless of configuration, users may have invalid passwords for whatever
5421 * reason (e.g., they were set before requirements were tightened up).
5422 * Only use it when asking for a new password, like on account creation or
5425 * Obviously, you still need to do server-side checking.
5427 * NOTE: A combination of bugs in various browsers means that this function
5428 * actually just returns array() unconditionally at the moment. May as
5429 * well keep it around for when the browser bugs get fixed, though.
5431 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5433 * @deprecated since 1.27
5434 * @return array Array of HTML attributes suitable for feeding to
5435 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5436 * That will get confused by the boolean attribute syntax used.)
5438 public static function passwordChangeInputAttribs() {
5439 global $wgMinimalPasswordLength;
5441 if ( $wgMinimalPasswordLength == 0 ) {
5445 # Note that the pattern requirement will always be satisfied if the
5446 # input is empty, so we need required in all cases.
5448 # @todo FIXME: T25769: This needs to not claim the password is required
5449 # if e-mail confirmation is being used. Since HTML5 input validation
5450 # is b0rked anyway in some browsers, just return nothing. When it's
5451 # re-enabled, fix this code to not output required for e-mail
5453 # $ret = array( 'required' );
5456 # We can't actually do this right now, because Opera 9.6 will print out
5457 # the entered password visibly in its error message! When other
5458 # browsers add support for this attribute, or Opera fixes its support,
5459 # we can add support with a version check to avoid doing this on Opera
5460 # versions where it will be a problem. Reported to Opera as
5461 # DSK-262266, but they don't have a public bug tracker for us to follow.
5463 if ( $wgMinimalPasswordLength > 1 ) {
5464 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5465 $ret['title'] = wfMessage( 'passwordtooshort' )
5466 ->numParams( $wgMinimalPasswordLength )->text();
5474 * Return the list of user fields that should be selected to create
5475 * a new user object.
5478 public static function selectFields() {
5486 'user_email_authenticated',
5488 'user_email_token_expires',
5489 'user_registration',
5495 * Factory function for fatal permission-denied errors
5498 * @param string $permission User right required
5501 static function newFatalPermissionDeniedStatus( $permission ) {
5505 foreach ( User
::getGroupsWithPermission( $permission ) as $group ) {
5506 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5510 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5512 return Status
::newFatal( 'badaccess-group0' );
5517 * Get a new instance of this user that was loaded from the master via a locking read
5519 * Use this instead of the main context User when updating that user. This avoids races
5520 * where that user was loaded from a replica DB or even the master but without proper locks.
5522 * @return User|null Returns null if the user was not found in the DB
5525 public function getInstanceForUpdate() {
5526 if ( !$this->getId() ) {
5527 return null; // anon
5530 $user = self
::newFromId( $this->getId() );
5531 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5539 * Checks if two user objects point to the same user.
5545 public function equals( User
$user ) {
5546 return $this->getName() === $user->getName();