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
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\Block\DatabaseBlock
;
25 use MediaWiki\Block\SystemBlock
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Session\SessionManager
;
28 use MediaWiki\Session\Token
;
29 use MediaWiki\Auth\AuthManager
;
30 use MediaWiki\Auth\AuthenticationResponse
;
31 use MediaWiki\Auth\AuthenticationRequest
;
32 use MediaWiki\User\UserIdentity
;
33 use MediaWiki\Logger\LoggerFactory
;
34 use Wikimedia\Assert\Assert
;
36 use Wikimedia\ScopedCallback
;
37 use Wikimedia\Rdbms\Database
;
38 use Wikimedia\Rdbms\DBExpectedError
;
39 use Wikimedia\Rdbms\IDatabase
;
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
, UserIdentity
{
54 * Number of characters required for the user_token field.
56 const TOKEN_LENGTH
= 32;
59 * An invalid string value for the user_token field.
61 const INVALID_TOKEN
= '*** INVALID ***';
64 * Version number to tag cached versions of serialized User objects. Should be increased when
65 * {@link $mCacheVars} or one of it's members changes.
70 * Exclude user options that are set to their default value.
73 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
78 const CHECK_USER_RIGHTS
= true;
83 const IGNORE_USER_RIGHTS
= false;
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
113 /** Cache variables */
126 /** @var string TS_MW timestamp from the DB */
128 /** @var string TS_MW timestamp from cache */
129 protected $mQuickTouched;
133 public $mEmailAuthenticated;
135 protected $mEmailToken;
137 protected $mEmailTokenExpires;
139 protected $mRegistration;
141 protected $mEditCount;
142 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
143 protected $mGroupMemberships;
145 protected $mOptionOverrides;
150 * @var bool Whether the cache variables have been loaded.
152 public $mOptionsLoaded;
155 * @var array|bool Array with already loaded items or true if all items have been loaded.
157 protected $mLoadedItems = [];
161 * @var string Initialization data source if mLoadedItems!==true. May be one of:
162 * - 'defaults' anonymous user initialised from class defaults
163 * - 'name' initialise from mName
164 * - 'id' initialise from mId
165 * - 'actor' initialise from mActorId
166 * - 'session' log in from session if possible
168 * Use the User::newFrom*() family of functions to set this.
173 * Lazy-initialized variables, invalidated with clearInstanceCache
178 protected $mDatePreference;
184 protected $mBlockreason;
186 protected $mEffectiveGroups;
188 protected $mImplicitGroups;
190 protected $mFormerGroups;
191 /** @var AbstractBlock */
192 protected $mGlobalBlock;
200 /** @var WebRequest */
203 /** @var AbstractBlock */
207 protected $mAllowUsertalk;
209 /** @var AbstractBlock|bool */
210 private $mBlockedFromCreateAccount = false;
212 /** @var int User::READ_* constant bitfield used to load data */
213 protected $queryFlagsUsed = self
::READ_NORMAL
;
216 public static $idCacheByName = [];
219 * Lightweight constructor for an anonymous user.
220 * Use the User::newFrom* factory functions for other kinds of users.
224 * @see newFromActorId()
225 * @see newFromConfirmationCode()
226 * @see newFromSession()
229 public function __construct() {
230 $this->clearInstanceCache( 'defaults' );
236 public function __toString() {
237 return (string)$this->getName();
240 public function &__get( $name ) {
241 // A shortcut for $mRights deprecation phase
242 if ( $name === 'mRights' ) {
243 $copy = $this->getRights();
245 } elseif ( !property_exists( $this, $name ) ) {
246 // T227688 - do not break $u->foo['bar'] = 1
247 wfLogWarning( 'tried to get non-existent property' );
251 wfLogWarning( 'tried to get non-visible property' );
256 public function __set( $name, $value ) {
257 // A shortcut for $mRights deprecation phase, only known legitimate use was for
258 // testing purposes, other uses seem bad in principle
259 if ( $name === 'mRights' ) {
260 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
262 is_null( $value ) ?
[] : $value
264 } elseif ( !property_exists( $this, $name ) ) {
265 $this->$name = $value;
267 wfLogWarning( 'tried to set non-visible property' );
272 * Test if it's safe to load this User object.
274 * You should typically check this before using $wgUser or
275 * RequestContext::getUser in a method that might be called before the
276 * system has been fully initialized. If the object is unsafe, you should
277 * use an anonymous user:
279 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
285 public function isSafeToLoad() {
286 global $wgFullyInitialised;
288 // The user is safe to load if:
289 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
290 // * mLoadedItems === true (already loaded)
291 // * mFrom !== 'session' (sessions not involved at all)
293 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
294 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
298 * Load the user table data for this object from the source given by mFrom.
300 * @param int $flags User::READ_* constant bitfield
302 public function load( $flags = self
::READ_NORMAL
) {
303 global $wgFullyInitialised;
305 if ( $this->mLoadedItems
=== true ) {
309 // Set it now to avoid infinite recursion in accessors
310 $oldLoadedItems = $this->mLoadedItems
;
311 $this->mLoadedItems
= true;
312 $this->queryFlagsUsed
= $flags;
314 // If this is called too early, things are likely to break.
315 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
316 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
317 ->warning( 'User::loadFromSession called before the end of Setup.php', [
318 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
320 $this->loadDefaults();
321 $this->mLoadedItems
= $oldLoadedItems;
325 switch ( $this->mFrom
) {
327 $this->loadDefaults();
330 // Make sure this thread sees its own changes
331 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
332 if ( $lb->hasOrMadeRecentMasterChanges() ) {
333 $flags |
= self
::READ_LATEST
;
334 $this->queryFlagsUsed
= $flags;
337 $this->mId
= self
::idFromName( $this->mName
, $flags );
339 // Nonexistent user placeholder object
340 $this->loadDefaults( $this->mName
);
342 $this->loadFromId( $flags );
346 // Make sure this thread sees its own changes, if the ID isn't 0
347 if ( $this->mId
!= 0 ) {
348 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
349 if ( $lb->hasOrMadeRecentMasterChanges() ) {
350 $flags |
= self
::READ_LATEST
;
351 $this->queryFlagsUsed
= $flags;
355 $this->loadFromId( $flags );
358 // Make sure this thread sees its own changes
359 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
360 if ( $lb->hasOrMadeRecentMasterChanges() ) {
361 $flags |
= self
::READ_LATEST
;
362 $this->queryFlagsUsed
= $flags;
365 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
366 $row = wfGetDB( $index )->selectRow(
368 [ 'actor_user', 'actor_name' ],
369 [ 'actor_id' => $this->mActorId
],
376 $this->loadDefaults();
377 } elseif ( $row->actor_user
) {
378 $this->mId
= $row->actor_user
;
379 $this->loadFromId( $flags );
381 $this->loadDefaults( $row->actor_name
);
385 if ( !$this->loadFromSession() ) {
386 // Loading from session failed. Load defaults.
387 $this->loadDefaults();
389 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
392 throw new UnexpectedValueException(
393 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
398 * Load user table data, given mId has already been set.
399 * @param int $flags User::READ_* constant bitfield
400 * @return bool False if the ID does not exist, true otherwise
402 public function loadFromId( $flags = self
::READ_NORMAL
) {
403 if ( $this->mId
== 0 ) {
404 // Anonymous users are not in the database (don't need cache)
405 $this->loadDefaults();
409 // Try cache (unless this needs data from the master DB).
410 // NOTE: if this thread called saveSettings(), the cache was cleared.
411 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
413 if ( !$this->loadFromDatabase( $flags ) ) {
414 // Can't load from ID
418 $this->loadFromCache();
421 $this->mLoadedItems
= true;
422 $this->queryFlagsUsed
= $flags;
429 * @param string $dbDomain
432 public static function purge( $dbDomain, $userId ) {
433 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
434 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
435 $cache->delete( $key );
440 * @param WANObjectCache $cache
443 protected function getCacheKey( WANObjectCache
$cache ) {
444 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
446 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
450 * @param WANObjectCache $cache
454 public function getMutableCacheKeys( WANObjectCache
$cache ) {
455 $id = $this->getId();
457 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
461 * Load user data from shared cache, given mId has already been set.
466 protected function loadFromCache() {
467 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
468 $data = $cache->getWithSetCallback(
469 $this->getCacheKey( $cache ),
471 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
472 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
473 wfDebug( "User: cache miss for user {$this->mId}\n" );
475 $this->loadFromDatabase( self
::READ_NORMAL
);
477 $this->loadOptions();
480 foreach ( self
::$mCacheVars as $name ) {
481 $data[$name] = $this->$name;
484 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
486 // if a user group membership is about to expire, the cache needs to
487 // expire at that time (T163691)
488 foreach ( $this->mGroupMemberships
as $ugm ) {
489 if ( $ugm->getExpiry() ) {
490 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
491 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
492 $ttl = $secondsUntilExpiry;
499 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
502 // Restore from cache
503 foreach ( self
::$mCacheVars as $name ) {
504 $this->$name = $data[$name];
510 /** @name newFrom*() static factory methods */
514 * Static factory method for creation from username.
516 * This is slightly less efficient than newFromId(), so use newFromId() if
517 * you have both an ID and a name handy.
519 * @param string $name Username, validated by Title::newFromText()
520 * @param string|bool $validate Validate username. Takes the same parameters as
521 * User::getCanonicalName(), except that true is accepted as an alias
522 * for 'valid', for BC.
524 * @return User|bool User object, or false if the username is invalid
525 * (e.g. if it contains illegal characters or is an IP address). If the
526 * username is not present in the database, the result will be a user object
527 * with a name, zero user ID and default settings.
529 public static function newFromName( $name, $validate = 'valid' ) {
530 if ( $validate === true ) {
533 $name = self
::getCanonicalName( $name, $validate );
534 if ( $name === false ) {
538 // Create unloaded user object
542 $u->setItemLoaded( 'name' );
548 * Static factory method for creation from a given user ID.
550 * @param int $id Valid user ID
551 * @return User The corresponding User object
553 public static function newFromId( $id ) {
557 $u->setItemLoaded( 'id' );
562 * Static factory method for creation from a given actor ID.
565 * @param int $id Valid actor ID
566 * @return User The corresponding User object
568 public static function newFromActorId( $id ) {
569 global $wgActorTableSchemaMigrationStage;
571 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
572 // but it does little harm and might be needed for write callers loading a User.
573 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
574 throw new BadMethodCallException(
575 'Cannot use ' . __METHOD__
576 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
583 $u->setItemLoaded( 'actor' );
588 * Returns a User object corresponding to the given UserIdentity.
592 * @param UserIdentity $identity
596 public static function newFromIdentity( UserIdentity
$identity ) {
597 if ( $identity instanceof User
) {
601 return self
::newFromAnyId(
602 $identity->getId() === 0 ?
null : $identity->getId(),
603 $identity->getName() === '' ?
null : $identity->getName(),
604 $identity->getActorId() === 0 ?
null : $identity->getActorId()
609 * Static factory method for creation from an ID, name, and/or actor ID
611 * This does not check that the ID, name, and actor ID all correspond to
615 * @param int|null $userId User ID, if known
616 * @param string|null $userName User name, if known
617 * @param int|null $actorId Actor ID, if known
618 * @param bool|string $dbDomain remote wiki to which the User/Actor ID applies, or false if none
621 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
622 global $wgActorTableSchemaMigrationStage;
624 // Stop-gap solution for the problem described in T222212.
625 // Force the User ID and Actor ID to zero for users loaded from the database
626 // of another wiki, to prevent subtle data corruption and confusing failure modes.
627 if ( $dbDomain !== false ) {
633 $user->mFrom
= 'defaults';
635 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
636 // but it does little harm and might be needed for write callers loading a User.
637 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
638 $user->mActorId
= (int)$actorId;
639 if ( $user->mActorId
!== 0 ) {
640 $user->mFrom
= 'actor';
642 $user->setItemLoaded( 'actor' );
645 if ( $userName !== null && $userName !== '' ) {
646 $user->mName
= $userName;
647 $user->mFrom
= 'name';
648 $user->setItemLoaded( 'name' );
651 if ( $userId !== null ) {
652 $user->mId
= (int)$userId;
653 if ( $user->mId
!== 0 ) {
656 $user->setItemLoaded( 'id' );
659 if ( $user->mFrom
=== 'defaults' ) {
660 throw new InvalidArgumentException(
661 'Cannot create a user with no name, no ID, and no actor ID'
669 * Factory method to fetch whichever user has a given email confirmation code.
670 * This code is generated when an account is created or its e-mail address
673 * If the code is invalid or has expired, returns NULL.
675 * @param string $code Confirmation code
676 * @param int $flags User::READ_* bitfield
679 public static function newFromConfirmationCode( $code, $flags = 0 ) {
680 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
681 ?
wfGetDB( DB_MASTER
)
682 : wfGetDB( DB_REPLICA
);
684 $id = $db->selectField(
688 'user_email_token' => md5( $code ),
689 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
693 return $id ? self
::newFromId( $id ) : null;
697 * Create a new user object using data from session. If the login
698 * credentials are invalid, the result is an anonymous user.
700 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
703 public static function newFromSession( WebRequest
$request = null ) {
705 $user->mFrom
= 'session';
706 $user->mRequest
= $request;
711 * Create a new user object from a user row.
712 * The row should have the following fields from the user table in it:
713 * - either user_name or user_id to load further data if needed (or both)
715 * - all other fields (email, etc.)
716 * It is useless to provide the remaining fields if either user_id,
717 * user_name and user_real_name are not provided because the whole row
718 * will be loaded once more from the database when accessing them.
720 * @param stdClass $row A row from the user table
721 * @param array|null $data Further data to load into the object
722 * (see User::loadFromRow for valid keys)
725 public static function newFromRow( $row, $data = null ) {
727 $user->loadFromRow( $row, $data );
732 * Static factory method for creation of a "system" user from username.
734 * A "system" user is an account that's used to attribute logged actions
735 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
736 * might include the 'Maintenance script' or 'Conversion script' accounts
737 * used by various scripts in the maintenance/ directory or accounts such
738 * as 'MediaWiki message delivery' used by the MassMessage extension.
740 * This can optionally create the user if it doesn't exist, and "steal" the
741 * account if it does exist.
743 * "Stealing" an existing user is intended to make it impossible for normal
744 * authentication processes to use the account, effectively disabling the
745 * account for normal use:
746 * - Email is invalidated, to prevent account recovery by emailing a
747 * temporary password and to disassociate the account from the existing
749 * - The token is set to a magic invalid value, to kill existing sessions
750 * and to prevent $this->setToken() calls from resetting the token to a
752 * - SessionManager is instructed to prevent new sessions for the user, to
753 * do things like deauthorizing OAuth consumers.
754 * - AuthManager is instructed to revoke access, to invalidate or remove
755 * passwords and other credentials.
757 * @param string $name Username
758 * @param array $options Options are:
759 * - validate: As for User::getCanonicalName(), default 'valid'
760 * - create: Whether to create the user if it doesn't already exist, default true
761 * - steal: Whether to "disable" the account for normal use if it already
762 * exists, default false
766 public static function newSystemUser( $name, $options = [] ) {
768 'validate' => 'valid',
773 $name = self
::getCanonicalName( $name, $options['validate'] );
774 if ( $name === false ) {
778 $dbr = wfGetDB( DB_REPLICA
);
779 $userQuery = self
::getQueryInfo();
780 $row = $dbr->selectRow(
781 $userQuery['tables'],
782 $userQuery['fields'],
783 [ 'user_name' => $name ],
789 // Try the master database...
790 $dbw = wfGetDB( DB_MASTER
);
791 $row = $dbw->selectRow(
792 $userQuery['tables'],
793 $userQuery['fields'],
794 [ 'user_name' => $name ],
802 // No user. Create it?
803 return $options['create']
804 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
808 $user = self
::newFromRow( $row );
810 // A user is considered to exist as a non-system user if it can
811 // authenticate, or has an email set, or has a non-invalid token.
812 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
813 AuthManager
::singleton()->userCanAuthenticate( $name )
815 // User exists. Steal it?
816 if ( !$options['steal'] ) {
820 AuthManager
::singleton()->revokeAccessForUser( $name );
822 $user->invalidateEmail();
823 $user->mToken
= self
::INVALID_TOKEN
;
824 $user->saveSettings();
825 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
834 * Get the username corresponding to a given user ID
835 * @param int $id User ID
836 * @return string|bool The corresponding username
838 public static function whoIs( $id ) {
839 return UserCache
::singleton()->getProp( $id, 'name' );
843 * Get the real name of a user given their user ID
845 * @param int $id User ID
846 * @return string|bool The corresponding user's real name
848 public static function whoIsReal( $id ) {
849 return UserCache
::singleton()->getProp( $id, 'real_name' );
853 * Get database id given a user name
854 * @param string $name Username
855 * @param int $flags User::READ_* constant bitfield
856 * @return int|null The corresponding user's ID, or null if user is nonexistent
858 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
859 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
860 $name = (string)$name;
861 $nt = Title
::makeTitleSafe( NS_USER
, $name );
862 if ( is_null( $nt ) ) {
867 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
868 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
871 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
872 $db = wfGetDB( $index );
877 [ 'user_name' => $nt->getText() ],
882 if ( $s === false ) {
885 $result = (int)$s->user_id
;
888 if ( count( self
::$idCacheByName ) >= 1000 ) {
889 self
::$idCacheByName = [];
892 self
::$idCacheByName[$name] = $result;
898 * Reset the cache used in idFromName(). For use in tests.
900 public static function resetIdByNameCache() {
901 self
::$idCacheByName = [];
905 * Does the string match an anonymous IP address?
907 * This function exists for username validation, in order to reject
908 * usernames which are similar in form to IP addresses. Strings such
909 * as 300.300.300.300 will return true because it looks like an IP
910 * address, despite not being strictly valid.
912 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
913 * address because the usemod software would "cloak" anonymous IP
914 * addresses like this, if we allowed accounts like this to be created
915 * new users could get the old edits of these anonymous users.
917 * @param string $name Name to match
920 public static function isIP( $name ) {
921 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
922 || IP
::isIPv6( $name );
926 * Is the user an IP range?
931 public function isIPRange() {
932 return IP
::isValidRange( $this->mName
);
936 * Is the input a valid username?
938 * Checks if the input is a valid username, we don't want an empty string,
939 * an IP address, anything that contains slashes (would mess up subpages),
940 * is longer than the maximum allowed username size or doesn't begin with
943 * @param string $name Name to match
946 public static function isValidUserName( $name ) {
947 global $wgMaxNameChars;
950 || self
::isIP( $name )
951 ||
strpos( $name, '/' ) !== false
952 ||
strlen( $name ) > $wgMaxNameChars
953 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
958 // Ensure that the name can't be misresolved as a different title,
959 // such as with extra namespace keys at the start.
960 $parsed = Title
::newFromText( $name );
961 if ( is_null( $parsed )
962 ||
$parsed->getNamespace()
963 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
967 // Check an additional blacklist of troublemaker characters.
968 // Should these be merged into the title char list?
969 $unicodeBlacklist = '/[' .
970 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
971 '\x{00a0}' . # non-breaking space
972 '\x{2000}-\x{200f}' . # various whitespace
973 '\x{2028}-\x{202f}' . # breaks and control chars
974 '\x{3000}' . # ideographic space
975 '\x{e000}-\x{f8ff}' . # private use
977 if ( preg_match( $unicodeBlacklist, $name ) ) {
985 * Usernames which fail to pass this function will be blocked
986 * from user login and new account registrations, but may be used
987 * internally by batch processes.
989 * If an account already exists in this form, login will be blocked
990 * by a failure to pass this function.
992 * @param string $name Name to match
995 public static function isUsableName( $name ) {
996 global $wgReservedUsernames;
997 // Must be a valid username, obviously ;)
998 if ( !self
::isValidUserName( $name ) ) {
1002 static $reservedUsernames = false;
1003 if ( !$reservedUsernames ) {
1004 $reservedUsernames = $wgReservedUsernames;
1005 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1008 // Certain names may be reserved for batch processes.
1009 foreach ( $reservedUsernames as $reserved ) {
1010 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1011 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1013 if ( $reserved == $name ) {
1021 * Return the users who are members of the given group(s). In case of multiple groups,
1022 * users who are members of at least one of them are returned.
1024 * @param string|array $groups A single group name or an array of group names
1025 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1026 * records; larger values are ignored.
1027 * @param int|null $after ID the user to start after
1028 * @return UserArrayFromResult
1030 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1031 if ( $groups === [] ) {
1032 return UserArrayFromResult
::newFromIDs( [] );
1035 $groups = array_unique( (array)$groups );
1036 $limit = min( 5000, $limit );
1038 $conds = [ 'ug_group' => $groups ];
1039 if ( $after !== null ) {
1040 $conds[] = 'ug_user > ' . (int)$after;
1043 $dbr = wfGetDB( DB_REPLICA
);
1044 $ids = $dbr->selectFieldValues(
1051 'ORDER BY' => 'ug_user',
1055 return UserArray
::newFromIDs( $ids );
1059 * Usernames which fail to pass this function will be blocked
1060 * from new account registrations, but may be used internally
1061 * either by batch processes or by user accounts which have
1062 * already been created.
1064 * Additional blacklisting may be added here rather than in
1065 * isValidUserName() to avoid disrupting existing accounts.
1067 * @param string $name String to match
1070 public static function isCreatableName( $name ) {
1071 global $wgInvalidUsernameCharacters;
1073 // Ensure that the username isn't longer than 235 bytes, so that
1074 // (at least for the builtin skins) user javascript and css files
1075 // will work. (T25080)
1076 if ( strlen( $name ) > 235 ) {
1077 wfDebugLog( 'username', __METHOD__
.
1078 ": '$name' invalid due to length" );
1082 // Preg yells if you try to give it an empty string
1083 if ( $wgInvalidUsernameCharacters !== '' &&
1084 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1086 wfDebugLog( 'username', __METHOD__
.
1087 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1091 return self
::isUsableName( $name );
1095 * Is the input a valid password for this user?
1097 * @param string $password Desired password
1100 public function isValidPassword( $password ) {
1101 // simple boolean wrapper for checkPasswordValidity
1102 return $this->checkPasswordValidity( $password )->isGood();
1106 * Check if this is a valid password for this user
1108 * Returns a Status object with a set of messages describing
1109 * problems with the password. If the return status is fatal,
1110 * the action should be refused and the password should not be
1111 * checked at all (this is mainly meant for DoS mitigation).
1112 * If the return value is OK but not good, the password can be checked,
1113 * but the user should not be able to set their password to this.
1114 * The value of the returned Status object will be an array which
1115 * can have the following fields:
1116 * - forceChange (bool): if set to true, the user should not be
1117 * allowed to log with this password unless they change it during
1118 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1119 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1120 * a password change on login.
1122 * @param string $password Desired password
1126 public function checkPasswordValidity( $password ) {
1127 global $wgPasswordPolicy;
1129 $upp = new UserPasswordPolicy(
1130 $wgPasswordPolicy['policies'],
1131 $wgPasswordPolicy['checks']
1134 $status = Status
::newGood( [] );
1135 $result = false; // init $result to false for the internal checks
1137 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1138 $status->error( $result );
1142 if ( $result === false ) {
1143 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1147 if ( $result === true ) {
1151 $status->error( $result );
1152 return $status; // the isValidPassword hook set a string $result and returned true
1156 * Given unvalidated user input, return a canonical username, or false if
1157 * the username is invalid.
1158 * @param string $name User input
1159 * @param string|bool $validate Type of validation to use:
1160 * - false No validation
1161 * - 'valid' Valid for batch processes
1162 * - 'usable' Valid for batch processes and login
1163 * - 'creatable' Valid for batch processes, login and account creation
1165 * @throws InvalidArgumentException
1166 * @return bool|string
1168 public static function getCanonicalName( $name, $validate = 'valid' ) {
1169 // Force usernames to capital
1170 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1172 # Reject names containing '#'; these will be cleaned up
1173 # with title normalisation, but then it's too late to
1175 if ( strpos( $name, '#' ) !== false ) {
1179 // Clean up name according to title rules,
1180 // but only when validation is requested (T14654)
1181 $t = ( $validate !== false ) ?
1182 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1183 // Check for invalid titles
1184 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1188 $name = $t->getText();
1190 switch ( $validate ) {
1194 if ( !self
::isValidUserName( $name ) ) {
1199 if ( !self
::isUsableName( $name ) ) {
1204 if ( !self
::isCreatableName( $name ) ) {
1209 throw new InvalidArgumentException(
1210 'Invalid parameter value for $validate in ' . __METHOD__
);
1216 * Set cached properties to default.
1218 * @note This no longer clears uncached lazy-initialised properties;
1219 * the constructor does that instead.
1221 * @param string|bool $name
1223 public function loadDefaults( $name = false ) {
1225 $this->mName
= $name;
1226 $this->mActorId
= null;
1227 $this->mRealName
= '';
1229 $this->mOptionOverrides
= null;
1230 $this->mOptionsLoaded
= false;
1232 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1233 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1234 if ( $loggedOut !== 0 ) {
1235 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1237 $this->mTouched
= '1'; # Allow any pages to be cached
1240 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1241 $this->mEmailAuthenticated
= null;
1242 $this->mEmailToken
= '';
1243 $this->mEmailTokenExpires
= null;
1244 $this->mRegistration
= wfTimestamp( TS_MW
);
1245 $this->mGroupMemberships
= [];
1247 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1251 * Return whether an item has been loaded.
1253 * @param string $item Item to check. Current possibilities:
1257 * @param string $all 'all' to check if the whole object has been loaded
1258 * or any other string to check if only the item is available (e.g.
1262 public function isItemLoaded( $item, $all = 'all' ) {
1263 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1264 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1268 * Set that an item has been loaded
1270 * @param string $item
1272 protected function setItemLoaded( $item ) {
1273 if ( is_array( $this->mLoadedItems
) ) {
1274 $this->mLoadedItems
[$item] = true;
1279 * Load user data from the session.
1281 * @return bool True if the user is logged in, false otherwise.
1283 private function loadFromSession() {
1284 // MediaWiki\Session\Session already did the necessary authentication of the user
1285 // returned here, so just use it if applicable.
1286 $session = $this->getRequest()->getSession();
1287 $user = $session->getUser();
1288 if ( $user->isLoggedIn() ) {
1289 $this->loadFromUserObject( $user );
1291 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1292 // every session load, because an autoblocked editor might not edit again from the same
1293 // IP address after being blocked.
1294 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1296 // Other code expects these to be set in the session, so set them.
1297 $session->set( 'wsUserID', $this->getId() );
1298 $session->set( 'wsUserName', $this->getName() );
1299 $session->set( 'wsToken', $this->getToken() );
1308 * Set the 'BlockID' cookie depending on block type and user authentication status.
1310 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1312 public function trackBlockWithCookie() {
1313 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1317 * Load user and user_group data from the database.
1318 * $this->mId must be set, this is how the user is identified.
1320 * @param int $flags User::READ_* constant bitfield
1321 * @return bool True if the user exists, false if the user is anonymous
1323 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1325 $this->mId
= intval( $this->mId
);
1327 if ( !$this->mId
) {
1328 // Anonymous users are not in the database
1329 $this->loadDefaults();
1333 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1334 $db = wfGetDB( $index );
1336 $userQuery = self
::getQueryInfo();
1337 $s = $db->selectRow(
1338 $userQuery['tables'],
1339 $userQuery['fields'],
1340 [ 'user_id' => $this->mId
],
1346 $this->queryFlagsUsed
= $flags;
1347 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1349 if ( $s !== false ) {
1350 // Initialise user table data
1351 $this->loadFromRow( $s );
1352 $this->mGroupMemberships
= null; // deferred
1353 $this->getEditCount(); // revalidation for nulls
1359 $this->loadDefaults();
1365 * Initialize this object from a row from the user table.
1367 * @param stdClass $row Row from the user table to load.
1368 * @param array|null $data Further user data to load into the object
1370 * user_groups Array of arrays or stdClass result rows out of the user_groups
1371 * table. Previously you were supposed to pass an array of strings
1372 * here, but we also need expiry info nowadays, so an array of
1373 * strings is ignored.
1374 * user_properties Array with properties out of the user_properties table
1376 protected function loadFromRow( $row, $data = null ) {
1377 global $wgActorTableSchemaMigrationStage;
1379 if ( !is_object( $row ) ) {
1380 throw new InvalidArgumentException( '$row must be an object' );
1385 $this->mGroupMemberships
= null; // deferred
1387 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1388 // but it does little harm and might be needed for write callers loading a User.
1389 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1390 if ( isset( $row->actor_id
) ) {
1391 $this->mActorId
= (int)$row->actor_id
;
1392 if ( $this->mActorId
!== 0 ) {
1393 $this->mFrom
= 'actor';
1395 $this->setItemLoaded( 'actor' );
1401 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1402 $this->mName
= $row->user_name
;
1403 $this->mFrom
= 'name';
1404 $this->setItemLoaded( 'name' );
1409 if ( isset( $row->user_real_name
) ) {
1410 $this->mRealName
= $row->user_real_name
;
1411 $this->setItemLoaded( 'realname' );
1416 if ( isset( $row->user_id
) ) {
1417 $this->mId
= intval( $row->user_id
);
1418 if ( $this->mId
!== 0 ) {
1419 $this->mFrom
= 'id';
1421 $this->setItemLoaded( 'id' );
1426 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1427 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1430 if ( isset( $row->user_editcount
) ) {
1431 $this->mEditCount
= $row->user_editcount
;
1436 if ( isset( $row->user_touched
) ) {
1437 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1442 if ( isset( $row->user_token
) ) {
1443 // The definition for the column is binary(32), so trim the NULs
1444 // that appends. The previous definition was char(32), so trim
1446 $this->mToken
= rtrim( $row->user_token
, " \0" );
1447 if ( $this->mToken
=== '' ) {
1448 $this->mToken
= null;
1454 if ( isset( $row->user_email
) ) {
1455 $this->mEmail
= $row->user_email
;
1456 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1457 $this->mEmailToken
= $row->user_email_token
;
1458 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1459 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1465 $this->mLoadedItems
= true;
1468 if ( is_array( $data ) ) {
1469 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1470 if ( $data['user_groups'] === [] ) {
1471 $this->mGroupMemberships
= [];
1473 $firstGroup = reset( $data['user_groups'] );
1474 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1475 $this->mGroupMemberships
= [];
1476 foreach ( $data['user_groups'] as $row ) {
1477 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1478 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1483 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1484 $this->loadOptions( $data['user_properties'] );
1490 * Load the data for this user object from another user object.
1494 protected function loadFromUserObject( $user ) {
1496 foreach ( self
::$mCacheVars as $var ) {
1497 $this->$var = $user->$var;
1502 * Load the groups from the database if they aren't already loaded.
1504 private function loadGroups() {
1505 if ( is_null( $this->mGroupMemberships
) ) {
1506 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1507 ?
wfGetDB( DB_MASTER
)
1508 : wfGetDB( DB_REPLICA
);
1509 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1515 * Add the user to the group if he/she meets given criteria.
1517 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1518 * possible to remove manually via Special:UserRights. In such case it
1519 * will not be re-added automatically. The user will also not lose the
1520 * group if they no longer meet the criteria.
1522 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1524 * @return array Array of groups the user has been promoted to.
1526 * @see $wgAutopromoteOnce
1528 public function addAutopromoteOnceGroups( $event ) {
1529 global $wgAutopromoteOnceLogInRC;
1531 if ( wfReadOnly() ||
!$this->getId() ) {
1535 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1536 if ( $toPromote === [] ) {
1540 if ( !$this->checkAndSetTouched() ) {
1541 return []; // raced out (bug T48834)
1544 $oldGroups = $this->getGroups(); // previous groups
1545 $oldUGMs = $this->getGroupMemberships();
1546 foreach ( $toPromote as $group ) {
1547 $this->addGroup( $group );
1549 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1550 $newUGMs = $this->getGroupMemberships();
1552 // update groups in external authentication database
1553 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1555 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1556 $logEntry->setPerformer( $this );
1557 $logEntry->setTarget( $this->getUserPage() );
1558 $logEntry->setParameters( [
1559 '4::oldgroups' => $oldGroups,
1560 '5::newgroups' => $newGroups,
1562 $logid = $logEntry->insert();
1563 if ( $wgAutopromoteOnceLogInRC ) {
1564 $logEntry->publish( $logid );
1571 * Builds update conditions. Additional conditions may be added to $conditions to
1572 * protected against race conditions using a compare-and-set (CAS) mechanism
1573 * based on comparing $this->mTouched with the user_touched field.
1575 * @param IDatabase $db
1576 * @param array $conditions WHERE conditions for use with Database::update
1577 * @return array WHERE conditions for use with Database::update
1579 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1580 if ( $this->mTouched
) {
1581 // CAS check: only update if the row wasn't changed sicne it was loaded.
1582 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1589 * Bump user_touched if it didn't change since this object was loaded
1591 * On success, the mTouched field is updated.
1592 * The user serialization cache is always cleared.
1594 * @return bool Whether user_touched was actually updated
1597 protected function checkAndSetTouched() {
1600 if ( !$this->mId
) {
1601 return false; // anon
1604 // Get a new user_touched that is higher than the old one
1605 $newTouched = $this->newTouchedTimestamp();
1607 $dbw = wfGetDB( DB_MASTER
);
1608 $dbw->update( 'user',
1609 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1610 $this->makeUpdateConditions( $dbw, [
1611 'user_id' => $this->mId
,
1615 $success = ( $dbw->affectedRows() > 0 );
1618 $this->mTouched
= $newTouched;
1619 $this->clearSharedCache( 'changed' );
1621 // Clears on failure too since that is desired if the cache is stale
1622 $this->clearSharedCache( 'refresh' );
1629 * Clear various cached data stored in this object. The cache of the user table
1630 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1632 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1633 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1635 public function clearInstanceCache( $reloadFrom = false ) {
1636 global $wgFullyInitialised;
1638 $this->mNewtalk
= -1;
1639 $this->mDatePreference
= null;
1640 $this->mBlockedby
= -1; # Unset
1641 $this->mHash
= false;
1642 $this->mEffectiveGroups
= null;
1643 $this->mImplicitGroups
= null;
1644 $this->mGroupMemberships
= null;
1645 $this->mOptions
= null;
1646 $this->mOptionsLoaded
= false;
1647 $this->mEditCount
= null;
1649 // Replacement of former `$this->mRights = null` line
1650 if ( $wgFullyInitialised && $this->mFrom
) {
1651 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1656 if ( $reloadFrom ) {
1657 $this->mLoadedItems
= [];
1658 $this->mFrom
= $reloadFrom;
1662 /** @var array|null */
1663 private static $defOpt = null;
1664 /** @var string|null */
1665 private static $defOptLang = null;
1668 * Reset the process cache of default user options. This is only necessary
1669 * if the wiki configuration has changed since defaults were calculated,
1670 * and as such should only be performed inside the testing suite that
1671 * regularly changes wiki configuration.
1673 public static function resetGetDefaultOptionsForTestsOnly() {
1674 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1675 self
::$defOpt = null;
1676 self
::$defOptLang = null;
1680 * Combine the language default options with any site-specific options
1681 * and add the default language variants.
1683 * @return array Array of String options
1685 public static function getDefaultOptions() {
1686 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1688 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1689 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1690 // The content language does not change (and should not change) mid-request, but the
1691 // unit tests change it anyway, and expect this method to return values relevant to the
1692 // current content language.
1693 return self
::$defOpt;
1696 self
::$defOpt = $wgDefaultUserOptions;
1697 // Default language setting
1698 self
::$defOptLang = $contLang->getCode();
1699 self
::$defOpt['language'] = self
::$defOptLang;
1700 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1701 if ( $langCode === $contLang->getCode() ) {
1702 self
::$defOpt['variant'] = $langCode;
1704 self
::$defOpt["variant-$langCode"] = $langCode;
1708 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1709 // since extensions may change the set of searchable namespaces depending
1710 // on user groups/permissions.
1711 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1712 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1714 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1716 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1718 return self
::$defOpt;
1722 * Get a given default option value.
1724 * @param string $opt Name of option to retrieve
1725 * @return string Default option value
1727 public static function getDefaultOption( $opt ) {
1728 $defOpts = self
::getDefaultOptions();
1729 return $defOpts[$opt] ??
null;
1733 * Get blocking information
1735 * TODO: Move this into the BlockManager, along with block-related properties.
1737 * @param bool $fromReplica Whether to check the replica DB first.
1738 * To improve performance, non-critical checks are done against replica DBs.
1739 * Check when actually saving should be done against master.
1741 private function getBlockedStatus( $fromReplica = true ) {
1742 if ( $this->mBlockedby
!= -1 ) {
1746 wfDebug( __METHOD__
. ": checking...\n" );
1748 // Initialize data...
1749 // Otherwise something ends up stomping on $this->mBlockedby when
1750 // things get lazy-loaded later, causing false positive block hits
1751 // due to -1 !== 0. Probably session-related... Nothing should be
1752 // overwriting mBlockedby, surely?
1755 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1761 $this->mBlock
= $block;
1762 $this->mBlockedby
= $block->getByName();
1763 $this->mBlockreason
= $block->getReason();
1764 $this->mHideName
= $block->getHideName();
1765 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1767 $this->mBlock
= null;
1768 $this->mBlockedby
= '';
1769 $this->mBlockreason
= '';
1770 $this->mHideName
= 0;
1771 $this->mAllowUsertalk
= false;
1774 // Avoid PHP 7.1 warning of passing $this by reference
1777 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1781 * Whether the given IP is in a DNS blacklist.
1783 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1784 * @param string $ip IP to check
1785 * @param bool $checkWhitelist Whether to check the whitelist first
1786 * @return bool True if blacklisted.
1788 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1789 return MediaWikiServices
::getInstance()->getBlockManager()
1790 ->isDnsBlacklisted( $ip, $checkWhitelist );
1794 * Whether the given IP is in a given DNS blacklist.
1796 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1797 * @param string $ip IP to check
1798 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1799 * @return bool True if blacklisted.
1801 public function inDnsBlacklist( $ip, $bases ) {
1802 wfDeprecated( __METHOD__
, '1.34' );
1805 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1806 if ( IP
::isIPv4( $ip ) ) {
1807 // Reverse IP, T23255
1808 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1810 foreach ( (array)$bases as $base ) {
1812 // If we have an access key, use that too (ProjectHoneypot, etc.)
1814 if ( is_array( $base ) ) {
1815 if ( count( $base ) >= 2 ) {
1816 // Access key is 1, base URL is 0
1817 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1819 $host = "$ipReversed.{$base[0]}";
1821 $basename = $base[0];
1823 $host = "$ipReversed.$base";
1827 $ipList = gethostbynamel( $host );
1830 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1835 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1843 * Check if an IP address is in the local proxy list
1845 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1849 public static function isLocallyBlockedProxy( $ip ) {
1850 wfDeprecated( __METHOD__
, '1.34' );
1852 global $wgProxyList;
1854 if ( !$wgProxyList ) {
1858 if ( !is_array( $wgProxyList ) ) {
1859 // Load values from the specified file
1860 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1863 $resultProxyList = [];
1864 $deprecatedIPEntries = [];
1866 // backward compatibility: move all ip addresses in keys to values
1867 foreach ( $wgProxyList as $key => $value ) {
1868 $keyIsIP = IP
::isIPAddress( $key );
1869 $valueIsIP = IP
::isIPAddress( $value );
1870 if ( $keyIsIP && !$valueIsIP ) {
1871 $deprecatedIPEntries[] = $key;
1872 $resultProxyList[] = $key;
1873 } elseif ( $keyIsIP && $valueIsIP ) {
1874 $deprecatedIPEntries[] = $key;
1875 $resultProxyList[] = $key;
1876 $resultProxyList[] = $value;
1878 $resultProxyList[] = $value;
1882 if ( $deprecatedIPEntries ) {
1884 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1885 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1888 $proxyListIPSet = new IPSet( $resultProxyList );
1889 return $proxyListIPSet->match( $ip );
1893 * Is this user subject to rate limiting?
1895 * @return bool True if rate limited
1897 public function isPingLimitable() {
1898 global $wgRateLimitsExcludedIPs;
1899 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1900 // No other good way currently to disable rate limits
1901 // for specific IPs. :P
1902 // But this is a crappy hack and should die.
1905 return !$this->isAllowed( 'noratelimit' );
1909 * Primitive rate limits: enforce maximum actions per time period
1910 * to put a brake on flooding.
1912 * The method generates both a generic profiling point and a per action one
1913 * (suffix being "-$action".
1915 * @note When using a shared cache like memcached, IP-address
1916 * last-hit counters will be shared across wikis.
1918 * @param string $action Action to enforce; 'edit' if unspecified
1919 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1920 * @return bool True if a rate limiter was tripped
1922 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1923 // Avoid PHP 7.1 warning of passing $this by reference
1925 // Call the 'PingLimiter' hook
1927 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1931 global $wgRateLimits;
1932 if ( !isset( $wgRateLimits[$action] ) ) {
1936 $limits = array_merge(
1937 [ '&can-bypass' => true ],
1938 $wgRateLimits[$action]
1941 // Some groups shouldn't trigger the ping limiter, ever
1942 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1947 $id = $this->getId();
1949 $isNewbie = $this->isNewbie();
1950 $cache = ObjectCache
::getLocalClusterInstance();
1954 if ( isset( $limits['anon'] ) ) {
1955 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1957 } elseif ( isset( $limits['user'] ) ) {
1958 // limits for logged-in users
1959 $userLimit = $limits['user'];
1962 // limits for anons and for newbie logged-in users
1965 if ( isset( $limits['ip'] ) ) {
1966 $ip = $this->getRequest()->getIP();
1967 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1969 // subnet-based limits
1970 if ( isset( $limits['subnet'] ) ) {
1971 $ip = $this->getRequest()->getIP();
1972 $subnet = IP
::getSubnet( $ip );
1973 if ( $subnet !== false ) {
1974 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1979 // Check for group-specific permissions
1980 // If more than one group applies, use the group with the highest limit ratio (max/period)
1981 foreach ( $this->getGroups() as $group ) {
1982 if ( isset( $limits[$group] ) ) {
1983 if ( $userLimit === false
1984 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1986 $userLimit = $limits[$group];
1991 // limits for newbie logged-in users (override all the normal user limits)
1992 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1993 $userLimit = $limits['newbie'];
1996 // Set the user limit key
1997 if ( $userLimit !== false ) {
1998 // phan is confused because &can-bypass's value is a bool, so it assumes
1999 // that $userLimit is also a bool here.
2000 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2001 list( $max, $period ) = $userLimit;
2002 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2003 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2006 // ip-based limits for all ping-limitable users
2007 if ( isset( $limits['ip-all'] ) ) {
2008 $ip = $this->getRequest()->getIP();
2009 // ignore if user limit is more permissive
2010 if ( $isNewbie ||
$userLimit === false
2011 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2012 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2016 // subnet-based limits for all ping-limitable users
2017 if ( isset( $limits['subnet-all'] ) ) {
2018 $ip = $this->getRequest()->getIP();
2019 $subnet = IP
::getSubnet( $ip );
2020 if ( $subnet !== false ) {
2021 // ignore if user limit is more permissive
2022 if ( $isNewbie ||
$userLimit === false
2023 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2024 > $userLimit[0] / $userLimit[1] ) {
2025 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2031 foreach ( $keys as $key => $limit ) {
2032 // phan is confused because &can-bypass's value is a bool, so it assumes
2033 // that $userLimit is also a bool here.
2034 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2035 list( $max, $period ) = $limit;
2036 $summary = "(limit $max in {$period}s)";
2037 $count = $cache->get( $key );
2039 if ( $count && $count >= $max ) {
2040 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2041 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2044 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2045 if ( $incrBy > 0 ) {
2046 $cache->add( $key, 0, intval( $period ) ); // first ping
2049 if ( $incrBy > 0 ) {
2050 $cache->incrWithInit( $key, (int)$period, $incrBy, $incrBy );
2058 * Check if user is blocked
2060 * @deprecated since 1.34, use User::getBlock() or
2061 * PermissionManager::isBlockedFrom() or
2062 * PermissionManager::userCan() instead.
2064 * @param bool $fromReplica Whether to check the replica DB instead of
2065 * the master. Hacked from false due to horrible probs on site.
2066 * @return bool True if blocked, false otherwise
2068 public function isBlocked( $fromReplica = true ) {
2069 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2070 $this->getBlock()->appliesToRight( 'edit' );
2074 * Get the block affecting the user, or null if the user is not blocked
2076 * @param bool $fromReplica Whether to check the replica DB instead of the master
2077 * @return AbstractBlock|null
2079 public function getBlock( $fromReplica = true ) {
2080 $this->getBlockedStatus( $fromReplica );
2081 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2085 * Check if user is blocked from editing a particular article
2087 * @param Title $title Title to check
2088 * @param bool $fromReplica Whether to check the replica DB instead of the master
2091 * @deprecated since 1.33,
2092 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2095 public function isBlockedFrom( $title, $fromReplica = false ) {
2096 return MediaWikiServices
::getInstance()->getPermissionManager()
2097 ->isBlockedFrom( $this, $title, $fromReplica );
2101 * If user is blocked, return the name of the user who placed the block
2102 * @return string Name of blocker
2104 public function blockedBy() {
2105 $this->getBlockedStatus();
2106 return $this->mBlockedby
;
2110 * If user is blocked, return the specified reason for the block
2111 * @return string Blocking reason
2113 public function blockedFor() {
2114 $this->getBlockedStatus();
2115 return $this->mBlockreason
;
2119 * If user is blocked, return the ID for the block
2120 * @return int Block ID
2122 public function getBlockId() {
2123 $this->getBlockedStatus();
2124 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2128 * Check if user is blocked on all wikis.
2129 * Do not use for actual edit permission checks!
2130 * This is intended for quick UI checks.
2132 * @param string $ip IP address, uses current client if none given
2133 * @return bool True if blocked, false otherwise
2135 public function isBlockedGlobally( $ip = '' ) {
2136 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2140 * Check if user is blocked on all wikis.
2141 * Do not use for actual edit permission checks!
2142 * This is intended for quick UI checks.
2144 * @param string $ip IP address, uses current client if none given
2145 * @return AbstractBlock|null Block object if blocked, null otherwise
2146 * @throws FatalError
2147 * @throws MWException
2149 public function getGlobalBlock( $ip = '' ) {
2150 if ( $this->mGlobalBlock
!== null ) {
2151 return $this->mGlobalBlock ?
: null;
2153 // User is already an IP?
2154 if ( IP
::isIPAddress( $this->getName() ) ) {
2155 $ip = $this->getName();
2157 $ip = $this->getRequest()->getIP();
2159 // Avoid PHP 7.1 warning of passing $this by reference
2163 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2165 if ( $blocked && $block === null ) {
2166 // back-compat: UserIsBlockedGlobally didn't have $block param first
2167 $block = new SystemBlock( [
2169 'systemBlock' => 'global-block'
2173 $this->mGlobalBlock
= $blocked ?
$block : false;
2174 return $this->mGlobalBlock ?
: null;
2178 * Check if user account is locked
2180 * @return bool True if locked, false otherwise
2182 public function isLocked() {
2183 if ( $this->mLocked
!== null ) {
2184 return $this->mLocked
;
2187 $this->mLocked
= false;
2188 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2189 return $this->mLocked
;
2193 * Check if user account is hidden
2195 * @return bool True if hidden, false otherwise
2197 public function isHidden() {
2198 if ( $this->mHideName
!== null ) {
2199 return (bool)$this->mHideName
;
2201 $this->getBlockedStatus();
2202 if ( !$this->mHideName
) {
2204 $this->mHideName
= false;
2205 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2207 return (bool)$this->mHideName
;
2211 * Get the user's ID.
2212 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2214 public function getId() {
2215 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2216 // Special case, we know the user is anonymous
2220 if ( !$this->isItemLoaded( 'id' ) ) {
2221 // Don't load if this was initialized from an ID
2225 return (int)$this->mId
;
2229 * Set the user and reload all fields according to a given ID
2230 * @param int $v User ID to reload
2232 public function setId( $v ) {
2234 $this->clearInstanceCache( 'id' );
2238 * Get the user name, or the IP of an anonymous user
2239 * @return string User's name or IP address
2241 public function getName() {
2242 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2243 // Special case optimisation
2244 return $this->mName
;
2248 if ( $this->mName
=== false ) {
2250 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2253 return $this->mName
;
2257 * Set the user name.
2259 * This does not reload fields from the database according to the given
2260 * name. Rather, it is used to create a temporary "nonexistent user" for
2261 * later addition to the database. It can also be used to set the IP
2262 * address for an anonymous user to something other than the current
2265 * @note User::newFromName() has roughly the same function, when the named user
2267 * @param string $str New user name to set
2269 public function setName( $str ) {
2271 $this->mName
= $str;
2275 * Get the user's actor ID.
2277 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2278 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2280 public function getActorId( IDatabase
$dbw = null ) {
2281 global $wgActorTableSchemaMigrationStage;
2283 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2284 // but it does little harm and might be needed for write callers loading a User.
2285 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2289 if ( !$this->isItemLoaded( 'actor' ) ) {
2293 // Currently $this->mActorId might be null if $this was loaded from a
2294 // cache entry that was written when $wgActorTableSchemaMigrationStage
2295 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2296 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2297 // has been removed), that condition may be removed.
2298 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2300 'actor_user' => $this->getId() ?
: null,
2301 'actor_name' => (string)$this->getName(),
2304 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2305 throw new CannotCreateActorException(
2306 'Cannot create an actor for a usable name that is not an existing user'
2309 if ( $q['actor_name'] === '' ) {
2310 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2312 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2313 if ( $dbw->affectedRows() ) {
2314 $this->mActorId
= (int)$dbw->insertId();
2317 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2318 $this->mActorId
= (int)$dbw->selectField(
2323 [ 'LOCK IN SHARE MODE' ]
2325 if ( !$this->mActorId
) {
2326 throw new CannotCreateActorException(
2327 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2331 $this->invalidateCache();
2333 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2334 $db = wfGetDB( $index );
2335 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2337 $this->setItemLoaded( 'actor' );
2340 return (int)$this->mActorId
;
2344 * Get the user's name escaped by underscores.
2345 * @return string Username escaped by underscores.
2347 public function getTitleKey() {
2348 return str_replace( ' ', '_', $this->getName() );
2352 * Check if the user has new messages.
2353 * @return bool True if the user has new messages
2355 public function getNewtalk() {
2358 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2359 if ( $this->mNewtalk
=== -1 ) {
2360 $this->mNewtalk
= false; # reset talk page status
2362 // Check memcached separately for anons, who have no
2363 // entire User object stored in there.
2364 if ( !$this->mId
) {
2365 global $wgDisableAnonTalk;
2366 if ( $wgDisableAnonTalk ) {
2367 // Anon newtalk disabled by configuration.
2368 $this->mNewtalk
= false;
2370 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2373 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2377 return (bool)$this->mNewtalk
;
2381 * Return the data needed to construct links for new talk page message
2382 * alerts. If there are new messages, this will return an associative array
2383 * with the following data:
2384 * wiki: The database name of the wiki
2385 * link: Root-relative link to the user's talk page
2386 * rev: The last talk page revision that the user has seen or null. This
2387 * is useful for building diff links.
2388 * If there are no new messages, it returns an empty array.
2389 * @note This function was designed to accomodate multiple talk pages, but
2390 * currently only returns a single link and revision.
2393 public function getNewMessageLinks() {
2394 // Avoid PHP 7.1 warning of passing $this by reference
2397 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2401 if ( !$this->getNewtalk() ) {
2404 $utp = $this->getTalkPage();
2405 $dbr = wfGetDB( DB_REPLICA
);
2406 // Get the "last viewed rev" timestamp from the oldest message notification
2407 $timestamp = $dbr->selectField( 'user_newtalk',
2408 'MIN(user_last_timestamp)',
2409 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2411 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2414 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2415 'link' => $utp->getLocalURL(),
2422 * Get the revision ID for the last talk page revision viewed by the talk
2424 * @return int|null Revision ID or null
2426 public function getNewMessageRevisionId() {
2427 $newMessageRevisionId = null;
2428 $newMessageLinks = $this->getNewMessageLinks();
2430 // Note: getNewMessageLinks() never returns more than a single link
2431 // and it is always for the same wiki, but we double-check here in
2432 // case that changes some time in the future.
2433 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2434 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2435 && $newMessageLinks[0]['rev']
2437 /** @var Revision $newMessageRevision */
2438 $newMessageRevision = $newMessageLinks[0]['rev'];
2439 $newMessageRevisionId = $newMessageRevision->getId();
2442 return $newMessageRevisionId;
2446 * Internal uncached check for new messages
2449 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2450 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2451 * @return bool True if the user has new messages
2453 protected function checkNewtalk( $field, $id ) {
2454 $dbr = wfGetDB( DB_REPLICA
);
2456 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2458 return $ok !== false;
2462 * Add or update the new messages flag
2463 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2464 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2465 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2466 * @return bool True if successful, false otherwise
2468 protected function updateNewtalk( $field, $id, $curRev = null ) {
2469 // Get timestamp of the talk page revision prior to the current one
2470 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2471 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2472 // Mark the user as having new messages since this revision
2473 $dbw = wfGetDB( DB_MASTER
);
2474 $dbw->insert( 'user_newtalk',
2475 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2478 if ( $dbw->affectedRows() ) {
2479 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2483 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2488 * Clear the new messages flag for the given user
2489 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2490 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2491 * @return bool True if successful, false otherwise
2493 protected function deleteNewtalk( $field, $id ) {
2494 $dbw = wfGetDB( DB_MASTER
);
2495 $dbw->delete( 'user_newtalk',
2498 if ( $dbw->affectedRows() ) {
2499 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2503 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2508 * Update the 'You have new messages!' status.
2509 * @param bool $val Whether the user has new messages
2510 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2511 * page. Ignored if null or !$val.
2513 public function setNewtalk( $val, $curRev = null ) {
2514 if ( wfReadOnly() ) {
2519 $this->mNewtalk
= $val;
2521 if ( $this->isAnon() ) {
2523 $id = $this->getName();
2526 $id = $this->getId();
2530 $changed = $this->updateNewtalk( $field, $id, $curRev );
2532 $changed = $this->deleteNewtalk( $field, $id );
2536 $this->invalidateCache();
2541 * Generate a current or new-future timestamp to be stored in the
2542 * user_touched field when we update things.
2544 * @return string Timestamp in TS_MW format
2546 private function newTouchedTimestamp() {
2548 if ( $this->mTouched
) {
2549 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2552 return wfTimestamp( TS_MW
, $time );
2556 * Clear user data from memcached
2558 * Use after applying updates to the database; caller's
2559 * responsibility to update user_touched if appropriate.
2561 * Called implicitly from invalidateCache() and saveSettings().
2563 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2565 public function clearSharedCache( $mode = 'refresh' ) {
2566 if ( !$this->getId() ) {
2570 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2571 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2572 $key = $this->getCacheKey( $cache );
2574 if ( $mode === 'refresh' ) {
2575 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2577 $lb->getConnectionRef( DB_MASTER
)->onTransactionPreCommitOrIdle(
2578 function () use ( $cache, $key ) {
2579 $cache->delete( $key );
2587 * Immediately touch the user data cache for this account
2589 * Calls touch() and removes account data from memcached
2591 public function invalidateCache() {
2593 $this->clearSharedCache( 'changed' );
2597 * Update the "touched" timestamp for the user
2599 * This is useful on various login/logout events when making sure that
2600 * a browser or proxy that has multiple tenants does not suffer cache
2601 * pollution where the new user sees the old users content. The value
2602 * of getTouched() is checked when determining 304 vs 200 responses.
2603 * Unlike invalidateCache(), this preserves the User object cache and
2604 * avoids database writes.
2608 public function touch() {
2609 $id = $this->getId();
2611 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2612 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2613 $cache->touchCheckKey( $key );
2614 $this->mQuickTouched
= null;
2619 * Validate the cache for this account.
2620 * @param string $timestamp A timestamp in TS_MW format
2623 public function validateCache( $timestamp ) {
2624 return ( $timestamp >= $this->getTouched() );
2628 * Get the user touched timestamp
2630 * Use this value only to validate caches via inequalities
2631 * such as in the case of HTTP If-Modified-Since response logic
2633 * @return string TS_MW Timestamp
2635 public function getTouched() {
2639 if ( $this->mQuickTouched
=== null ) {
2640 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2641 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2643 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2646 return max( $this->mTouched
, $this->mQuickTouched
);
2649 return $this->mTouched
;
2653 * Get the user_touched timestamp field (time of last DB updates)
2654 * @return string TS_MW Timestamp
2657 public function getDBTouched() {
2660 return $this->mTouched
;
2664 * Set the password and reset the random token.
2665 * Calls through to authentication plugin if necessary;
2666 * will have no effect if the auth plugin refuses to
2667 * pass the change through or if the legal password
2670 * As a special case, setting the password to null
2671 * wipes it, so the account cannot be logged in until
2672 * a new password is set, for instance via e-mail.
2674 * @deprecated since 1.27, use AuthManager instead
2675 * @param string $str New password to set
2676 * @throws PasswordError On failure
2679 public function setPassword( $str ) {
2680 wfDeprecated( __METHOD__
, '1.27' );
2681 return $this->setPasswordInternal( $str );
2685 * Set the password and reset the random token unconditionally.
2687 * @deprecated since 1.27, use AuthManager instead
2688 * @param string|null $str New password to set or null to set an invalid
2689 * password hash meaning that the user will not be able to log in
2690 * through the web interface.
2692 public function setInternalPassword( $str ) {
2693 wfDeprecated( __METHOD__
, '1.27' );
2694 $this->setPasswordInternal( $str );
2698 * Actually set the password and such
2699 * @since 1.27 cannot set a password for a user not in the database
2700 * @param string|null $str New password to set or null to set an invalid
2701 * password hash meaning that the user will not be able to log in
2702 * through the web interface.
2703 * @return bool Success
2705 private function setPasswordInternal( $str ) {
2706 $manager = AuthManager
::singleton();
2708 // If the user doesn't exist yet, fail
2709 if ( !$manager->userExists( $this->getName() ) ) {
2710 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2713 $status = $this->changeAuthenticationData( [
2714 'username' => $this->getName(),
2718 if ( !$status->isGood() ) {
2719 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2720 ->info( __METHOD__
. ': Password change rejected: '
2721 . $status->getWikiText( null, null, 'en' ) );
2725 $this->setOption( 'watchlisttoken', false );
2726 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2732 * Changes credentials of the user.
2734 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2735 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2736 * e.g. when no provider handled the change.
2738 * @param array $data A set of authentication data in fieldname => value format. This is the
2739 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2743 public function changeAuthenticationData( array $data ) {
2744 $manager = AuthManager
::singleton();
2745 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2746 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2748 $status = Status
::newGood( 'ignored' );
2749 foreach ( $reqs as $req ) {
2750 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2752 if ( $status->getValue() === 'ignored' ) {
2753 $status->warning( 'authenticationdatachange-ignored' );
2756 if ( $status->isGood() ) {
2757 foreach ( $reqs as $req ) {
2758 $manager->changeAuthenticationData( $req );
2765 * Get the user's current token.
2766 * @param bool $forceCreation Force the generation of a new token if the
2767 * user doesn't have one (default=true for backwards compatibility).
2768 * @return string|null Token
2770 public function getToken( $forceCreation = true ) {
2771 global $wgAuthenticationTokenVersion;
2774 if ( !$this->mToken
&& $forceCreation ) {
2778 if ( !$this->mToken
) {
2779 // The user doesn't have a token, return null to indicate that.
2783 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2784 // We return a random value here so existing token checks are very
2786 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2789 if ( $wgAuthenticationTokenVersion === null ) {
2790 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2791 return $this->mToken
;
2794 // $wgAuthenticationTokenVersion in use, so hmac it.
2795 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2797 // The raw hash can be overly long. Shorten it up.
2798 $len = max( 32, self
::TOKEN_LENGTH
);
2799 if ( strlen( $ret ) < $len ) {
2800 // Should never happen, even md5 is 128 bits
2801 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2804 return substr( $ret, -$len );
2808 * Set the random token (used for persistent authentication)
2809 * Called from loadDefaults() among other places.
2811 * @param string|bool $token If specified, set the token to this value
2813 public function setToken( $token = false ) {
2815 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2816 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2817 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2818 } elseif ( !$token ) {
2819 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2821 $this->mToken
= $token;
2826 * Set the password for a password reminder or new account email
2828 * @deprecated Removed in 1.27. Use PasswordReset instead.
2829 * @param string $str New password to set or null to set an invalid
2830 * password hash meaning that the user will not be able to use it
2831 * @param bool $throttle If true, reset the throttle timestamp to the present
2833 public function setNewpassword( $str, $throttle = true ) {
2834 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2838 * Get the user's e-mail address
2839 * @return string User's email address
2841 public function getEmail() {
2843 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2844 return $this->mEmail
;
2848 * Get the timestamp of the user's e-mail authentication
2849 * @return string TS_MW timestamp
2851 public function getEmailAuthenticationTimestamp() {
2853 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2854 return $this->mEmailAuthenticated
;
2858 * Set the user's e-mail address
2859 * @param string $str New e-mail address
2861 public function setEmail( $str ) {
2863 if ( $str == $this->mEmail
) {
2866 $this->invalidateEmail();
2867 $this->mEmail
= $str;
2868 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2872 * Set the user's e-mail address and a confirmation mail if needed.
2875 * @param string $str New e-mail address
2878 public function setEmailWithConfirmation( $str ) {
2879 global $wgEnableEmail, $wgEmailAuthentication;
2881 if ( !$wgEnableEmail ) {
2882 return Status
::newFatal( 'emaildisabled' );
2885 $oldaddr = $this->getEmail();
2886 if ( $str === $oldaddr ) {
2887 return Status
::newGood( true );
2890 $type = $oldaddr != '' ?
'changed' : 'set';
2891 $notificationResult = null;
2893 if ( $wgEmailAuthentication && $type === 'changed' ) {
2894 // Send the user an email notifying the user of the change in registered
2895 // email address on their previous email address
2896 $change = $str != '' ?
'changed' : 'removed';
2897 $notificationResult = $this->sendMail(
2898 wfMessage( 'notificationemail_subject_' . $change )->text(),
2899 wfMessage( 'notificationemail_body_' . $change,
2900 $this->getRequest()->getIP(),
2906 $this->setEmail( $str );
2908 if ( $str !== '' && $wgEmailAuthentication ) {
2909 // Send a confirmation request to the new address if needed
2910 $result = $this->sendConfirmationMail( $type );
2912 if ( $notificationResult !== null ) {
2913 $result->merge( $notificationResult );
2916 if ( $result->isGood() ) {
2917 // Say to the caller that a confirmation and notification mail has been sent
2918 $result->value
= 'eauth';
2921 $result = Status
::newGood( true );
2928 * Get the user's real name
2929 * @return string User's real name
2931 public function getRealName() {
2932 if ( !$this->isItemLoaded( 'realname' ) ) {
2936 return $this->mRealName
;
2940 * Set the user's real name
2941 * @param string $str New real name
2943 public function setRealName( $str ) {
2945 $this->mRealName
= $str;
2949 * Get the user's current setting for a given option.
2951 * @param string $oname The option to check
2952 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2953 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2954 * @return string|array|int|null User's current value for the option
2955 * @see getBoolOption()
2956 * @see getIntOption()
2958 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2959 global $wgHiddenPrefs;
2960 $this->loadOptions();
2962 # We want 'disabled' preferences to always behave as the default value for
2963 # users, even if they have set the option explicitly in their settings (ie they
2964 # set it, and then it was disabled removing their ability to change it). But
2965 # we don't want to erase the preferences in the database in case the preference
2966 # is re-enabled again. So don't touch $mOptions, just override the returned value
2967 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2968 return self
::getDefaultOption( $oname );
2971 if ( array_key_exists( $oname, $this->mOptions
) ) {
2972 return $this->mOptions
[$oname];
2975 return $defaultOverride;
2979 * Get all user's options
2981 * @param int $flags Bitwise combination of:
2982 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2983 * to the default value. (Since 1.25)
2986 public function getOptions( $flags = 0 ) {
2987 global $wgHiddenPrefs;
2988 $this->loadOptions();
2989 $options = $this->mOptions
;
2991 # We want 'disabled' preferences to always behave as the default value for
2992 # users, even if they have set the option explicitly in their settings (ie they
2993 # set it, and then it was disabled removing their ability to change it). But
2994 # we don't want to erase the preferences in the database in case the preference
2995 # is re-enabled again. So don't touch $mOptions, just override the returned value
2996 foreach ( $wgHiddenPrefs as $pref ) {
2997 $default = self
::getDefaultOption( $pref );
2998 if ( $default !== null ) {
2999 $options[$pref] = $default;
3003 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3004 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3011 * Get the user's current setting for a given option, as a boolean value.
3013 * @param string $oname The option to check
3014 * @return bool User's current value for the option
3017 public function getBoolOption( $oname ) {
3018 return (bool)$this->getOption( $oname );
3022 * Get the user's current setting for a given option, as an integer value.
3024 * @param string $oname The option to check
3025 * @param int $defaultOverride A default value returned if the option does not exist
3026 * @return int User's current value for the option
3029 public function getIntOption( $oname, $defaultOverride = 0 ) {
3030 $val = $this->getOption( $oname );
3032 $val = $defaultOverride;
3034 return intval( $val );
3038 * Set the given option for a user.
3040 * You need to call saveSettings() to actually write to the database.
3042 * @param string $oname The option to set
3043 * @param mixed $val New value to set
3045 public function setOption( $oname, $val ) {
3046 $this->loadOptions();
3048 // Explicitly NULL values should refer to defaults
3049 if ( is_null( $val ) ) {
3050 $val = self
::getDefaultOption( $oname );
3053 $this->mOptions
[$oname] = $val;
3057 * Get a token stored in the preferences (like the watchlist one),
3058 * resetting it if it's empty (and saving changes).
3060 * @param string $oname The option name to retrieve the token from
3061 * @return string|bool User's current value for the option, or false if this option is disabled.
3062 * @see resetTokenFromOption()
3064 * @deprecated since 1.26 Applications should use the OAuth extension
3066 public function getTokenFromOption( $oname ) {
3067 global $wgHiddenPrefs;
3069 $id = $this->getId();
3070 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3074 $token = $this->getOption( $oname );
3076 // Default to a value based on the user token to avoid space
3077 // wasted on storing tokens for all users. When this option
3078 // is set manually by the user, only then is it stored.
3079 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3086 * Reset a token stored in the preferences (like the watchlist one).
3087 * *Does not* save user's preferences (similarly to setOption()).
3089 * @param string $oname The option name to reset the token in
3090 * @return string|bool New token value, or false if this option is disabled.
3091 * @see getTokenFromOption()
3094 public function resetTokenFromOption( $oname ) {
3095 global $wgHiddenPrefs;
3096 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3100 $token = MWCryptRand
::generateHex( 40 );
3101 $this->setOption( $oname, $token );
3106 * Return a list of the types of user options currently returned by
3107 * User::getOptionKinds().
3109 * Currently, the option kinds are:
3110 * - 'registered' - preferences which are registered in core MediaWiki or
3111 * by extensions using the UserGetDefaultOptions hook.
3112 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3113 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3114 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3115 * be used by user scripts.
3116 * - 'special' - "preferences" that are not accessible via User::getOptions
3117 * or User::setOptions.
3118 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3119 * These are usually legacy options, removed in newer versions.
3121 * The API (and possibly others) use this function to determine the possible
3122 * option types for validation purposes, so make sure to update this when a
3123 * new option kind is added.
3125 * @see User::getOptionKinds
3126 * @return array Option kinds
3128 public static function listOptionKinds() {
3131 'registered-multiselect',
3132 'registered-checkmatrix',
3140 * Return an associative array mapping preferences keys to the kind of a preference they're
3141 * used for. Different kinds are handled differently when setting or reading preferences.
3143 * See User::listOptionKinds for the list of valid option types that can be provided.
3145 * @see User::listOptionKinds
3146 * @param IContextSource $context
3147 * @param array|null $options Assoc. array with options keys to check as keys.
3148 * Defaults to $this->mOptions.
3149 * @return array The key => kind mapping data
3151 public function getOptionKinds( IContextSource
$context, $options = null ) {
3152 $this->loadOptions();
3153 if ( $options === null ) {
3154 $options = $this->mOptions
;
3157 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3158 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3161 // Pull out the "special" options, so they don't get converted as
3162 // multiselect or checkmatrix.
3163 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3164 foreach ( $specialOptions as $name => $value ) {
3165 unset( $prefs[$name] );
3168 // Multiselect and checkmatrix options are stored in the database with
3169 // one key per option, each having a boolean value. Extract those keys.
3170 $multiselectOptions = [];
3171 foreach ( $prefs as $name => $info ) {
3172 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3173 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3174 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3175 $prefix = $info['prefix'] ??
$name;
3177 foreach ( $opts as $value ) {
3178 $multiselectOptions["$prefix$value"] = true;
3181 unset( $prefs[$name] );
3184 $checkmatrixOptions = [];
3185 foreach ( $prefs as $name => $info ) {
3186 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3187 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3188 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3189 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3190 $prefix = $info['prefix'] ??
$name;
3192 foreach ( $columns as $column ) {
3193 foreach ( $rows as $row ) {
3194 $checkmatrixOptions["$prefix$column-$row"] = true;
3198 unset( $prefs[$name] );
3202 // $value is ignored
3203 foreach ( $options as $key => $value ) {
3204 if ( isset( $prefs[$key] ) ) {
3205 $mapping[$key] = 'registered';
3206 } elseif ( isset( $multiselectOptions[$key] ) ) {
3207 $mapping[$key] = 'registered-multiselect';
3208 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3209 $mapping[$key] = 'registered-checkmatrix';
3210 } elseif ( isset( $specialOptions[$key] ) ) {
3211 $mapping[$key] = 'special';
3212 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3213 $mapping[$key] = 'userjs';
3215 $mapping[$key] = 'unused';
3223 * Reset certain (or all) options to the site defaults
3225 * The optional parameter determines which kinds of preferences will be reset.
3226 * Supported values are everything that can be reported by getOptionKinds()
3227 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3229 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3230 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3231 * for backwards-compatibility.
3232 * @param IContextSource|null $context Context source used when $resetKinds
3233 * does not contain 'all', passed to getOptionKinds().
3234 * Defaults to RequestContext::getMain() when null.
3236 public function resetOptions(
3237 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3238 IContextSource
$context = null
3241 $defaultOptions = self
::getDefaultOptions();
3243 if ( !is_array( $resetKinds ) ) {
3244 $resetKinds = [ $resetKinds ];
3247 if ( in_array( 'all', $resetKinds ) ) {
3248 $newOptions = $defaultOptions;
3250 if ( $context === null ) {
3251 $context = RequestContext
::getMain();
3254 $optionKinds = $this->getOptionKinds( $context );
3255 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3258 // Use default values for the options that should be deleted, and
3259 // copy old values for the ones that shouldn't.
3260 foreach ( $this->mOptions
as $key => $value ) {
3261 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3262 if ( array_key_exists( $key, $defaultOptions ) ) {
3263 $newOptions[$key] = $defaultOptions[$key];
3266 $newOptions[$key] = $value;
3271 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3273 $this->mOptions
= $newOptions;
3274 $this->mOptionsLoaded
= true;
3278 * Get the user's preferred date format.
3279 * @return string User's preferred date format
3281 public function getDatePreference() {
3282 // Important migration for old data rows
3283 if ( is_null( $this->mDatePreference
) ) {
3285 $value = $this->getOption( 'date' );
3286 $map = $wgLang->getDatePreferenceMigrationMap();
3287 if ( isset( $map[$value] ) ) {
3288 $value = $map[$value];
3290 $this->mDatePreference
= $value;
3292 return $this->mDatePreference
;
3296 * Determine based on the wiki configuration and the user's options,
3297 * whether this user must be over HTTPS no matter what.
3301 public function requiresHTTPS() {
3302 global $wgSecureLogin;
3303 if ( !$wgSecureLogin ) {
3307 $https = $this->getBoolOption( 'prefershttps' );
3308 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3310 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3317 * Get the user preferred stub threshold
3321 public function getStubThreshold() {
3322 global $wgMaxArticleSize; # Maximum article size, in Kb
3323 $threshold = $this->getIntOption( 'stubthreshold' );
3324 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3325 // If they have set an impossible value, disable the preference
3326 // so we can use the parser cache again.
3333 * Get the permissions this user has.
3334 * @return string[] permission names
3336 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3337 * ->getUserPermissions(..) instead
3340 public function getRights() {
3341 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3345 * Get the list of explicit group memberships this user has.
3346 * The implicit * and user groups are not included.
3348 * @return string[] Array of internal group names (sorted since 1.33)
3350 public function getGroups() {
3352 $this->loadGroups();
3353 return array_keys( $this->mGroupMemberships
);
3357 * Get the list of explicit group memberships this user has, stored as
3358 * UserGroupMembership objects. Implicit groups are not included.
3360 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3363 public function getGroupMemberships() {
3365 $this->loadGroups();
3366 return $this->mGroupMemberships
;
3370 * Get the list of implicit group memberships this user has.
3371 * This includes all explicit groups, plus 'user' if logged in,
3372 * '*' for all accounts, and autopromoted groups
3373 * @param bool $recache Whether to avoid the cache
3374 * @return array Array of String internal group names
3376 public function getEffectiveGroups( $recache = false ) {
3377 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3378 $this->mEffectiveGroups
= array_unique( array_merge(
3379 $this->getGroups(), // explicit groups
3380 $this->getAutomaticGroups( $recache ) // implicit groups
3382 // Avoid PHP 7.1 warning of passing $this by reference
3384 // Hook for additional groups
3385 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3386 // Force reindexation of groups when a hook has unset one of them
3387 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3389 return $this->mEffectiveGroups
;
3393 * Get the list of implicit group memberships this user has.
3394 * This includes 'user' if logged in, '*' for all accounts,
3395 * and autopromoted groups
3396 * @param bool $recache Whether to avoid the cache
3397 * @return array Array of String internal group names
3399 public function getAutomaticGroups( $recache = false ) {
3400 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3401 $this->mImplicitGroups
= [ '*' ];
3402 if ( $this->getId() ) {
3403 $this->mImplicitGroups
[] = 'user';
3405 $this->mImplicitGroups
= array_unique( array_merge(
3406 $this->mImplicitGroups
,
3407 Autopromote
::getAutopromoteGroups( $this )
3411 // Assure data consistency with rights/groups,
3412 // as getEffectiveGroups() depends on this function
3413 $this->mEffectiveGroups
= null;
3416 return $this->mImplicitGroups
;
3420 * Returns the groups the user has belonged to.
3422 * The user may still belong to the returned groups. Compare with getGroups().
3424 * The function will not return groups the user had belonged to before MW 1.17
3426 * @return array Names of the groups the user has belonged to.
3428 public function getFormerGroups() {
3431 if ( is_null( $this->mFormerGroups
) ) {
3432 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3433 ?
wfGetDB( DB_MASTER
)
3434 : wfGetDB( DB_REPLICA
);
3435 $res = $db->select( 'user_former_groups',
3437 [ 'ufg_user' => $this->mId
],
3439 $this->mFormerGroups
= [];
3440 foreach ( $res as $row ) {
3441 $this->mFormerGroups
[] = $row->ufg_group
;
3445 return $this->mFormerGroups
;
3449 * Get the user's edit count.
3450 * @return int|null Null for anonymous users
3452 public function getEditCount() {
3453 if ( !$this->getId() ) {
3457 if ( $this->mEditCount
=== null ) {
3458 /* Populate the count, if it has not been populated yet */
3459 $dbr = wfGetDB( DB_REPLICA
);
3460 // check if the user_editcount field has been initialized
3461 $count = $dbr->selectField(
3462 'user', 'user_editcount',
3463 [ 'user_id' => $this->mId
],
3467 if ( $count === null ) {
3468 // it has not been initialized. do so.
3469 $count = $this->initEditCountInternal( $dbr );
3471 $this->mEditCount
= $count;
3473 return (int)$this->mEditCount
;
3477 * Add the user to the given group. This takes immediate effect.
3478 * If the user is already in the group, the expiry time will be updated to the new
3479 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3482 * @param string $group Name of the group to add
3483 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3484 * wfTimestamp(), or null if the group assignment should not expire
3487 public function addGroup( $group, $expiry = null ) {
3489 $this->loadGroups();
3492 $expiry = wfTimestamp( TS_MW
, $expiry );
3495 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3499 // create the new UserGroupMembership and put it in the DB
3500 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3501 if ( !$ugm->insert( true ) ) {
3505 $this->mGroupMemberships
[$group] = $ugm;
3507 // Refresh the groups caches, and clear the rights cache so it will be
3508 // refreshed on the next call to $this->getRights().
3509 $this->getEffectiveGroups( true );
3510 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3511 $this->invalidateCache();
3517 * Remove the user from the given group.
3518 * This takes immediate effect.
3519 * @param string $group Name of the group to remove
3522 public function removeGroup( $group ) {
3525 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3529 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3530 // delete the membership entry
3531 if ( !$ugm ||
!$ugm->delete() ) {
3535 $this->loadGroups();
3536 unset( $this->mGroupMemberships
[$group] );
3538 // Refresh the groups caches, and clear the rights cache so it will be
3539 // refreshed on the next call to $this->getRights().
3540 $this->getEffectiveGroups( true );
3541 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3542 $this->invalidateCache();
3548 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3549 * only this new name and not the old isLoggedIn() variant.
3551 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3552 * anonymous or has no local account (which can happen when importing). This is equivalent to
3553 * getId() != 0 and is provided for code readability.
3556 public function isRegistered() {
3557 return $this->getId() != 0;
3561 * Get whether the user is logged in
3564 public function isLoggedIn() {
3565 return $this->isRegistered();
3569 * Get whether the user is anonymous
3572 public function isAnon() {
3573 return !$this->isRegistered();
3577 * @return bool Whether this user is flagged as being a bot role account
3580 public function isBot() {
3581 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3586 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3592 * Check if user is allowed to access a feature / make an action
3594 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3595 * ->getPermissionManager()->userHasAnyRights(...) instead
3597 * @param string $permissions,... Permissions to test
3598 * @return bool True if user is allowed to perform *any* of the given actions
3599 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3601 public function isAllowedAny() {
3602 return MediaWikiServices
::getInstance()
3603 ->getPermissionManager()
3604 ->userHasAnyRight( $this, ...func_get_args() );
3608 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3609 * ->getPermissionManager()->userHasAllRights(...) instead
3610 * @param string $permissions,... Permissions to test
3611 * @return bool True if the user is allowed to perform *all* of the given actions
3612 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3614 public function isAllowedAll() {
3615 return MediaWikiServices
::getInstance()
3616 ->getPermissionManager()
3617 ->userHasAllRights( $this, ...func_get_args() );
3621 * Internal mechanics of testing a permission
3623 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3624 * ->getPermissionManager()->userHasRight(...) instead
3626 * @param string $action
3630 public function isAllowed( $action = '' ) {
3631 return MediaWikiServices
::getInstance()->getPermissionManager()
3632 ->userHasRight( $this, $action );
3636 * Check whether to enable recent changes patrol features for this user
3637 * @return bool True or false
3639 public function useRCPatrol() {
3640 global $wgUseRCPatrol;
3641 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3645 * Check whether to enable new pages patrol features for this user
3646 * @return bool True or false
3648 public function useNPPatrol() {
3649 global $wgUseRCPatrol, $wgUseNPPatrol;
3651 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3652 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3657 * Check whether to enable new files patrol features for this user
3658 * @return bool True or false
3660 public function useFilePatrol() {
3661 global $wgUseRCPatrol, $wgUseFilePatrol;
3663 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3664 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3669 * Get the WebRequest object to use with this object
3671 * @return WebRequest
3673 public function getRequest() {
3674 if ( $this->mRequest
) {
3675 return $this->mRequest
;
3683 * Check the watched status of an article.
3684 * @since 1.22 $checkRights parameter added
3685 * @param Title $title Title of the article to look at
3686 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3687 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3690 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3691 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3692 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3699 * @since 1.22 $checkRights parameter added
3700 * @param Title $title Title of the article to look at
3701 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3702 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3704 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3705 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3706 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3708 [ $title->getSubjectPage(), $title->getTalkPage() ]
3711 $this->invalidateCache();
3715 * Stop watching an article.
3716 * @since 1.22 $checkRights parameter added
3717 * @param Title $title Title of the article to look at
3718 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3719 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3721 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3722 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3723 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3724 $store->removeWatch( $this, $title->getSubjectPage() );
3725 $store->removeWatch( $this, $title->getTalkPage() );
3727 $this->invalidateCache();
3731 * Clear the user's notification timestamp for the given title.
3732 * If e-notif e-mails are on, they will receive notification mails on
3733 * the next change of the page if it's watched etc.
3734 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3735 * @param Title &$title Title of the article to look at
3736 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3738 public function clearNotification( &$title, $oldid = 0 ) {
3739 global $wgUseEnotif, $wgShowUpdatedMarker;
3741 // Do nothing if the database is locked to writes
3742 if ( wfReadOnly() ) {
3746 // Do nothing if not allowed to edit the watchlist
3747 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3751 // If we're working on user's talk page, we should update the talk page message indicator
3752 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3753 // Avoid PHP 7.1 warning of passing $this by reference
3755 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3759 // Try to update the DB post-send and only if needed...
3760 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3761 if ( !$this->getNewtalk() ) {
3762 return; // no notifications to clear
3765 // Delete the last notifications (they stack up)
3766 $this->setNewtalk( false );
3768 // If there is a new, unseen, revision, use its timestamp
3770 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3773 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3778 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3782 if ( $this->isAnon() ) {
3783 // Nothing else to do...
3787 // Only update the timestamp if the page is being watched.
3788 // The query to find out if it is watched is cached both in memcached and per-invocation,
3789 // and when it does have to be executed, it can be on a replica DB
3790 // If this is the user's newtalk page, we always update the timestamp
3792 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3796 MediaWikiServices
::getInstance()->getWatchedItemStore()
3797 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3801 * Resets all of the given user's page-change notification timestamps.
3802 * If e-notif e-mails are on, they will receive notification mails on
3803 * the next change of any watched page.
3804 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3806 public function clearAllNotifications() {
3807 global $wgUseEnotif, $wgShowUpdatedMarker;
3808 // Do nothing if not allowed to edit the watchlist
3809 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3813 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3814 $this->setNewtalk( false );
3818 $id = $this->getId();
3823 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3824 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3826 // We also need to clear here the "you have new message" notification for the own
3827 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3831 * Compute experienced level based on edit count and registration date.
3833 * @return string 'newcomer', 'learner', or 'experienced'
3835 public function getExperienceLevel() {
3836 global $wgLearnerEdits,
3837 $wgExperiencedUserEdits,
3838 $wgLearnerMemberSince,
3839 $wgExperiencedUserMemberSince;
3841 if ( $this->isAnon() ) {
3845 $editCount = $this->getEditCount();
3846 $registration = $this->getRegistration();
3848 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3849 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3851 if ( $editCount < $wgLearnerEdits ||
3852 $registration > $learnerRegistration ) {
3856 if ( $editCount > $wgExperiencedUserEdits &&
3857 $registration <= $experiencedRegistration
3859 return 'experienced';
3866 * Persist this user's session (e.g. set cookies)
3868 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3870 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3871 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3873 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3875 if ( $this->mId
== 0 ) {
3879 $session = $this->getRequest()->getSession();
3880 if ( $request && $session->getRequest() !== $request ) {
3881 $session = $session->sessionWithRequest( $request );
3883 $delay = $session->delaySave();
3885 if ( !$session->getUser()->equals( $this ) ) {
3886 if ( !$session->canSetUser() ) {
3887 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3888 ->warning( __METHOD__
.
3889 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3893 $session->setUser( $this );
3896 $session->setRememberUser( $rememberMe );
3897 if ( $secure !== null ) {
3898 $session->setForceHTTPS( $secure );
3901 $session->persist();
3903 ScopedCallback
::consume( $delay );
3907 * Log this user out.
3909 public function logout() {
3910 // Avoid PHP 7.1 warning of passing $this by reference
3912 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3918 * Clear the user's session, and reset the instance cache.
3921 public function doLogout() {
3922 $session = $this->getRequest()->getSession();
3923 if ( !$session->canSetUser() ) {
3924 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3925 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3926 $error = 'immutable';
3927 } elseif ( !$session->getUser()->equals( $this ) ) {
3928 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3929 ->warning( __METHOD__
.
3930 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3932 // But we still may as well make this user object anon
3933 $this->clearInstanceCache( 'defaults' );
3934 $error = 'wronguser';
3936 $this->clearInstanceCache( 'defaults' );
3937 $delay = $session->delaySave();
3938 $session->unpersist(); // Clear cookies (T127436)
3939 $session->setLoggedOutTimestamp( time() );
3940 $session->setUser( new User
);
3941 $session->set( 'wsUserID', 0 ); // Other code expects this
3942 $session->resetAllTokens();
3943 ScopedCallback
::consume( $delay );
3946 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3947 'event' => 'logout',
3948 'successful' => $error === false,
3949 'status' => $error ?
: 'success',
3954 * Save this user's settings into the database.
3955 * @todo Only rarely do all these fields need to be set!
3957 public function saveSettings() {
3958 if ( wfReadOnly() ) {
3959 // @TODO: caller should deal with this instead!
3960 // This should really just be an exception.
3961 MWExceptionHandler
::logException( new DBExpectedError(
3963 "Could not update user with ID '{$this->mId}'; DB is read-only."
3969 if ( $this->mId
== 0 ) {
3973 // Get a new user_touched that is higher than the old one.
3974 // This will be used for a CAS check as a last-resort safety
3975 // check against race conditions and replica DB lag.
3976 $newTouched = $this->newTouchedTimestamp();
3978 $dbw = wfGetDB( DB_MASTER
);
3979 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3980 global $wgActorTableSchemaMigrationStage;
3982 $dbw->update( 'user',
3984 'user_name' => $this->mName
,
3985 'user_real_name' => $this->mRealName
,
3986 'user_email' => $this->mEmail
,
3987 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3988 'user_touched' => $dbw->timestamp( $newTouched ),
3989 'user_token' => strval( $this->mToken
),
3990 'user_email_token' => $this->mEmailToken
,
3991 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3992 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3993 'user_id' => $this->mId
,
3997 if ( !$dbw->affectedRows() ) {
3998 // Maybe the problem was a missed cache update; clear it to be safe
3999 $this->clearSharedCache( 'refresh' );
4000 // User was changed in the meantime or loaded with stale data
4001 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4002 LoggerFactory
::getInstance( 'preferences' )->warning(
4003 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4004 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4006 throw new MWException( "CAS update failed on user_touched. " .
4007 "The version of the user to be saved is older than the current version."
4011 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4014 [ 'actor_name' => $this->mName
],
4015 [ 'actor_user' => $this->mId
],
4021 $this->mTouched
= $newTouched;
4022 $this->saveOptions();
4024 Hooks
::run( 'UserSaveSettings', [ $this ] );
4025 $this->clearSharedCache( 'changed' );
4026 $this->getUserPage()->purgeSquid();
4030 * If only this user's username is known, and it exists, return the user ID.
4032 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4035 public function idForName( $flags = 0 ) {
4036 $s = trim( $this->getName() );
4041 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4042 ?
wfGetDB( DB_MASTER
)
4043 : wfGetDB( DB_REPLICA
);
4045 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4046 ?
[ 'LOCK IN SHARE MODE' ]
4049 $id = $db->selectField( 'user',
4050 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4056 * Add a user to the database, return the user object
4058 * @param string $name Username to add
4059 * @param array $params Array of Strings Non-default parameters to save to
4060 * the database as user_* fields:
4061 * - email: The user's email address.
4062 * - email_authenticated: The email authentication timestamp.
4063 * - real_name: The user's real name.
4064 * - options: An associative array of non-default options.
4065 * - token: Random authentication token. Do not set.
4066 * - registration: Registration timestamp. Do not set.
4068 * @return User|null User object, or null if the username already exists.
4070 public static function createNew( $name, $params = [] ) {
4071 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4072 if ( isset( $params[$field] ) ) {
4073 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4074 unset( $params[$field] );
4080 $user->setToken(); // init token
4081 if ( isset( $params['options'] ) ) {
4082 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4083 unset( $params['options'] );
4085 $dbw = wfGetDB( DB_MASTER
);
4087 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4090 'user_name' => $name,
4091 'user_password' => $noPass,
4092 'user_newpassword' => $noPass,
4093 'user_email' => $user->mEmail
,
4094 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4095 'user_real_name' => $user->mRealName
,
4096 'user_token' => strval( $user->mToken
),
4097 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4098 'user_editcount' => 0,
4099 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4101 foreach ( $params as $name => $value ) {
4102 $fields["user_$name"] = $value;
4105 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4106 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4107 if ( $dbw->affectedRows() ) {
4108 $newUser = self
::newFromId( $dbw->insertId() );
4109 $newUser->mName
= $fields['user_name'];
4110 $newUser->updateActorId( $dbw );
4111 // Load the user from master to avoid replica lag
4112 $newUser->load( self
::READ_LATEST
);
4121 * Add this existing user object to the database. If the user already
4122 * exists, a fatal status object is returned, and the user object is
4123 * initialised with the data from the database.
4125 * Previously, this function generated a DB error due to a key conflict
4126 * if the user already existed. Many extension callers use this function
4127 * in code along the lines of:
4129 * $user = User::newFromName( $name );
4130 * if ( !$user->isLoggedIn() ) {
4131 * $user->addToDatabase();
4133 * // do something with $user...
4135 * However, this was vulnerable to a race condition (T18020). By
4136 * initialising the user object if the user exists, we aim to support this
4137 * calling sequence as far as possible.
4139 * Note that if the user exists, this function will acquire a write lock,
4140 * so it is still advisable to make the call conditional on isLoggedIn(),
4141 * and to commit the transaction after calling.
4143 * @throws MWException
4146 public function addToDatabase() {
4148 if ( !$this->mToken
) {
4149 $this->setToken(); // init token
4152 if ( !is_string( $this->mName
) ) {
4153 throw new RuntimeException( "User name field is not set." );
4156 $this->mTouched
= $this->newTouchedTimestamp();
4158 $dbw = wfGetDB( DB_MASTER
);
4159 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4160 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4161 $dbw->insert( 'user',
4163 'user_name' => $this->mName
,
4164 'user_password' => $noPass,
4165 'user_newpassword' => $noPass,
4166 'user_email' => $this->mEmail
,
4167 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4168 'user_real_name' => $this->mRealName
,
4169 'user_token' => strval( $this->mToken
),
4170 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4171 'user_editcount' => 0,
4172 'user_touched' => $dbw->timestamp( $this->mTouched
),
4176 if ( !$dbw->affectedRows() ) {
4177 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4178 $this->mId
= $dbw->selectField(
4181 [ 'user_name' => $this->mName
],
4183 [ 'LOCK IN SHARE MODE' ]
4186 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4190 throw new MWException( $fname . ": hit a key conflict attempting " .
4191 "to insert user '{$this->mName}' row, but it was not present in select!" );
4193 return Status
::newFatal( 'userexists' );
4195 $this->mId
= $dbw->insertId();
4196 self
::$idCacheByName[$this->mName
] = $this->mId
;
4197 $this->updateActorId( $dbw );
4199 return Status
::newGood();
4201 if ( !$status->isGood() ) {
4205 // Clear instance cache other than user table data and actor, which is already accurate
4206 $this->clearInstanceCache();
4208 $this->saveOptions();
4209 return Status
::newGood();
4213 * Update the actor ID after an insert
4214 * @param IDatabase $dbw Writable database handle
4216 private function updateActorId( IDatabase
$dbw ) {
4217 global $wgActorTableSchemaMigrationStage;
4219 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4222 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4225 $this->mActorId
= (int)$dbw->insertId();
4230 * If this user is logged-in and blocked,
4231 * block any IP address they've successfully logged in from.
4232 * @return bool A block was spread
4234 public function spreadAnyEditBlock() {
4235 if ( $this->isLoggedIn() && $this->getBlock() ) {
4236 return $this->spreadBlock();
4243 * If this (non-anonymous) user is blocked,
4244 * block the IP address they've successfully logged in from.
4245 * @return bool A block was spread
4247 protected function spreadBlock() {
4248 wfDebug( __METHOD__
. "()\n" );
4250 if ( $this->mId
== 0 ) {
4254 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4255 if ( !$userblock ) {
4259 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4263 * Get whether the user is explicitly blocked from account creation.
4264 * @return bool|AbstractBlock
4266 public function isBlockedFromCreateAccount() {
4267 $this->getBlockedStatus();
4268 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4269 return $this->mBlock
;
4272 # T15611: if the IP address the user is trying to create an account from is
4273 # blocked with createaccount disabled, prevent new account creation there even
4274 # when the user is logged in
4275 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4276 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4277 null, $this->getRequest()->getIP()
4280 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4281 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4282 ?
$this->mBlockedFromCreateAccount
4287 * Get whether the user is blocked from using Special:Emailuser.
4290 public function isBlockedFromEmailuser() {
4291 $this->getBlockedStatus();
4292 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4296 * Get whether the user is blocked from using Special:Upload
4301 public function isBlockedFromUpload() {
4302 $this->getBlockedStatus();
4303 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
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 wfDeprecated( __METHOD__
, '1.27' );
4351 $manager = AuthManager
::singleton();
4352 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4353 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4355 'username' => $this->getName(),
4356 'password' => $password,
4359 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4360 switch ( $res->status
) {
4361 case AuthenticationResponse
::PASS
:
4363 case AuthenticationResponse
::FAIL
:
4364 // Hope it's not a PreAuthenticationProvider that failed...
4365 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4366 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4369 throw new BadMethodCallException(
4370 'AuthManager returned a response unsupported by ' . __METHOD__
4376 * Check if the given clear-text password matches the temporary password
4377 * sent by e-mail for password reset operations.
4379 * @deprecated since 1.27, use AuthManager instead
4380 * @param string $plaintext
4381 * @return bool True if matches, false otherwise
4383 public function checkTemporaryPassword( $plaintext ) {
4384 wfDeprecated( __METHOD__
, '1.27' );
4385 // Can't check the temporary password individually.
4386 return $this->checkPassword( $plaintext );
4390 * Initialize (if necessary) and return a session token value
4391 * which can be used in edit forms to show that the user's
4392 * login credentials aren't being hijacked with a foreign form
4396 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4397 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4398 * @return MediaWiki\Session\Token The new edit token
4400 public function getEditTokenObject( $salt = '', $request = null ) {
4401 if ( $this->isAnon() ) {
4402 return new LoggedOutEditToken();
4406 $request = $this->getRequest();
4408 return $request->getSession()->getToken( $salt );
4412 * Initialize (if necessary) and return a session token value
4413 * which can be used in edit forms to show that the user's
4414 * login credentials aren't being hijacked with a foreign form
4417 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4420 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4421 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4422 * @return string The new edit token
4424 public function getEditToken( $salt = '', $request = null ) {
4425 return $this->getEditTokenObject( $salt, $request )->toString();
4429 * Check given value against the token value stored in the session.
4430 * A match should confirm that the form was submitted from the
4431 * user's own login session, not a form submission from a third-party
4434 * @param string $val Input value to compare
4435 * @param string|array $salt Optional function-specific data for hashing
4436 * @param WebRequest|null $request Object to use or null to use $wgRequest
4437 * @param int|null $maxage Fail tokens older than this, in seconds
4438 * @return bool Whether the token matches
4440 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4441 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4445 * Check given value against the token value stored in the session,
4446 * ignoring the suffix.
4448 * @param string $val Input value to compare
4449 * @param string|array $salt Optional function-specific data for hashing
4450 * @param WebRequest|null $request Object to use or null to use $wgRequest
4451 * @param int|null $maxage Fail tokens older than this, in seconds
4452 * @return bool Whether the token matches
4454 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4455 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4456 return $this->matchEditToken( $val, $salt, $request, $maxage );
4460 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4461 * mail to the user's given address.
4463 * @param string $type Message to send, either "created", "changed" or "set"
4466 public function sendConfirmationMail( $type = 'created' ) {
4468 $expiration = null; // gets passed-by-ref and defined in next line.
4469 $token = $this->confirmationToken( $expiration );
4470 $url = $this->confirmationTokenUrl( $token );
4471 $invalidateURL = $this->invalidationTokenUrl( $token );
4472 $this->saveSettings();
4474 if ( $type == 'created' ||
$type === false ) {
4475 $message = 'confirmemail_body';
4477 } elseif ( $type === true ) {
4478 $message = 'confirmemail_body_changed';
4481 // Messages: confirmemail_body_changed, confirmemail_body_set
4482 $message = 'confirmemail_body_' . $type;
4486 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4487 'body' => wfMessage( $message,
4488 $this->getRequest()->getIP(),
4491 $wgLang->userTimeAndDate( $expiration, $this ),
4493 $wgLang->userDate( $expiration, $this ),
4494 $wgLang->userTime( $expiration, $this ) )->text(),
4500 'ip' => $this->getRequest()->getIP(),
4501 'confirmURL' => $url,
4502 'invalidateURL' => $invalidateURL,
4503 'expiration' => $expiration
4506 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4507 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4511 * Send an e-mail to this user's account. Does not check for
4512 * confirmed status or validity.
4514 * @param string $subject Message subject
4515 * @param string $body Message body
4516 * @param User|null $from Optional sending user; if unspecified, default
4517 * $wgPasswordSender will be used.
4518 * @param MailAddress|null $replyto Reply-To address
4521 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4522 global $wgPasswordSender;
4524 if ( $from instanceof User
) {
4525 $sender = MailAddress
::newFromUser( $from );
4527 $sender = new MailAddress( $wgPasswordSender,
4528 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4530 $to = MailAddress
::newFromUser( $this );
4532 return UserMailer
::send( $to, $sender, $subject, $body, [
4533 'replyTo' => $replyto,
4538 * Generate, store, and return a new e-mail confirmation code.
4539 * A hash (unsalted, since it's used as a key) is stored.
4541 * @note Call saveSettings() after calling this function to commit
4542 * this change to the database.
4544 * @param string &$expiration Accepts the expiration time
4545 * @return string New token
4547 protected function confirmationToken( &$expiration ) {
4548 global $wgUserEmailConfirmationTokenExpiry;
4550 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4551 $expiration = wfTimestamp( TS_MW
, $expires );
4553 $token = MWCryptRand
::generateHex( 32 );
4554 $hash = md5( $token );
4555 $this->mEmailToken
= $hash;
4556 $this->mEmailTokenExpires
= $expiration;
4561 * Return a URL the user can use to confirm their email address.
4562 * @param string $token Accepts the email confirmation token
4563 * @return string New token URL
4565 protected function confirmationTokenUrl( $token ) {
4566 return $this->getTokenUrl( 'ConfirmEmail', $token );
4570 * Return a URL the user can use to invalidate their email address.
4571 * @param string $token Accepts the email confirmation token
4572 * @return string New token URL
4574 protected function invalidationTokenUrl( $token ) {
4575 return $this->getTokenUrl( 'InvalidateEmail', $token );
4579 * Internal function to format the e-mail validation/invalidation URLs.
4580 * This uses a quickie hack to use the
4581 * hardcoded English names of the Special: pages, for ASCII safety.
4583 * @note Since these URLs get dropped directly into emails, using the
4584 * short English names avoids insanely long URL-encoded links, which
4585 * also sometimes can get corrupted in some browsers/mailers
4586 * (T8957 with Gmail and Internet Explorer).
4588 * @param string $page Special page
4589 * @param string $token
4590 * @return string Formatted URL
4592 protected function getTokenUrl( $page, $token ) {
4593 // Hack to bypass localization of 'Special:'
4594 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4595 return $title->getCanonicalURL();
4599 * Mark the e-mail address confirmed.
4601 * @note Call saveSettings() after calling this function to commit the change.
4605 public function confirmEmail() {
4606 // Check if it's already confirmed, so we don't touch the database
4607 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4608 if ( !$this->isEmailConfirmed() ) {
4609 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4610 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4616 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4617 * address if it was already confirmed.
4619 * @note Call saveSettings() after calling this function to commit the change.
4620 * @return bool Returns true
4622 public function invalidateEmail() {
4624 $this->mEmailToken
= null;
4625 $this->mEmailTokenExpires
= null;
4626 $this->setEmailAuthenticationTimestamp( null );
4628 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4633 * Set the e-mail authentication timestamp.
4634 * @param string $timestamp TS_MW timestamp
4636 public function setEmailAuthenticationTimestamp( $timestamp ) {
4638 $this->mEmailAuthenticated
= $timestamp;
4639 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4643 * Is this user allowed to send e-mails within limits of current
4644 * site configuration?
4647 public function canSendEmail() {
4648 global $wgEnableEmail, $wgEnableUserEmail;
4649 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4652 $canSend = $this->isEmailConfirmed();
4653 // Avoid PHP 7.1 warning of passing $this by reference
4655 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4660 * Is this user allowed to receive e-mails within limits of current
4661 * site configuration?
4664 public function canReceiveEmail() {
4665 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4669 * Is this user's e-mail address valid-looking and confirmed within
4670 * limits of the current site configuration?
4672 * @note If $wgEmailAuthentication is on, this may require the user to have
4673 * confirmed their address by returning a code or using a password
4674 * sent to the address from the wiki.
4678 public function isEmailConfirmed() {
4679 global $wgEmailAuthentication;
4681 // Avoid PHP 7.1 warning of passing $this by reference
4684 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4685 if ( $this->isAnon() ) {
4688 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4691 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4701 * Check whether there is an outstanding request for e-mail confirmation.
4704 public function isEmailConfirmationPending() {
4705 global $wgEmailAuthentication;
4706 return $wgEmailAuthentication &&
4707 !$this->isEmailConfirmed() &&
4708 $this->mEmailToken
&&
4709 $this->mEmailTokenExpires
> wfTimestamp();
4713 * Get the timestamp of account creation.
4715 * @return string|bool|null Timestamp of account creation, false for
4716 * non-existent/anonymous user accounts, or null if existing account
4717 * but information is not in database.
4719 public function getRegistration() {
4720 if ( $this->isAnon() ) {
4724 return $this->mRegistration
;
4728 * Get the timestamp of the first edit
4730 * @return string|bool Timestamp of first edit, or false for
4731 * non-existent/anonymous user accounts.
4733 public function getFirstEditTimestamp() {
4734 return $this->getEditTimestamp( true );
4738 * Get the timestamp of the latest edit
4741 * @return string|bool Timestamp of first edit, or false for
4742 * non-existent/anonymous user accounts.
4744 public function getLatestEditTimestamp() {
4745 return $this->getEditTimestamp( false );
4749 * Get the timestamp of the first or latest edit
4751 * @param bool $first True for the first edit, false for the latest one
4752 * @return string|bool Timestamp of first or latest edit, or false for
4753 * non-existent/anonymous user accounts.
4755 private function getEditTimestamp( $first ) {
4756 if ( $this->getId() == 0 ) {
4757 return false; // anons
4759 $dbr = wfGetDB( DB_REPLICA
);
4760 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4761 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4762 ?
'revactor_timestamp' : 'rev_timestamp';
4763 $sortOrder = $first ?
'ASC' : 'DESC';
4764 $time = $dbr->selectField(
4765 [ 'revision' ] +
$actorWhere['tables'],
4767 [ $actorWhere['conds'] ],
4769 [ 'ORDER BY' => "$tsField $sortOrder" ],
4770 $actorWhere['joins']
4773 return false; // no edits
4775 return wfTimestamp( TS_MW
, $time );
4779 * Get the permissions associated with a given list of groups
4781 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4782 * ->getGroupPermissions() instead
4784 * @param array $groups Array of Strings List of internal group names
4785 * @return array Array of Strings List of permission key names for given groups combined
4787 public static function getGroupPermissions( $groups ) {
4788 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4792 * Get all the groups who have a given permission
4794 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4795 * ->getGroupsWithPermission() instead
4797 * @param string $role Role to check
4798 * @return array Array of Strings List of internal group names with the given permission
4800 public static function getGroupsWithPermission( $role ) {
4801 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4805 * Check, if the given group has the given permission
4807 * If you're wanting to check whether all users have a permission, use
4808 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4811 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4812 * ->groupHasPermission(..) instead
4815 * @param string $group Group to check
4816 * @param string $role Role to check
4819 public static function groupHasPermission( $group, $role ) {
4820 return MediaWikiServices
::getInstance()->getPermissionManager()
4821 ->groupHasPermission( $group, $role );
4825 * Check if all users may be assumed to have the given permission
4827 * We generally assume so if the right is granted to '*' and isn't revoked
4828 * on any group. It doesn't attempt to take grants or other extension
4829 * limitations on rights into account in the general case, though, as that
4830 * would require it to always return false and defeat the purpose.
4831 * Specifically, session-based rights restrictions (such as OAuth or bot
4832 * passwords) are applied based on the current session.
4834 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4835 * ->isEveryoneAllowed() instead
4837 * @param string $right Right to check
4842 public static function isEveryoneAllowed( $right ) {
4843 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4847 * Return the set of defined explicit groups.
4848 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4849 * are not included, as they are defined automatically, not in the database.
4850 * @return array Array of internal group names
4852 public static function getAllGroups() {
4853 global $wgGroupPermissions, $wgRevokePermissions;
4854 return array_values( array_diff(
4855 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4856 self
::getImplicitGroups()
4861 * Get a list of all available permissions.
4863 * @deprecated since 1.34, use PermissionManager::getAllPermissions() instead
4865 * @return string[] Array of permission names
4867 public static function getAllRights() {
4868 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4872 * Get a list of implicit groups
4873 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4875 * @return array Array of Strings Array of internal group names
4877 public static function getImplicitGroups() {
4878 global $wgImplicitGroups;
4879 return $wgImplicitGroups;
4883 * Returns an array of the groups that a particular group can add/remove.
4885 * @param string $group The group to check for whether it can add/remove
4886 * @return array [ 'add' => [ addablegroups ],
4887 * 'remove' => [ removablegroups ],
4888 * 'add-self' => [ addablegroups to self ],
4889 * 'remove-self' => [ removable groups from self ] ]
4891 public static function changeableByGroup( $group ) {
4892 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4901 if ( empty( $wgAddGroups[$group] ) ) {
4902 // Don't add anything to $groups
4903 } elseif ( $wgAddGroups[$group] === true ) {
4904 // You get everything
4905 $groups['add'] = self
::getAllGroups();
4906 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4907 $groups['add'] = $wgAddGroups[$group];
4910 // Same thing for remove
4911 if ( empty( $wgRemoveGroups[$group] ) ) {
4913 } elseif ( $wgRemoveGroups[$group] === true ) {
4914 $groups['remove'] = self
::getAllGroups();
4915 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4916 $groups['remove'] = $wgRemoveGroups[$group];
4919 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4920 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4921 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4922 if ( is_int( $key ) ) {
4923 $wgGroupsAddToSelf['user'][] = $value;
4928 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4929 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4930 if ( is_int( $key ) ) {
4931 $wgGroupsRemoveFromSelf['user'][] = $value;
4936 // Now figure out what groups the user can add to him/herself
4937 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4939 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4940 // No idea WHY this would be used, but it's there
4941 $groups['add-self'] = self
::getAllGroups();
4942 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4943 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4946 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4948 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4949 $groups['remove-self'] = self
::getAllGroups();
4950 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4951 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4958 * Returns an array of groups that this user can add and remove
4959 * @return array [ 'add' => [ addablegroups ],
4960 * 'remove' => [ removablegroups ],
4961 * 'add-self' => [ addablegroups to self ],
4962 * 'remove-self' => [ removable groups from self ] ]
4964 public function changeableGroups() {
4965 if ( $this->isAllowed( 'userrights' ) ) {
4966 // This group gives the right to modify everything (reverse-
4967 // compatibility with old "userrights lets you change
4969 // Using array_merge to make the groups reindexed
4970 $all = array_merge( self
::getAllGroups() );
4979 // Okay, it's not so simple, we will have to go through the arrays
4986 $addergroups = $this->getEffectiveGroups();
4988 foreach ( $addergroups as $addergroup ) {
4989 $groups = array_merge_recursive(
4990 $groups, $this->changeableByGroup( $addergroup )
4992 $groups['add'] = array_unique( $groups['add'] );
4993 $groups['remove'] = array_unique( $groups['remove'] );
4994 $groups['add-self'] = array_unique( $groups['add-self'] );
4995 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5001 * Schedule a deferred update to update the user's edit count
5003 public function incEditCount() {
5004 if ( $this->isAnon() ) {
5008 DeferredUpdates
::addUpdate(
5009 new UserEditCountUpdate( $this, 1 ),
5010 DeferredUpdates
::POSTSEND
5015 * This method should not be called outside User/UserEditCountUpdate
5019 public function setEditCountInternal( $count ) {
5020 $this->mEditCount
= $count;
5024 * Initialize user_editcount from data out of the revision table
5026 * @internal This method should not be called outside User/UserEditCountUpdate
5027 * @param IDatabase $dbr Replica database
5028 * @return int Number of edits
5030 public function initEditCountInternal( IDatabase
$dbr ) {
5031 // Pull from a replica DB to be less cruel to servers
5032 // Accuracy isn't the point anyway here
5033 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5034 $count = (int)$dbr->selectField(
5035 [ 'revision' ] +
$actorWhere['tables'],
5037 [ $actorWhere['conds'] ],
5040 $actorWhere['joins']
5043 $dbw = wfGetDB( DB_MASTER
);
5046 [ 'user_editcount' => $count ],
5048 'user_id' => $this->getId(),
5049 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5058 * Get the description of a given right
5061 * @param string $right Right to query
5062 * @return string Localized description of the right
5064 public static function getRightDescription( $right ) {
5065 $key = "right-$right";
5066 $msg = wfMessage( $key );
5067 return $msg->isDisabled() ?
$right : $msg->text();
5071 * Get the name of a given grant
5074 * @param string $grant Grant to query
5075 * @return string Localized name of the grant
5077 public static function getGrantName( $grant ) {
5078 $key = "grant-$grant";
5079 $msg = wfMessage( $key );
5080 return $msg->isDisabled() ?
$grant : $msg->text();
5084 * Add a newuser log entry for this user.
5085 * Before 1.19 the return value was always true.
5087 * @deprecated since 1.27, AuthManager handles logging
5088 * @param string|bool $action Account creation type.
5089 * - String, one of the following values:
5090 * - 'create' for an anonymous user creating an account for himself.
5091 * This will force the action's performer to be the created user itself,
5092 * no matter the value of $wgUser
5093 * - 'create2' for a logged in user creating an account for someone else
5094 * - 'byemail' when the created user will receive its password by e-mail
5095 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5096 * - Boolean means whether the account was created by e-mail (deprecated):
5097 * - true will be converted to 'byemail'
5098 * - false will be converted to 'create' if this object is the same as
5099 * $wgUser and to 'create2' otherwise
5100 * @param string $reason User supplied reason
5103 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5104 return true; // disabled
5108 * Add an autocreate newuser log entry for this user
5109 * Used by things like CentralAuth and perhaps other authplugins.
5110 * Consider calling addNewUserLogEntry() directly instead.
5112 * @deprecated since 1.27, AuthManager handles logging
5115 public function addNewUserLogEntryAutoCreate() {
5116 wfDeprecated( __METHOD__
, '1.27' );
5117 $this->addNewUserLogEntry( 'autocreate' );
5123 * Load the user options either from cache, the database or an array
5125 * @param array|null $data Rows for the current user out of the user_properties table
5127 protected function loadOptions( $data = null ) {
5130 if ( $this->mOptionsLoaded
) {
5134 $this->mOptions
= self
::getDefaultOptions();
5136 if ( !$this->getId() ) {
5137 // For unlogged-in users, load language/variant options from request.
5138 // There's no need to do it for logged-in users: they can set preferences,
5139 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5140 // so don't override user's choice (especially when the user chooses site default).
5141 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5142 $this->mOptions
['variant'] = $variant;
5143 $this->mOptions
['language'] = $variant;
5144 $this->mOptionsLoaded
= true;
5148 // Maybe load from the object
5149 if ( !is_null( $this->mOptionOverrides
) ) {
5150 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5151 foreach ( $this->mOptionOverrides
as $key => $value ) {
5152 $this->mOptions
[$key] = $value;
5155 if ( !is_array( $data ) ) {
5156 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5157 // Load from database
5158 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5159 ?
wfGetDB( DB_MASTER
)
5160 : wfGetDB( DB_REPLICA
);
5162 $res = $dbr->select(
5164 [ 'up_property', 'up_value' ],
5165 [ 'up_user' => $this->getId() ],
5169 $this->mOptionOverrides
= [];
5171 foreach ( $res as $row ) {
5172 // Convert '0' to 0. PHP's boolean conversion considers them both
5173 // false, but e.g. JavaScript considers the former as true.
5174 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5175 // and convert all values here.
5176 if ( $row->up_value
=== '0' ) {
5179 $data[$row->up_property
] = $row->up_value
;
5183 foreach ( $data as $property => $value ) {
5184 $this->mOptionOverrides
[$property] = $value;
5185 $this->mOptions
[$property] = $value;
5189 // Replace deprecated language codes
5190 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5191 $this->mOptions
['language']
5194 $this->mOptionsLoaded
= true;
5196 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5200 * Saves the non-default options for this user, as previously set e.g. via
5201 * setOption(), in the database's "user_properties" (preferences) table.
5202 * Usually used via saveSettings().
5204 protected function saveOptions() {
5205 $this->loadOptions();
5207 // Not using getOptions(), to keep hidden preferences in database
5208 $saveOptions = $this->mOptions
;
5210 // Allow hooks to abort, for instance to save to a global profile.
5211 // Reset options to default state before saving.
5212 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5216 $userId = $this->getId();
5218 $insert_rows = []; // all the new preference rows
5219 foreach ( $saveOptions as $key => $value ) {
5220 // Don't bother storing default values
5221 $defaultOption = self
::getDefaultOption( $key );
5222 if ( ( $defaultOption === null && $value !== false && $value !== null )
5223 ||
$value != $defaultOption
5226 'up_user' => $userId,
5227 'up_property' => $key,
5228 'up_value' => $value,
5233 $dbw = wfGetDB( DB_MASTER
);
5235 $res = $dbw->select( 'user_properties',
5236 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5238 // Find prior rows that need to be removed or updated. These rows will
5239 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5241 foreach ( $res as $row ) {
5242 if ( !isset( $saveOptions[$row->up_property
] )
5243 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5245 $keysDelete[] = $row->up_property
;
5249 if ( count( $keysDelete ) ) {
5250 // Do the DELETE by PRIMARY KEY for prior rows.
5251 // In the past a very large portion of calls to this function are for setting
5252 // 'rememberpassword' for new accounts (a preference that has since been removed).
5253 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5254 // caused gap locks on [max user ID,+infinity) which caused high contention since
5255 // updates would pile up on each other as they are for higher (newer) user IDs.
5256 // It might not be necessary these days, but it shouldn't hurt either.
5257 $dbw->delete( 'user_properties',
5258 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5260 // Insert the new preference rows
5261 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5265 * Return the list of user fields that should be selected to create
5266 * a new user object.
5267 * @deprecated since 1.31, use self::getQueryInfo() instead.
5270 public static function selectFields() {
5271 wfDeprecated( __METHOD__
, '1.31' );
5279 'user_email_authenticated',
5281 'user_email_token_expires',
5282 'user_registration',
5288 * Return the tables, fields, and join conditions to be selected to create
5289 * a new user object.
5291 * @return array With three keys:
5292 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5293 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5294 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5296 public static function getQueryInfo() {
5297 global $wgActorTableSchemaMigrationStage;
5300 'tables' => [ 'user' ],
5308 'user_email_authenticated',
5310 'user_email_token_expires',
5311 'user_registration',
5317 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5318 // but it does little harm and might be needed for write callers loading a User.
5319 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5320 $ret['tables']['user_actor'] = 'actor';
5321 $ret['fields'][] = 'user_actor.actor_id';
5322 $ret['joins']['user_actor'] = [
5323 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5324 [ 'user_actor.actor_user = user_id' ]
5332 * Factory function for fatal permission-denied errors
5335 * @param string $permission User right required
5338 static function newFatalPermissionDeniedStatus( $permission ) {
5342 foreach ( MediaWikiServices
::getInstance()
5343 ->getPermissionManager()
5344 ->getGroupsWithPermission( $permission ) as $group ) {
5345 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5349 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5352 return Status
::newFatal( 'badaccess-group0' );
5356 * Get a new instance of this user that was loaded from the master via a locking read
5358 * Use this instead of the main context User when updating that user. This avoids races
5359 * where that user was loaded from a replica DB or even the master but without proper locks.
5361 * @return User|null Returns null if the user was not found in the DB
5364 public function getInstanceForUpdate() {
5365 if ( !$this->getId() ) {
5366 return null; // anon
5369 $user = self
::newFromId( $this->getId() );
5370 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5378 * Checks if two user objects point to the same user.
5380 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5381 * @param UserIdentity $user
5384 public function equals( UserIdentity
$user ) {
5385 // XXX it's not clear whether central ID providers are supposed to obey this
5386 return $this->getName() === $user->getName();
5390 * Checks if usertalk is allowed
5394 public function isAllowUsertalk() {
5395 return $this->mAllowUsertalk
;