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 // @phan-suppress-next-line PhanAccessMethodInternal It's the only allowed use
1756 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1762 $this->mBlock
= $block;
1763 $this->mBlockedby
= $block->getByName();
1764 $this->mBlockreason
= $block->getReason();
1765 $this->mHideName
= $block->getHideName();
1766 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1768 $this->mBlock
= null;
1769 $this->mBlockedby
= '';
1770 $this->mBlockreason
= '';
1771 $this->mHideName
= 0;
1772 $this->mAllowUsertalk
= false;
1775 // Avoid PHP 7.1 warning of passing $this by reference
1778 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1782 * Whether the given IP is in a DNS blacklist.
1784 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1785 * @param string $ip IP to check
1786 * @param bool $checkWhitelist Whether to check the whitelist first
1787 * @return bool True if blacklisted.
1789 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1790 return MediaWikiServices
::getInstance()->getBlockManager()
1791 ->isDnsBlacklisted( $ip, $checkWhitelist );
1795 * Whether the given IP is in a given DNS blacklist.
1797 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1798 * @param string $ip IP to check
1799 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1800 * @return bool True if blacklisted.
1802 public function inDnsBlacklist( $ip, $bases ) {
1803 wfDeprecated( __METHOD__
, '1.34' );
1806 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1807 if ( IP
::isIPv4( $ip ) ) {
1808 // Reverse IP, T23255
1809 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1811 foreach ( (array)$bases as $base ) {
1813 // If we have an access key, use that too (ProjectHoneypot, etc.)
1815 if ( is_array( $base ) ) {
1816 if ( count( $base ) >= 2 ) {
1817 // Access key is 1, base URL is 0
1818 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1820 $host = "$ipReversed.{$base[0]}";
1822 $basename = $base[0];
1824 $host = "$ipReversed.$base";
1828 $ipList = gethostbynamel( $host );
1831 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1836 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1844 * Check if an IP address is in the local proxy list
1846 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1850 public static function isLocallyBlockedProxy( $ip ) {
1851 wfDeprecated( __METHOD__
, '1.34' );
1853 global $wgProxyList;
1855 if ( !$wgProxyList ) {
1859 if ( !is_array( $wgProxyList ) ) {
1860 // Load values from the specified file
1861 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1864 $resultProxyList = [];
1865 $deprecatedIPEntries = [];
1867 // backward compatibility: move all ip addresses in keys to values
1868 foreach ( $wgProxyList as $key => $value ) {
1869 $keyIsIP = IP
::isIPAddress( $key );
1870 $valueIsIP = IP
::isIPAddress( $value );
1871 if ( $keyIsIP && !$valueIsIP ) {
1872 $deprecatedIPEntries[] = $key;
1873 $resultProxyList[] = $key;
1874 } elseif ( $keyIsIP && $valueIsIP ) {
1875 $deprecatedIPEntries[] = $key;
1876 $resultProxyList[] = $key;
1877 $resultProxyList[] = $value;
1879 $resultProxyList[] = $value;
1883 if ( $deprecatedIPEntries ) {
1885 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1886 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1889 $proxyListIPSet = new IPSet( $resultProxyList );
1890 return $proxyListIPSet->match( $ip );
1894 * Is this user subject to rate limiting?
1896 * @return bool True if rate limited
1898 public function isPingLimitable() {
1899 global $wgRateLimitsExcludedIPs;
1900 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1901 // No other good way currently to disable rate limits
1902 // for specific IPs. :P
1903 // But this is a crappy hack and should die.
1906 return !$this->isAllowed( 'noratelimit' );
1910 * Primitive rate limits: enforce maximum actions per time period
1911 * to put a brake on flooding.
1913 * The method generates both a generic profiling point and a per action one
1914 * (suffix being "-$action".
1916 * @note When using a shared cache like memcached, IP-address
1917 * last-hit counters will be shared across wikis.
1919 * @param string $action Action to enforce; 'edit' if unspecified
1920 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1921 * @return bool True if a rate limiter was tripped
1923 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1924 // Avoid PHP 7.1 warning of passing $this by reference
1926 // Call the 'PingLimiter' hook
1928 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1932 global $wgRateLimits;
1933 if ( !isset( $wgRateLimits[$action] ) ) {
1937 $limits = array_merge(
1938 [ '&can-bypass' => true ],
1939 $wgRateLimits[$action]
1942 // Some groups shouldn't trigger the ping limiter, ever
1943 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1948 $id = $this->getId();
1950 $isNewbie = $this->isNewbie();
1951 $cache = ObjectCache
::getLocalClusterInstance();
1955 if ( isset( $limits['anon'] ) ) {
1956 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1958 } elseif ( isset( $limits['user'] ) ) {
1959 // limits for logged-in users
1960 $userLimit = $limits['user'];
1963 // limits for anons and for newbie logged-in users
1966 if ( isset( $limits['ip'] ) ) {
1967 $ip = $this->getRequest()->getIP();
1968 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1970 // subnet-based limits
1971 if ( isset( $limits['subnet'] ) ) {
1972 $ip = $this->getRequest()->getIP();
1973 $subnet = IP
::getSubnet( $ip );
1974 if ( $subnet !== false ) {
1975 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1980 // Check for group-specific permissions
1981 // If more than one group applies, use the group with the highest limit ratio (max/period)
1982 foreach ( $this->getGroups() as $group ) {
1983 if ( isset( $limits[$group] ) ) {
1984 if ( $userLimit === false
1985 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1987 $userLimit = $limits[$group];
1992 // limits for newbie logged-in users (override all the normal user limits)
1993 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1994 $userLimit = $limits['newbie'];
1997 // Set the user limit key
1998 if ( $userLimit !== false ) {
1999 // phan is confused because &can-bypass's value is a bool, so it assumes
2000 // that $userLimit is also a bool here.
2001 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2002 list( $max, $period ) = $userLimit;
2003 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2004 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2007 // ip-based limits for all ping-limitable users
2008 if ( isset( $limits['ip-all'] ) ) {
2009 $ip = $this->getRequest()->getIP();
2010 // ignore if user limit is more permissive
2011 if ( $isNewbie ||
$userLimit === false
2012 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2013 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2017 // subnet-based limits for all ping-limitable users
2018 if ( isset( $limits['subnet-all'] ) ) {
2019 $ip = $this->getRequest()->getIP();
2020 $subnet = IP
::getSubnet( $ip );
2021 if ( $subnet !== false ) {
2022 // ignore if user limit is more permissive
2023 if ( $isNewbie ||
$userLimit === false
2024 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2025 > $userLimit[0] / $userLimit[1] ) {
2026 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2032 foreach ( $keys as $key => $limit ) {
2033 // phan is confused because &can-bypass's value is a bool, so it assumes
2034 // that $userLimit is also a bool here.
2035 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2036 list( $max, $period ) = $limit;
2037 $summary = "(limit $max in {$period}s)";
2038 $count = $cache->get( $key );
2040 if ( $count && $count >= $max ) {
2041 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2042 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2045 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2046 if ( $incrBy > 0 ) {
2047 $cache->add( $key, 0, intval( $period ) ); // first ping
2050 if ( $incrBy > 0 ) {
2051 $cache->incrWithInit( $key, (int)$period, $incrBy, $incrBy );
2059 * Check if user is blocked
2061 * @deprecated since 1.34, use User::getBlock() or
2062 * PermissionManager::isBlockedFrom() or
2063 * PermissionManager::userCan() instead.
2065 * @param bool $fromReplica Whether to check the replica DB instead of
2066 * the master. Hacked from false due to horrible probs on site.
2067 * @return bool True if blocked, false otherwise
2069 public function isBlocked( $fromReplica = true ) {
2070 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2071 $this->getBlock()->appliesToRight( 'edit' );
2075 * Get the block affecting the user, or null if the user is not blocked
2077 * @param bool $fromReplica Whether to check the replica DB instead of the master
2078 * @return AbstractBlock|null
2080 public function getBlock( $fromReplica = true ) {
2081 $this->getBlockedStatus( $fromReplica );
2082 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2086 * Check if user is blocked from editing a particular article
2088 * @param Title $title Title to check
2089 * @param bool $fromReplica Whether to check the replica DB instead of the master
2092 * @deprecated since 1.33,
2093 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2096 public function isBlockedFrom( $title, $fromReplica = false ) {
2097 return MediaWikiServices
::getInstance()->getPermissionManager()
2098 ->isBlockedFrom( $this, $title, $fromReplica );
2102 * If user is blocked, return the name of the user who placed the block
2103 * @return string Name of blocker
2105 public function blockedBy() {
2106 $this->getBlockedStatus();
2107 return $this->mBlockedby
;
2111 * If user is blocked, return the specified reason for the block
2112 * @return string Blocking reason
2114 public function blockedFor() {
2115 $this->getBlockedStatus();
2116 return $this->mBlockreason
;
2120 * If user is blocked, return the ID for the block
2121 * @return int Block ID
2123 public function getBlockId() {
2124 $this->getBlockedStatus();
2125 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2129 * Check if user is blocked on all wikis.
2130 * Do not use for actual edit permission checks!
2131 * This is intended for quick UI checks.
2133 * @param string $ip IP address, uses current client if none given
2134 * @return bool True if blocked, false otherwise
2136 public function isBlockedGlobally( $ip = '' ) {
2137 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2141 * Check if user is blocked on all wikis.
2142 * Do not use for actual edit permission checks!
2143 * This is intended for quick UI checks.
2145 * @param string $ip IP address, uses current client if none given
2146 * @return AbstractBlock|null Block object if blocked, null otherwise
2147 * @throws FatalError
2148 * @throws MWException
2150 public function getGlobalBlock( $ip = '' ) {
2151 if ( $this->mGlobalBlock
!== null ) {
2152 return $this->mGlobalBlock ?
: null;
2154 // User is already an IP?
2155 if ( IP
::isIPAddress( $this->getName() ) ) {
2156 $ip = $this->getName();
2158 $ip = $this->getRequest()->getIP();
2160 // Avoid PHP 7.1 warning of passing $this by reference
2164 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2166 if ( $blocked && $block === null ) {
2167 // back-compat: UserIsBlockedGlobally didn't have $block param first
2168 $block = new SystemBlock( [
2170 'systemBlock' => 'global-block'
2174 $this->mGlobalBlock
= $blocked ?
$block : false;
2175 return $this->mGlobalBlock ?
: null;
2179 * Check if user account is locked
2181 * @return bool True if locked, false otherwise
2183 public function isLocked() {
2184 if ( $this->mLocked
!== null ) {
2185 return $this->mLocked
;
2188 $this->mLocked
= false;
2189 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2190 return $this->mLocked
;
2194 * Check if user account is hidden
2196 * @return bool True if hidden, false otherwise
2198 public function isHidden() {
2199 if ( $this->mHideName
!== null ) {
2200 return (bool)$this->mHideName
;
2202 $this->getBlockedStatus();
2203 if ( !$this->mHideName
) {
2205 $this->mHideName
= false;
2206 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2208 return (bool)$this->mHideName
;
2212 * Get the user's ID.
2213 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2215 public function getId() {
2216 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2217 // Special case, we know the user is anonymous
2221 if ( !$this->isItemLoaded( 'id' ) ) {
2222 // Don't load if this was initialized from an ID
2226 return (int)$this->mId
;
2230 * Set the user and reload all fields according to a given ID
2231 * @param int $v User ID to reload
2233 public function setId( $v ) {
2235 $this->clearInstanceCache( 'id' );
2239 * Get the user name, or the IP of an anonymous user
2240 * @return string User's name or IP address
2242 public function getName() {
2243 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2244 // Special case optimisation
2245 return $this->mName
;
2249 if ( $this->mName
=== false ) {
2251 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2254 return $this->mName
;
2258 * Set the user name.
2260 * This does not reload fields from the database according to the given
2261 * name. Rather, it is used to create a temporary "nonexistent user" for
2262 * later addition to the database. It can also be used to set the IP
2263 * address for an anonymous user to something other than the current
2266 * @note User::newFromName() has roughly the same function, when the named user
2268 * @param string $str New user name to set
2270 public function setName( $str ) {
2272 $this->mName
= $str;
2276 * Get the user's actor ID.
2278 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2279 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2281 public function getActorId( IDatabase
$dbw = null ) {
2282 global $wgActorTableSchemaMigrationStage;
2284 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2285 // but it does little harm and might be needed for write callers loading a User.
2286 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2290 if ( !$this->isItemLoaded( 'actor' ) ) {
2294 // Currently $this->mActorId might be null if $this was loaded from a
2295 // cache entry that was written when $wgActorTableSchemaMigrationStage
2296 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2297 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2298 // has been removed), that condition may be removed.
2299 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2301 'actor_user' => $this->getId() ?
: null,
2302 'actor_name' => (string)$this->getName(),
2305 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2306 throw new CannotCreateActorException(
2307 'Cannot create an actor for a usable name that is not an existing user'
2310 if ( $q['actor_name'] === '' ) {
2311 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2313 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2314 if ( $dbw->affectedRows() ) {
2315 $this->mActorId
= (int)$dbw->insertId();
2318 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2319 $this->mActorId
= (int)$dbw->selectField(
2324 [ 'LOCK IN SHARE MODE' ]
2326 if ( !$this->mActorId
) {
2327 throw new CannotCreateActorException(
2328 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2332 $this->invalidateCache();
2334 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2335 $db = wfGetDB( $index );
2336 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2338 $this->setItemLoaded( 'actor' );
2341 return (int)$this->mActorId
;
2345 * Get the user's name escaped by underscores.
2346 * @return string Username escaped by underscores.
2348 public function getTitleKey() {
2349 return str_replace( ' ', '_', $this->getName() );
2353 * Check if the user has new messages.
2354 * @return bool True if the user has new messages
2356 public function getNewtalk() {
2359 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2360 if ( $this->mNewtalk
=== -1 ) {
2361 $this->mNewtalk
= false; # reset talk page status
2363 // Check memcached separately for anons, who have no
2364 // entire User object stored in there.
2365 if ( !$this->mId
) {
2366 global $wgDisableAnonTalk;
2367 if ( $wgDisableAnonTalk ) {
2368 // Anon newtalk disabled by configuration.
2369 $this->mNewtalk
= false;
2371 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2374 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2378 return (bool)$this->mNewtalk
;
2382 * Return the data needed to construct links for new talk page message
2383 * alerts. If there are new messages, this will return an associative array
2384 * with the following data:
2385 * wiki: The database name of the wiki
2386 * link: Root-relative link to the user's talk page
2387 * rev: The last talk page revision that the user has seen or null. This
2388 * is useful for building diff links.
2389 * If there are no new messages, it returns an empty array.
2390 * @note This function was designed to accomodate multiple talk pages, but
2391 * currently only returns a single link and revision.
2394 public function getNewMessageLinks() {
2395 // Avoid PHP 7.1 warning of passing $this by reference
2398 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2402 if ( !$this->getNewtalk() ) {
2405 $utp = $this->getTalkPage();
2406 $dbr = wfGetDB( DB_REPLICA
);
2407 // Get the "last viewed rev" timestamp from the oldest message notification
2408 $timestamp = $dbr->selectField( 'user_newtalk',
2409 'MIN(user_last_timestamp)',
2410 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2412 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2415 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2416 'link' => $utp->getLocalURL(),
2423 * Get the revision ID for the last talk page revision viewed by the talk
2425 * @return int|null Revision ID or null
2427 public function getNewMessageRevisionId() {
2428 $newMessageRevisionId = null;
2429 $newMessageLinks = $this->getNewMessageLinks();
2431 // Note: getNewMessageLinks() never returns more than a single link
2432 // and it is always for the same wiki, but we double-check here in
2433 // case that changes some time in the future.
2434 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2435 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2436 && $newMessageLinks[0]['rev']
2438 /** @var Revision $newMessageRevision */
2439 $newMessageRevision = $newMessageLinks[0]['rev'];
2440 $newMessageRevisionId = $newMessageRevision->getId();
2443 return $newMessageRevisionId;
2447 * Internal uncached check for new messages
2450 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2451 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2452 * @return bool True if the user has new messages
2454 protected function checkNewtalk( $field, $id ) {
2455 $dbr = wfGetDB( DB_REPLICA
);
2457 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2459 return $ok !== false;
2463 * Add or update the new messages flag
2464 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2465 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2466 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2467 * @return bool True if successful, false otherwise
2469 protected function updateNewtalk( $field, $id, $curRev = null ) {
2470 // Get timestamp of the talk page revision prior to the current one
2471 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2472 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2473 // Mark the user as having new messages since this revision
2474 $dbw = wfGetDB( DB_MASTER
);
2475 $dbw->insert( 'user_newtalk',
2476 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2479 if ( $dbw->affectedRows() ) {
2480 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2484 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2489 * Clear the new messages flag for the given user
2490 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2491 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2492 * @return bool True if successful, false otherwise
2494 protected function deleteNewtalk( $field, $id ) {
2495 $dbw = wfGetDB( DB_MASTER
);
2496 $dbw->delete( 'user_newtalk',
2499 if ( $dbw->affectedRows() ) {
2500 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2504 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2509 * Update the 'You have new messages!' status.
2510 * @param bool $val Whether the user has new messages
2511 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2512 * page. Ignored if null or !$val.
2514 public function setNewtalk( $val, $curRev = null ) {
2515 if ( wfReadOnly() ) {
2520 $this->mNewtalk
= $val;
2522 if ( $this->isAnon() ) {
2524 $id = $this->getName();
2527 $id = $this->getId();
2531 $changed = $this->updateNewtalk( $field, $id, $curRev );
2533 $changed = $this->deleteNewtalk( $field, $id );
2537 $this->invalidateCache();
2542 * Generate a current or new-future timestamp to be stored in the
2543 * user_touched field when we update things.
2545 * @return string Timestamp in TS_MW format
2547 private function newTouchedTimestamp() {
2549 if ( $this->mTouched
) {
2550 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2553 return wfTimestamp( TS_MW
, $time );
2557 * Clear user data from memcached
2559 * Use after applying updates to the database; caller's
2560 * responsibility to update user_touched if appropriate.
2562 * Called implicitly from invalidateCache() and saveSettings().
2564 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2566 public function clearSharedCache( $mode = 'refresh' ) {
2567 if ( !$this->getId() ) {
2571 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2572 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2573 $key = $this->getCacheKey( $cache );
2575 if ( $mode === 'refresh' ) {
2576 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2578 $lb->getConnectionRef( DB_MASTER
)->onTransactionPreCommitOrIdle(
2579 function () use ( $cache, $key ) {
2580 $cache->delete( $key );
2588 * Immediately touch the user data cache for this account
2590 * Calls touch() and removes account data from memcached
2592 public function invalidateCache() {
2594 $this->clearSharedCache( 'changed' );
2598 * Update the "touched" timestamp for the user
2600 * This is useful on various login/logout events when making sure that
2601 * a browser or proxy that has multiple tenants does not suffer cache
2602 * pollution where the new user sees the old users content. The value
2603 * of getTouched() is checked when determining 304 vs 200 responses.
2604 * Unlike invalidateCache(), this preserves the User object cache and
2605 * avoids database writes.
2609 public function touch() {
2610 $id = $this->getId();
2612 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2613 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2614 $cache->touchCheckKey( $key );
2615 $this->mQuickTouched
= null;
2620 * Validate the cache for this account.
2621 * @param string $timestamp A timestamp in TS_MW format
2624 public function validateCache( $timestamp ) {
2625 return ( $timestamp >= $this->getTouched() );
2629 * Get the user touched timestamp
2631 * Use this value only to validate caches via inequalities
2632 * such as in the case of HTTP If-Modified-Since response logic
2634 * @return string TS_MW Timestamp
2636 public function getTouched() {
2640 if ( $this->mQuickTouched
=== null ) {
2641 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2642 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2644 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2647 return max( $this->mTouched
, $this->mQuickTouched
);
2650 return $this->mTouched
;
2654 * Get the user_touched timestamp field (time of last DB updates)
2655 * @return string TS_MW Timestamp
2658 public function getDBTouched() {
2661 return $this->mTouched
;
2665 * Set the password and reset the random token.
2666 * Calls through to authentication plugin if necessary;
2667 * will have no effect if the auth plugin refuses to
2668 * pass the change through or if the legal password
2671 * As a special case, setting the password to null
2672 * wipes it, so the account cannot be logged in until
2673 * a new password is set, for instance via e-mail.
2675 * @deprecated since 1.27, use AuthManager instead
2676 * @param string $str New password to set
2677 * @throws PasswordError On failure
2680 public function setPassword( $str ) {
2681 wfDeprecated( __METHOD__
, '1.27' );
2682 return $this->setPasswordInternal( $str );
2686 * Set the password and reset the random token unconditionally.
2688 * @deprecated since 1.27, use AuthManager instead
2689 * @param string|null $str New password to set or null to set an invalid
2690 * password hash meaning that the user will not be able to log in
2691 * through the web interface.
2693 public function setInternalPassword( $str ) {
2694 wfDeprecated( __METHOD__
, '1.27' );
2695 $this->setPasswordInternal( $str );
2699 * Actually set the password and such
2700 * @since 1.27 cannot set a password for a user not in the database
2701 * @param string|null $str New password to set or null to set an invalid
2702 * password hash meaning that the user will not be able to log in
2703 * through the web interface.
2704 * @return bool Success
2706 private function setPasswordInternal( $str ) {
2707 $manager = AuthManager
::singleton();
2709 // If the user doesn't exist yet, fail
2710 if ( !$manager->userExists( $this->getName() ) ) {
2711 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2714 $status = $this->changeAuthenticationData( [
2715 'username' => $this->getName(),
2719 if ( !$status->isGood() ) {
2720 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2721 ->info( __METHOD__
. ': Password change rejected: '
2722 . $status->getWikiText( null, null, 'en' ) );
2726 $this->setOption( 'watchlisttoken', false );
2727 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2733 * Changes credentials of the user.
2735 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2736 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2737 * e.g. when no provider handled the change.
2739 * @param array $data A set of authentication data in fieldname => value format. This is the
2740 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2744 public function changeAuthenticationData( array $data ) {
2745 $manager = AuthManager
::singleton();
2746 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2747 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2749 $status = Status
::newGood( 'ignored' );
2750 foreach ( $reqs as $req ) {
2751 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2753 if ( $status->getValue() === 'ignored' ) {
2754 $status->warning( 'authenticationdatachange-ignored' );
2757 if ( $status->isGood() ) {
2758 foreach ( $reqs as $req ) {
2759 $manager->changeAuthenticationData( $req );
2766 * Get the user's current token.
2767 * @param bool $forceCreation Force the generation of a new token if the
2768 * user doesn't have one (default=true for backwards compatibility).
2769 * @return string|null Token
2771 public function getToken( $forceCreation = true ) {
2772 global $wgAuthenticationTokenVersion;
2775 if ( !$this->mToken
&& $forceCreation ) {
2779 if ( !$this->mToken
) {
2780 // The user doesn't have a token, return null to indicate that.
2784 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2785 // We return a random value here so existing token checks are very
2787 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2790 if ( $wgAuthenticationTokenVersion === null ) {
2791 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2792 return $this->mToken
;
2795 // $wgAuthenticationTokenVersion in use, so hmac it.
2796 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2798 // The raw hash can be overly long. Shorten it up.
2799 $len = max( 32, self
::TOKEN_LENGTH
);
2800 if ( strlen( $ret ) < $len ) {
2801 // Should never happen, even md5 is 128 bits
2802 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2805 return substr( $ret, -$len );
2809 * Set the random token (used for persistent authentication)
2810 * Called from loadDefaults() among other places.
2812 * @param string|bool $token If specified, set the token to this value
2814 public function setToken( $token = false ) {
2816 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2817 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2818 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2819 } elseif ( !$token ) {
2820 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2822 $this->mToken
= $token;
2827 * Set the password for a password reminder or new account email
2829 * @deprecated Removed in 1.27. Use PasswordReset instead.
2830 * @param string $str New password to set or null to set an invalid
2831 * password hash meaning that the user will not be able to use it
2832 * @param bool $throttle If true, reset the throttle timestamp to the present
2834 public function setNewpassword( $str, $throttle = true ) {
2835 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2839 * Get the user's e-mail address
2840 * @return string User's email address
2842 public function getEmail() {
2844 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2845 return $this->mEmail
;
2849 * Get the timestamp of the user's e-mail authentication
2850 * @return string TS_MW timestamp
2852 public function getEmailAuthenticationTimestamp() {
2854 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2855 return $this->mEmailAuthenticated
;
2859 * Set the user's e-mail address
2860 * @param string $str New e-mail address
2862 public function setEmail( $str ) {
2864 if ( $str == $this->mEmail
) {
2867 $this->invalidateEmail();
2868 $this->mEmail
= $str;
2869 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2873 * Set the user's e-mail address and a confirmation mail if needed.
2876 * @param string $str New e-mail address
2879 public function setEmailWithConfirmation( $str ) {
2880 global $wgEnableEmail, $wgEmailAuthentication;
2882 if ( !$wgEnableEmail ) {
2883 return Status
::newFatal( 'emaildisabled' );
2886 $oldaddr = $this->getEmail();
2887 if ( $str === $oldaddr ) {
2888 return Status
::newGood( true );
2891 $type = $oldaddr != '' ?
'changed' : 'set';
2892 $notificationResult = null;
2894 if ( $wgEmailAuthentication && $type === 'changed' ) {
2895 // Send the user an email notifying the user of the change in registered
2896 // email address on their previous email address
2897 $change = $str != '' ?
'changed' : 'removed';
2898 $notificationResult = $this->sendMail(
2899 wfMessage( 'notificationemail_subject_' . $change )->text(),
2900 wfMessage( 'notificationemail_body_' . $change,
2901 $this->getRequest()->getIP(),
2907 $this->setEmail( $str );
2909 if ( $str !== '' && $wgEmailAuthentication ) {
2910 // Send a confirmation request to the new address if needed
2911 $result = $this->sendConfirmationMail( $type );
2913 if ( $notificationResult !== null ) {
2914 $result->merge( $notificationResult );
2917 if ( $result->isGood() ) {
2918 // Say to the caller that a confirmation and notification mail has been sent
2919 $result->value
= 'eauth';
2922 $result = Status
::newGood( true );
2929 * Get the user's real name
2930 * @return string User's real name
2932 public function getRealName() {
2933 if ( !$this->isItemLoaded( 'realname' ) ) {
2937 return $this->mRealName
;
2941 * Set the user's real name
2942 * @param string $str New real name
2944 public function setRealName( $str ) {
2946 $this->mRealName
= $str;
2950 * Get the user's current setting for a given option.
2952 * @param string $oname The option to check
2953 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2954 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2955 * @return string|array|int|null User's current value for the option
2956 * @see getBoolOption()
2957 * @see getIntOption()
2959 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2960 global $wgHiddenPrefs;
2961 $this->loadOptions();
2963 # We want 'disabled' preferences to always behave as the default value for
2964 # users, even if they have set the option explicitly in their settings (ie they
2965 # set it, and then it was disabled removing their ability to change it). But
2966 # we don't want to erase the preferences in the database in case the preference
2967 # is re-enabled again. So don't touch $mOptions, just override the returned value
2968 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2969 return self
::getDefaultOption( $oname );
2972 if ( array_key_exists( $oname, $this->mOptions
) ) {
2973 return $this->mOptions
[$oname];
2976 return $defaultOverride;
2980 * Get all user's options
2982 * @param int $flags Bitwise combination of:
2983 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2984 * to the default value. (Since 1.25)
2987 public function getOptions( $flags = 0 ) {
2988 global $wgHiddenPrefs;
2989 $this->loadOptions();
2990 $options = $this->mOptions
;
2992 # We want 'disabled' preferences to always behave as the default value for
2993 # users, even if they have set the option explicitly in their settings (ie they
2994 # set it, and then it was disabled removing their ability to change it). But
2995 # we don't want to erase the preferences in the database in case the preference
2996 # is re-enabled again. So don't touch $mOptions, just override the returned value
2997 foreach ( $wgHiddenPrefs as $pref ) {
2998 $default = self
::getDefaultOption( $pref );
2999 if ( $default !== null ) {
3000 $options[$pref] = $default;
3004 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3005 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3012 * Get the user's current setting for a given option, as a boolean value.
3014 * @param string $oname The option to check
3015 * @return bool User's current value for the option
3018 public function getBoolOption( $oname ) {
3019 return (bool)$this->getOption( $oname );
3023 * Get the user's current setting for a given option, as an integer value.
3025 * @param string $oname The option to check
3026 * @param int $defaultOverride A default value returned if the option does not exist
3027 * @return int User's current value for the option
3030 public function getIntOption( $oname, $defaultOverride = 0 ) {
3031 $val = $this->getOption( $oname );
3033 $val = $defaultOverride;
3035 return intval( $val );
3039 * Set the given option for a user.
3041 * You need to call saveSettings() to actually write to the database.
3043 * @param string $oname The option to set
3044 * @param mixed $val New value to set
3046 public function setOption( $oname, $val ) {
3047 $this->loadOptions();
3049 // Explicitly NULL values should refer to defaults
3050 if ( is_null( $val ) ) {
3051 $val = self
::getDefaultOption( $oname );
3054 $this->mOptions
[$oname] = $val;
3058 * Get a token stored in the preferences (like the watchlist one),
3059 * resetting it if it's empty (and saving changes).
3061 * @param string $oname The option name to retrieve the token from
3062 * @return string|bool User's current value for the option, or false if this option is disabled.
3063 * @see resetTokenFromOption()
3065 * @deprecated since 1.26 Applications should use the OAuth extension
3067 public function getTokenFromOption( $oname ) {
3068 global $wgHiddenPrefs;
3070 $id = $this->getId();
3071 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3075 $token = $this->getOption( $oname );
3077 // Default to a value based on the user token to avoid space
3078 // wasted on storing tokens for all users. When this option
3079 // is set manually by the user, only then is it stored.
3080 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3087 * Reset a token stored in the preferences (like the watchlist one).
3088 * *Does not* save user's preferences (similarly to setOption()).
3090 * @param string $oname The option name to reset the token in
3091 * @return string|bool New token value, or false if this option is disabled.
3092 * @see getTokenFromOption()
3095 public function resetTokenFromOption( $oname ) {
3096 global $wgHiddenPrefs;
3097 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3101 $token = MWCryptRand
::generateHex( 40 );
3102 $this->setOption( $oname, $token );
3107 * Return a list of the types of user options currently returned by
3108 * User::getOptionKinds().
3110 * Currently, the option kinds are:
3111 * - 'registered' - preferences which are registered in core MediaWiki or
3112 * by extensions using the UserGetDefaultOptions hook.
3113 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3114 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3115 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3116 * be used by user scripts.
3117 * - 'special' - "preferences" that are not accessible via User::getOptions
3118 * or User::setOptions.
3119 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3120 * These are usually legacy options, removed in newer versions.
3122 * The API (and possibly others) use this function to determine the possible
3123 * option types for validation purposes, so make sure to update this when a
3124 * new option kind is added.
3126 * @see User::getOptionKinds
3127 * @return array Option kinds
3129 public static function listOptionKinds() {
3132 'registered-multiselect',
3133 'registered-checkmatrix',
3141 * Return an associative array mapping preferences keys to the kind of a preference they're
3142 * used for. Different kinds are handled differently when setting or reading preferences.
3144 * See User::listOptionKinds for the list of valid option types that can be provided.
3146 * @see User::listOptionKinds
3147 * @param IContextSource $context
3148 * @param array|null $options Assoc. array with options keys to check as keys.
3149 * Defaults to $this->mOptions.
3150 * @return array The key => kind mapping data
3152 public function getOptionKinds( IContextSource
$context, $options = null ) {
3153 $this->loadOptions();
3154 if ( $options === null ) {
3155 $options = $this->mOptions
;
3158 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3159 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3162 // Pull out the "special" options, so they don't get converted as
3163 // multiselect or checkmatrix.
3164 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3165 foreach ( $specialOptions as $name => $value ) {
3166 unset( $prefs[$name] );
3169 // Multiselect and checkmatrix options are stored in the database with
3170 // one key per option, each having a boolean value. Extract those keys.
3171 $multiselectOptions = [];
3172 foreach ( $prefs as $name => $info ) {
3173 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3174 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3175 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3176 $prefix = $info['prefix'] ??
$name;
3178 foreach ( $opts as $value ) {
3179 $multiselectOptions["$prefix$value"] = true;
3182 unset( $prefs[$name] );
3185 $checkmatrixOptions = [];
3186 foreach ( $prefs as $name => $info ) {
3187 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3188 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3189 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3190 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3191 $prefix = $info['prefix'] ??
$name;
3193 foreach ( $columns as $column ) {
3194 foreach ( $rows as $row ) {
3195 $checkmatrixOptions["$prefix$column-$row"] = true;
3199 unset( $prefs[$name] );
3203 // $value is ignored
3204 foreach ( $options as $key => $value ) {
3205 if ( isset( $prefs[$key] ) ) {
3206 $mapping[$key] = 'registered';
3207 } elseif ( isset( $multiselectOptions[$key] ) ) {
3208 $mapping[$key] = 'registered-multiselect';
3209 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3210 $mapping[$key] = 'registered-checkmatrix';
3211 } elseif ( isset( $specialOptions[$key] ) ) {
3212 $mapping[$key] = 'special';
3213 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3214 $mapping[$key] = 'userjs';
3216 $mapping[$key] = 'unused';
3224 * Reset certain (or all) options to the site defaults
3226 * The optional parameter determines which kinds of preferences will be reset.
3227 * Supported values are everything that can be reported by getOptionKinds()
3228 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3230 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3231 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3232 * for backwards-compatibility.
3233 * @param IContextSource|null $context Context source used when $resetKinds
3234 * does not contain 'all', passed to getOptionKinds().
3235 * Defaults to RequestContext::getMain() when null.
3237 public function resetOptions(
3238 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3239 IContextSource
$context = null
3242 $defaultOptions = self
::getDefaultOptions();
3244 if ( !is_array( $resetKinds ) ) {
3245 $resetKinds = [ $resetKinds ];
3248 if ( in_array( 'all', $resetKinds ) ) {
3249 $newOptions = $defaultOptions;
3251 if ( $context === null ) {
3252 $context = RequestContext
::getMain();
3255 $optionKinds = $this->getOptionKinds( $context );
3256 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3259 // Use default values for the options that should be deleted, and
3260 // copy old values for the ones that shouldn't.
3261 foreach ( $this->mOptions
as $key => $value ) {
3262 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3263 if ( array_key_exists( $key, $defaultOptions ) ) {
3264 $newOptions[$key] = $defaultOptions[$key];
3267 $newOptions[$key] = $value;
3272 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3274 $this->mOptions
= $newOptions;
3275 $this->mOptionsLoaded
= true;
3279 * Get the user's preferred date format.
3280 * @return string User's preferred date format
3282 public function getDatePreference() {
3283 // Important migration for old data rows
3284 if ( is_null( $this->mDatePreference
) ) {
3286 $value = $this->getOption( 'date' );
3287 $map = $wgLang->getDatePreferenceMigrationMap();
3288 if ( isset( $map[$value] ) ) {
3289 $value = $map[$value];
3291 $this->mDatePreference
= $value;
3293 return $this->mDatePreference
;
3297 * Determine based on the wiki configuration and the user's options,
3298 * whether this user must be over HTTPS no matter what.
3302 public function requiresHTTPS() {
3303 global $wgSecureLogin;
3304 if ( !$wgSecureLogin ) {
3308 $https = $this->getBoolOption( 'prefershttps' );
3309 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3311 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3318 * Get the user preferred stub threshold
3322 public function getStubThreshold() {
3323 global $wgMaxArticleSize; # Maximum article size, in Kb
3324 $threshold = $this->getIntOption( 'stubthreshold' );
3325 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3326 // If they have set an impossible value, disable the preference
3327 // so we can use the parser cache again.
3334 * Get the permissions this user has.
3335 * @return string[] permission names
3337 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3338 * ->getUserPermissions(..) instead
3341 public function getRights() {
3342 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3346 * Get the list of explicit group memberships this user has.
3347 * The implicit * and user groups are not included.
3349 * @return string[] Array of internal group names (sorted since 1.33)
3351 public function getGroups() {
3353 $this->loadGroups();
3354 return array_keys( $this->mGroupMemberships
);
3358 * Get the list of explicit group memberships this user has, stored as
3359 * UserGroupMembership objects. Implicit groups are not included.
3361 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3364 public function getGroupMemberships() {
3366 $this->loadGroups();
3367 return $this->mGroupMemberships
;
3371 * Get the list of implicit group memberships this user has.
3372 * This includes all explicit groups, plus 'user' if logged in,
3373 * '*' for all accounts, and autopromoted groups
3374 * @param bool $recache Whether to avoid the cache
3375 * @return array Array of String internal group names
3377 public function getEffectiveGroups( $recache = false ) {
3378 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3379 $this->mEffectiveGroups
= array_unique( array_merge(
3380 $this->getGroups(), // explicit groups
3381 $this->getAutomaticGroups( $recache ) // implicit groups
3383 // Avoid PHP 7.1 warning of passing $this by reference
3385 // Hook for additional groups
3386 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3387 // Force reindexation of groups when a hook has unset one of them
3388 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3390 return $this->mEffectiveGroups
;
3394 * Get the list of implicit group memberships this user has.
3395 * This includes 'user' if logged in, '*' for all accounts,
3396 * and autopromoted groups
3397 * @param bool $recache Whether to avoid the cache
3398 * @return array Array of String internal group names
3400 public function getAutomaticGroups( $recache = false ) {
3401 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3402 $this->mImplicitGroups
= [ '*' ];
3403 if ( $this->getId() ) {
3404 $this->mImplicitGroups
[] = 'user';
3406 $this->mImplicitGroups
= array_unique( array_merge(
3407 $this->mImplicitGroups
,
3408 Autopromote
::getAutopromoteGroups( $this )
3412 // Assure data consistency with rights/groups,
3413 // as getEffectiveGroups() depends on this function
3414 $this->mEffectiveGroups
= null;
3417 return $this->mImplicitGroups
;
3421 * Returns the groups the user has belonged to.
3423 * The user may still belong to the returned groups. Compare with getGroups().
3425 * The function will not return groups the user had belonged to before MW 1.17
3427 * @return array Names of the groups the user has belonged to.
3429 public function getFormerGroups() {
3432 if ( is_null( $this->mFormerGroups
) ) {
3433 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3434 ?
wfGetDB( DB_MASTER
)
3435 : wfGetDB( DB_REPLICA
);
3436 $res = $db->select( 'user_former_groups',
3438 [ 'ufg_user' => $this->mId
],
3440 $this->mFormerGroups
= [];
3441 foreach ( $res as $row ) {
3442 $this->mFormerGroups
[] = $row->ufg_group
;
3446 return $this->mFormerGroups
;
3450 * Get the user's edit count.
3451 * @return int|null Null for anonymous users
3453 public function getEditCount() {
3454 if ( !$this->getId() ) {
3458 if ( $this->mEditCount
=== null ) {
3459 /* Populate the count, if it has not been populated yet */
3460 $dbr = wfGetDB( DB_REPLICA
);
3461 // check if the user_editcount field has been initialized
3462 $count = $dbr->selectField(
3463 'user', 'user_editcount',
3464 [ 'user_id' => $this->mId
],
3468 if ( $count === null ) {
3469 // it has not been initialized. do so.
3470 $count = $this->initEditCountInternal( $dbr );
3472 $this->mEditCount
= $count;
3474 return (int)$this->mEditCount
;
3478 * Add the user to the given group. This takes immediate effect.
3479 * If the user is already in the group, the expiry time will be updated to the new
3480 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3483 * @param string $group Name of the group to add
3484 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3485 * wfTimestamp(), or null if the group assignment should not expire
3488 public function addGroup( $group, $expiry = null ) {
3490 $this->loadGroups();
3493 $expiry = wfTimestamp( TS_MW
, $expiry );
3496 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3500 // create the new UserGroupMembership and put it in the DB
3501 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3502 if ( !$ugm->insert( true ) ) {
3506 $this->mGroupMemberships
[$group] = $ugm;
3508 // Refresh the groups caches, and clear the rights cache so it will be
3509 // refreshed on the next call to $this->getRights().
3510 $this->getEffectiveGroups( true );
3511 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3512 $this->invalidateCache();
3518 * Remove the user from the given group.
3519 * This takes immediate effect.
3520 * @param string $group Name of the group to remove
3523 public function removeGroup( $group ) {
3526 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3530 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3531 // delete the membership entry
3532 if ( !$ugm ||
!$ugm->delete() ) {
3536 $this->loadGroups();
3537 unset( $this->mGroupMemberships
[$group] );
3539 // Refresh the groups caches, and clear the rights cache so it will be
3540 // refreshed on the next call to $this->getRights().
3541 $this->getEffectiveGroups( true );
3542 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3543 $this->invalidateCache();
3549 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3550 * only this new name and not the old isLoggedIn() variant.
3552 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3553 * anonymous or has no local account (which can happen when importing). This is equivalent to
3554 * getId() != 0 and is provided for code readability.
3557 public function isRegistered() {
3558 return $this->getId() != 0;
3562 * Get whether the user is logged in
3565 public function isLoggedIn() {
3566 return $this->isRegistered();
3570 * Get whether the user is anonymous
3573 public function isAnon() {
3574 return !$this->isRegistered();
3578 * @return bool Whether this user is flagged as being a bot role account
3581 public function isBot() {
3582 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3587 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3593 * Check if user is allowed to access a feature / make an action
3595 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3596 * ->getPermissionManager()->userHasAnyRights(...) instead
3598 * @param string $permissions,... Permissions to test
3599 * @return bool True if user is allowed to perform *any* of the given actions
3600 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3602 public function isAllowedAny() {
3603 return MediaWikiServices
::getInstance()
3604 ->getPermissionManager()
3605 ->userHasAnyRight( $this, ...func_get_args() );
3609 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3610 * ->getPermissionManager()->userHasAllRights(...) instead
3611 * @param string $permissions,... Permissions to test
3612 * @return bool True if the user is allowed to perform *all* of the given actions
3613 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3615 public function isAllowedAll() {
3616 return MediaWikiServices
::getInstance()
3617 ->getPermissionManager()
3618 ->userHasAllRights( $this, ...func_get_args() );
3622 * Internal mechanics of testing a permission
3624 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3625 * ->getPermissionManager()->userHasRight(...) instead
3627 * @param string $action
3631 public function isAllowed( $action = '' ) {
3632 return MediaWikiServices
::getInstance()->getPermissionManager()
3633 ->userHasRight( $this, $action );
3637 * Check whether to enable recent changes patrol features for this user
3638 * @return bool True or false
3640 public function useRCPatrol() {
3641 global $wgUseRCPatrol;
3642 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3646 * Check whether to enable new pages patrol features for this user
3647 * @return bool True or false
3649 public function useNPPatrol() {
3650 global $wgUseRCPatrol, $wgUseNPPatrol;
3652 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3653 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3658 * Check whether to enable new files patrol features for this user
3659 * @return bool True or false
3661 public function useFilePatrol() {
3662 global $wgUseRCPatrol, $wgUseFilePatrol;
3664 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3665 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3670 * Get the WebRequest object to use with this object
3672 * @return WebRequest
3674 public function getRequest() {
3675 if ( $this->mRequest
) {
3676 return $this->mRequest
;
3684 * Check the watched status of an article.
3685 * @since 1.22 $checkRights parameter added
3686 * @param Title $title Title of the article to look at
3687 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3688 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3691 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3692 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3693 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3700 * @since 1.22 $checkRights parameter added
3701 * @param Title $title Title of the article to look at
3702 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3703 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3705 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3706 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3707 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3709 [ $title->getSubjectPage(), $title->getTalkPage() ]
3712 $this->invalidateCache();
3716 * Stop watching an article.
3717 * @since 1.22 $checkRights parameter added
3718 * @param Title $title Title of the article to look at
3719 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3720 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3722 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3723 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3724 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3725 $store->removeWatch( $this, $title->getSubjectPage() );
3726 $store->removeWatch( $this, $title->getTalkPage() );
3728 $this->invalidateCache();
3732 * Clear the user's notification timestamp for the given title.
3733 * If e-notif e-mails are on, they will receive notification mails on
3734 * the next change of the page if it's watched etc.
3735 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3736 * @param Title &$title Title of the article to look at
3737 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3739 public function clearNotification( &$title, $oldid = 0 ) {
3740 global $wgUseEnotif, $wgShowUpdatedMarker;
3742 // Do nothing if the database is locked to writes
3743 if ( wfReadOnly() ) {
3747 // Do nothing if not allowed to edit the watchlist
3748 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3752 // If we're working on user's talk page, we should update the talk page message indicator
3753 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3754 // Avoid PHP 7.1 warning of passing $this by reference
3756 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3760 // Try to update the DB post-send and only if needed...
3761 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3762 if ( !$this->getNewtalk() ) {
3763 return; // no notifications to clear
3766 // Delete the last notifications (they stack up)
3767 $this->setNewtalk( false );
3769 // If there is a new, unseen, revision, use its timestamp
3771 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3774 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3779 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3783 if ( $this->isAnon() ) {
3784 // Nothing else to do...
3788 // Only update the timestamp if the page is being watched.
3789 // The query to find out if it is watched is cached both in memcached and per-invocation,
3790 // and when it does have to be executed, it can be on a replica DB
3791 // If this is the user's newtalk page, we always update the timestamp
3793 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3797 MediaWikiServices
::getInstance()->getWatchedItemStore()
3798 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3802 * Resets all of the given user's page-change notification timestamps.
3803 * If e-notif e-mails are on, they will receive notification mails on
3804 * the next change of any watched page.
3805 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3807 public function clearAllNotifications() {
3808 global $wgUseEnotif, $wgShowUpdatedMarker;
3809 // Do nothing if not allowed to edit the watchlist
3810 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3814 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3815 $this->setNewtalk( false );
3819 $id = $this->getId();
3824 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3825 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3827 // We also need to clear here the "you have new message" notification for the own
3828 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3832 * Compute experienced level based on edit count and registration date.
3834 * @return string 'newcomer', 'learner', or 'experienced'
3836 public function getExperienceLevel() {
3837 global $wgLearnerEdits,
3838 $wgExperiencedUserEdits,
3839 $wgLearnerMemberSince,
3840 $wgExperiencedUserMemberSince;
3842 if ( $this->isAnon() ) {
3846 $editCount = $this->getEditCount();
3847 $registration = $this->getRegistration();
3849 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3850 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3852 if ( $editCount < $wgLearnerEdits ||
3853 $registration > $learnerRegistration ) {
3857 if ( $editCount > $wgExperiencedUserEdits &&
3858 $registration <= $experiencedRegistration
3860 return 'experienced';
3867 * Persist this user's session (e.g. set cookies)
3869 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3871 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3872 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3874 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3876 if ( $this->mId
== 0 ) {
3880 $session = $this->getRequest()->getSession();
3881 if ( $request && $session->getRequest() !== $request ) {
3882 $session = $session->sessionWithRequest( $request );
3884 $delay = $session->delaySave();
3886 if ( !$session->getUser()->equals( $this ) ) {
3887 if ( !$session->canSetUser() ) {
3888 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3889 ->warning( __METHOD__
.
3890 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3894 $session->setUser( $this );
3897 $session->setRememberUser( $rememberMe );
3898 if ( $secure !== null ) {
3899 $session->setForceHTTPS( $secure );
3902 $session->persist();
3904 ScopedCallback
::consume( $delay );
3908 * Log this user out.
3910 public function logout() {
3911 // Avoid PHP 7.1 warning of passing $this by reference
3913 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3919 * Clear the user's session, and reset the instance cache.
3922 public function doLogout() {
3923 $session = $this->getRequest()->getSession();
3924 if ( !$session->canSetUser() ) {
3925 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3926 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3927 $error = 'immutable';
3928 } elseif ( !$session->getUser()->equals( $this ) ) {
3929 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3930 ->warning( __METHOD__
.
3931 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3933 // But we still may as well make this user object anon
3934 $this->clearInstanceCache( 'defaults' );
3935 $error = 'wronguser';
3937 $this->clearInstanceCache( 'defaults' );
3938 $delay = $session->delaySave();
3939 $session->unpersist(); // Clear cookies (T127436)
3940 $session->setLoggedOutTimestamp( time() );
3941 $session->setUser( new User
);
3942 $session->set( 'wsUserID', 0 ); // Other code expects this
3943 $session->resetAllTokens();
3944 ScopedCallback
::consume( $delay );
3947 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3948 'event' => 'logout',
3949 'successful' => $error === false,
3950 'status' => $error ?
: 'success',
3955 * Save this user's settings into the database.
3956 * @todo Only rarely do all these fields need to be set!
3958 public function saveSettings() {
3959 if ( wfReadOnly() ) {
3960 // @TODO: caller should deal with this instead!
3961 // This should really just be an exception.
3962 MWExceptionHandler
::logException( new DBExpectedError(
3964 "Could not update user with ID '{$this->mId}'; DB is read-only."
3970 if ( $this->mId
== 0 ) {
3974 // Get a new user_touched that is higher than the old one.
3975 // This will be used for a CAS check as a last-resort safety
3976 // check against race conditions and replica DB lag.
3977 $newTouched = $this->newTouchedTimestamp();
3979 $dbw = wfGetDB( DB_MASTER
);
3980 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3981 global $wgActorTableSchemaMigrationStage;
3983 $dbw->update( 'user',
3985 'user_name' => $this->mName
,
3986 'user_real_name' => $this->mRealName
,
3987 'user_email' => $this->mEmail
,
3988 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3989 'user_touched' => $dbw->timestamp( $newTouched ),
3990 'user_token' => strval( $this->mToken
),
3991 'user_email_token' => $this->mEmailToken
,
3992 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3993 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3994 'user_id' => $this->mId
,
3998 if ( !$dbw->affectedRows() ) {
3999 // Maybe the problem was a missed cache update; clear it to be safe
4000 $this->clearSharedCache( 'refresh' );
4001 // User was changed in the meantime or loaded with stale data
4002 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4003 LoggerFactory
::getInstance( 'preferences' )->warning(
4004 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4005 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4007 throw new MWException( "CAS update failed on user_touched. " .
4008 "The version of the user to be saved is older than the current version."
4012 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4015 [ 'actor_name' => $this->mName
],
4016 [ 'actor_user' => $this->mId
],
4022 $this->mTouched
= $newTouched;
4023 $this->saveOptions();
4025 Hooks
::run( 'UserSaveSettings', [ $this ] );
4026 $this->clearSharedCache( 'changed' );
4027 $this->getUserPage()->purgeSquid();
4031 * If only this user's username is known, and it exists, return the user ID.
4033 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4036 public function idForName( $flags = 0 ) {
4037 $s = trim( $this->getName() );
4042 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4043 ?
wfGetDB( DB_MASTER
)
4044 : wfGetDB( DB_REPLICA
);
4046 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4047 ?
[ 'LOCK IN SHARE MODE' ]
4050 $id = $db->selectField( 'user',
4051 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4057 * Add a user to the database, return the user object
4059 * @param string $name Username to add
4060 * @param array $params Array of Strings Non-default parameters to save to
4061 * the database as user_* fields:
4062 * - email: The user's email address.
4063 * - email_authenticated: The email authentication timestamp.
4064 * - real_name: The user's real name.
4065 * - options: An associative array of non-default options.
4066 * - token: Random authentication token. Do not set.
4067 * - registration: Registration timestamp. Do not set.
4069 * @return User|null User object, or null if the username already exists.
4071 public static function createNew( $name, $params = [] ) {
4072 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4073 if ( isset( $params[$field] ) ) {
4074 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4075 unset( $params[$field] );
4081 $user->setToken(); // init token
4082 if ( isset( $params['options'] ) ) {
4083 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4084 unset( $params['options'] );
4086 $dbw = wfGetDB( DB_MASTER
);
4088 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4091 'user_name' => $name,
4092 'user_password' => $noPass,
4093 'user_newpassword' => $noPass,
4094 'user_email' => $user->mEmail
,
4095 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4096 'user_real_name' => $user->mRealName
,
4097 'user_token' => strval( $user->mToken
),
4098 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4099 'user_editcount' => 0,
4100 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4102 foreach ( $params as $name => $value ) {
4103 $fields["user_$name"] = $value;
4106 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4107 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4108 if ( $dbw->affectedRows() ) {
4109 $newUser = self
::newFromId( $dbw->insertId() );
4110 $newUser->mName
= $fields['user_name'];
4111 $newUser->updateActorId( $dbw );
4112 // Load the user from master to avoid replica lag
4113 $newUser->load( self
::READ_LATEST
);
4122 * Add this existing user object to the database. If the user already
4123 * exists, a fatal status object is returned, and the user object is
4124 * initialised with the data from the database.
4126 * Previously, this function generated a DB error due to a key conflict
4127 * if the user already existed. Many extension callers use this function
4128 * in code along the lines of:
4130 * $user = User::newFromName( $name );
4131 * if ( !$user->isLoggedIn() ) {
4132 * $user->addToDatabase();
4134 * // do something with $user...
4136 * However, this was vulnerable to a race condition (T18020). By
4137 * initialising the user object if the user exists, we aim to support this
4138 * calling sequence as far as possible.
4140 * Note that if the user exists, this function will acquire a write lock,
4141 * so it is still advisable to make the call conditional on isLoggedIn(),
4142 * and to commit the transaction after calling.
4144 * @throws MWException
4147 public function addToDatabase() {
4149 if ( !$this->mToken
) {
4150 $this->setToken(); // init token
4153 if ( !is_string( $this->mName
) ) {
4154 throw new RuntimeException( "User name field is not set." );
4157 $this->mTouched
= $this->newTouchedTimestamp();
4159 $dbw = wfGetDB( DB_MASTER
);
4160 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4161 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4162 $dbw->insert( 'user',
4164 'user_name' => $this->mName
,
4165 'user_password' => $noPass,
4166 'user_newpassword' => $noPass,
4167 'user_email' => $this->mEmail
,
4168 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4169 'user_real_name' => $this->mRealName
,
4170 'user_token' => strval( $this->mToken
),
4171 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4172 'user_editcount' => 0,
4173 'user_touched' => $dbw->timestamp( $this->mTouched
),
4177 if ( !$dbw->affectedRows() ) {
4178 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4179 $this->mId
= $dbw->selectField(
4182 [ 'user_name' => $this->mName
],
4184 [ 'LOCK IN SHARE MODE' ]
4187 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4191 throw new MWException( $fname . ": hit a key conflict attempting " .
4192 "to insert user '{$this->mName}' row, but it was not present in select!" );
4194 return Status
::newFatal( 'userexists' );
4196 $this->mId
= $dbw->insertId();
4197 self
::$idCacheByName[$this->mName
] = $this->mId
;
4198 $this->updateActorId( $dbw );
4200 return Status
::newGood();
4202 if ( !$status->isGood() ) {
4206 // Clear instance cache other than user table data and actor, which is already accurate
4207 $this->clearInstanceCache();
4209 $this->saveOptions();
4210 return Status
::newGood();
4214 * Update the actor ID after an insert
4215 * @param IDatabase $dbw Writable database handle
4217 private function updateActorId( IDatabase
$dbw ) {
4218 global $wgActorTableSchemaMigrationStage;
4220 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4223 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4226 $this->mActorId
= (int)$dbw->insertId();
4231 * If this user is logged-in and blocked,
4232 * block any IP address they've successfully logged in from.
4233 * @return bool A block was spread
4235 public function spreadAnyEditBlock() {
4236 if ( $this->isLoggedIn() && $this->getBlock() ) {
4237 return $this->spreadBlock();
4244 * If this (non-anonymous) user is blocked,
4245 * block the IP address they've successfully logged in from.
4246 * @return bool A block was spread
4248 protected function spreadBlock() {
4249 wfDebug( __METHOD__
. "()\n" );
4251 if ( $this->mId
== 0 ) {
4255 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4256 if ( !$userblock ) {
4260 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4264 * Get whether the user is explicitly blocked from account creation.
4265 * @return bool|AbstractBlock
4267 public function isBlockedFromCreateAccount() {
4268 $this->getBlockedStatus();
4269 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4270 return $this->mBlock
;
4273 # T15611: if the IP address the user is trying to create an account from is
4274 # blocked with createaccount disabled, prevent new account creation there even
4275 # when the user is logged in
4276 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4277 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4278 null, $this->getRequest()->getIP()
4281 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4282 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4283 ?
$this->mBlockedFromCreateAccount
4288 * Get whether the user is blocked from using Special:Emailuser.
4291 public function isBlockedFromEmailuser() {
4292 $this->getBlockedStatus();
4293 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4297 * Get whether the user is blocked from using Special:Upload
4302 public function isBlockedFromUpload() {
4303 $this->getBlockedStatus();
4304 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4308 * Get whether the user is allowed to create an account.
4311 public function isAllowedToCreateAccount() {
4312 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4316 * Get this user's personal page title.
4318 * @return Title User's personal page title
4320 public function getUserPage() {
4321 return Title
::makeTitle( NS_USER
, $this->getName() );
4325 * Get this user's talk page title.
4327 * @return Title User's talk page title
4329 public function getTalkPage() {
4330 $title = $this->getUserPage();
4331 return $title->getTalkPage();
4335 * Determine whether the user is a newbie. Newbies are either
4336 * anonymous IPs, or the most recently created accounts.
4339 public function isNewbie() {
4340 return !$this->isAllowed( 'autoconfirmed' );
4344 * Check to see if the given clear-text password is one of the accepted passwords
4345 * @deprecated since 1.27, use AuthManager instead
4346 * @param string $password User password
4347 * @return bool True if the given password is correct, otherwise False
4349 public function checkPassword( $password ) {
4350 wfDeprecated( __METHOD__
, '1.27' );
4352 $manager = AuthManager
::singleton();
4353 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4354 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4356 'username' => $this->getName(),
4357 'password' => $password,
4360 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4361 switch ( $res->status
) {
4362 case AuthenticationResponse
::PASS
:
4364 case AuthenticationResponse
::FAIL
:
4365 // Hope it's not a PreAuthenticationProvider that failed...
4366 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4367 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4370 throw new BadMethodCallException(
4371 'AuthManager returned a response unsupported by ' . __METHOD__
4377 * Check if the given clear-text password matches the temporary password
4378 * sent by e-mail for password reset operations.
4380 * @deprecated since 1.27, use AuthManager instead
4381 * @param string $plaintext
4382 * @return bool True if matches, false otherwise
4384 public function checkTemporaryPassword( $plaintext ) {
4385 wfDeprecated( __METHOD__
, '1.27' );
4386 // Can't check the temporary password individually.
4387 return $this->checkPassword( $plaintext );
4391 * Initialize (if necessary) and return a session token value
4392 * which can be used in edit forms to show that the user's
4393 * login credentials aren't being hijacked with a foreign form
4397 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4398 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4399 * @return MediaWiki\Session\Token The new edit token
4401 public function getEditTokenObject( $salt = '', $request = null ) {
4402 if ( $this->isAnon() ) {
4403 return new LoggedOutEditToken();
4407 $request = $this->getRequest();
4409 return $request->getSession()->getToken( $salt );
4413 * Initialize (if necessary) and return a session token value
4414 * which can be used in edit forms to show that the user's
4415 * login credentials aren't being hijacked with a foreign form
4418 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4421 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4422 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4423 * @return string The new edit token
4425 public function getEditToken( $salt = '', $request = null ) {
4426 return $this->getEditTokenObject( $salt, $request )->toString();
4430 * Check given value against the token value stored in the session.
4431 * A match should confirm that the form was submitted from the
4432 * user's own login session, not a form submission from a third-party
4435 * @param string $val Input value to compare
4436 * @param string|array $salt Optional function-specific data for hashing
4437 * @param WebRequest|null $request Object to use or null to use $wgRequest
4438 * @param int|null $maxage Fail tokens older than this, in seconds
4439 * @return bool Whether the token matches
4441 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4442 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4446 * Check given value against the token value stored in the session,
4447 * ignoring the suffix.
4449 * @param string $val Input value to compare
4450 * @param string|array $salt Optional function-specific data for hashing
4451 * @param WebRequest|null $request Object to use or null to use $wgRequest
4452 * @param int|null $maxage Fail tokens older than this, in seconds
4453 * @return bool Whether the token matches
4455 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4456 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4457 return $this->matchEditToken( $val, $salt, $request, $maxage );
4461 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4462 * mail to the user's given address.
4464 * @param string $type Message to send, either "created", "changed" or "set"
4467 public function sendConfirmationMail( $type = 'created' ) {
4469 $expiration = null; // gets passed-by-ref and defined in next line.
4470 $token = $this->confirmationToken( $expiration );
4471 $url = $this->confirmationTokenUrl( $token );
4472 $invalidateURL = $this->invalidationTokenUrl( $token );
4473 $this->saveSettings();
4475 if ( $type == 'created' ||
$type === false ) {
4476 $message = 'confirmemail_body';
4478 } elseif ( $type === true ) {
4479 $message = 'confirmemail_body_changed';
4482 // Messages: confirmemail_body_changed, confirmemail_body_set
4483 $message = 'confirmemail_body_' . $type;
4487 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4488 'body' => wfMessage( $message,
4489 $this->getRequest()->getIP(),
4492 $wgLang->userTimeAndDate( $expiration, $this ),
4494 $wgLang->userDate( $expiration, $this ),
4495 $wgLang->userTime( $expiration, $this ) )->text(),
4501 'ip' => $this->getRequest()->getIP(),
4502 'confirmURL' => $url,
4503 'invalidateURL' => $invalidateURL,
4504 'expiration' => $expiration
4507 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4508 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4512 * Send an e-mail to this user's account. Does not check for
4513 * confirmed status or validity.
4515 * @param string $subject Message subject
4516 * @param string $body Message body
4517 * @param User|null $from Optional sending user; if unspecified, default
4518 * $wgPasswordSender will be used.
4519 * @param MailAddress|null $replyto Reply-To address
4522 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4523 global $wgPasswordSender;
4525 if ( $from instanceof User
) {
4526 $sender = MailAddress
::newFromUser( $from );
4528 $sender = new MailAddress( $wgPasswordSender,
4529 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4531 $to = MailAddress
::newFromUser( $this );
4533 return UserMailer
::send( $to, $sender, $subject, $body, [
4534 'replyTo' => $replyto,
4539 * Generate, store, and return a new e-mail confirmation code.
4540 * A hash (unsalted, since it's used as a key) is stored.
4542 * @note Call saveSettings() after calling this function to commit
4543 * this change to the database.
4545 * @param string &$expiration Accepts the expiration time
4546 * @return string New token
4548 protected function confirmationToken( &$expiration ) {
4549 global $wgUserEmailConfirmationTokenExpiry;
4551 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4552 $expiration = wfTimestamp( TS_MW
, $expires );
4554 $token = MWCryptRand
::generateHex( 32 );
4555 $hash = md5( $token );
4556 $this->mEmailToken
= $hash;
4557 $this->mEmailTokenExpires
= $expiration;
4562 * Return a URL the user can use to confirm their email address.
4563 * @param string $token Accepts the email confirmation token
4564 * @return string New token URL
4566 protected function confirmationTokenUrl( $token ) {
4567 return $this->getTokenUrl( 'ConfirmEmail', $token );
4571 * Return a URL the user can use to invalidate their email address.
4572 * @param string $token Accepts the email confirmation token
4573 * @return string New token URL
4575 protected function invalidationTokenUrl( $token ) {
4576 return $this->getTokenUrl( 'InvalidateEmail', $token );
4580 * Internal function to format the e-mail validation/invalidation URLs.
4581 * This uses a quickie hack to use the
4582 * hardcoded English names of the Special: pages, for ASCII safety.
4584 * @note Since these URLs get dropped directly into emails, using the
4585 * short English names avoids insanely long URL-encoded links, which
4586 * also sometimes can get corrupted in some browsers/mailers
4587 * (T8957 with Gmail and Internet Explorer).
4589 * @param string $page Special page
4590 * @param string $token
4591 * @return string Formatted URL
4593 protected function getTokenUrl( $page, $token ) {
4594 // Hack to bypass localization of 'Special:'
4595 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4596 return $title->getCanonicalURL();
4600 * Mark the e-mail address confirmed.
4602 * @note Call saveSettings() after calling this function to commit the change.
4606 public function confirmEmail() {
4607 // Check if it's already confirmed, so we don't touch the database
4608 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4609 if ( !$this->isEmailConfirmed() ) {
4610 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4611 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4617 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4618 * address if it was already confirmed.
4620 * @note Call saveSettings() after calling this function to commit the change.
4621 * @return bool Returns true
4623 public function invalidateEmail() {
4625 $this->mEmailToken
= null;
4626 $this->mEmailTokenExpires
= null;
4627 $this->setEmailAuthenticationTimestamp( null );
4629 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4634 * Set the e-mail authentication timestamp.
4635 * @param string $timestamp TS_MW timestamp
4637 public function setEmailAuthenticationTimestamp( $timestamp ) {
4639 $this->mEmailAuthenticated
= $timestamp;
4640 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4644 * Is this user allowed to send e-mails within limits of current
4645 * site configuration?
4648 public function canSendEmail() {
4649 global $wgEnableEmail, $wgEnableUserEmail;
4650 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4653 $canSend = $this->isEmailConfirmed();
4654 // Avoid PHP 7.1 warning of passing $this by reference
4656 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4661 * Is this user allowed to receive e-mails within limits of current
4662 * site configuration?
4665 public function canReceiveEmail() {
4666 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4670 * Is this user's e-mail address valid-looking and confirmed within
4671 * limits of the current site configuration?
4673 * @note If $wgEmailAuthentication is on, this may require the user to have
4674 * confirmed their address by returning a code or using a password
4675 * sent to the address from the wiki.
4679 public function isEmailConfirmed() {
4680 global $wgEmailAuthentication;
4682 // Avoid PHP 7.1 warning of passing $this by reference
4685 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4686 if ( $this->isAnon() ) {
4689 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4692 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4702 * Check whether there is an outstanding request for e-mail confirmation.
4705 public function isEmailConfirmationPending() {
4706 global $wgEmailAuthentication;
4707 return $wgEmailAuthentication &&
4708 !$this->isEmailConfirmed() &&
4709 $this->mEmailToken
&&
4710 $this->mEmailTokenExpires
> wfTimestamp();
4714 * Get the timestamp of account creation.
4716 * @return string|bool|null Timestamp of account creation, false for
4717 * non-existent/anonymous user accounts, or null if existing account
4718 * but information is not in database.
4720 public function getRegistration() {
4721 if ( $this->isAnon() ) {
4725 return $this->mRegistration
;
4729 * Get the timestamp of the first edit
4731 * @return string|bool Timestamp of first edit, or false for
4732 * non-existent/anonymous user accounts.
4734 public function getFirstEditTimestamp() {
4735 return $this->getEditTimestamp( true );
4739 * Get the timestamp of the latest edit
4742 * @return string|bool Timestamp of first edit, or false for
4743 * non-existent/anonymous user accounts.
4745 public function getLatestEditTimestamp() {
4746 return $this->getEditTimestamp( false );
4750 * Get the timestamp of the first or latest edit
4752 * @param bool $first True for the first edit, false for the latest one
4753 * @return string|bool Timestamp of first or latest edit, or false for
4754 * non-existent/anonymous user accounts.
4756 private function getEditTimestamp( $first ) {
4757 if ( $this->getId() == 0 ) {
4758 return false; // anons
4760 $dbr = wfGetDB( DB_REPLICA
);
4761 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4762 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4763 ?
'revactor_timestamp' : 'rev_timestamp';
4764 $sortOrder = $first ?
'ASC' : 'DESC';
4765 $time = $dbr->selectField(
4766 [ 'revision' ] +
$actorWhere['tables'],
4768 [ $actorWhere['conds'] ],
4770 [ 'ORDER BY' => "$tsField $sortOrder" ],
4771 $actorWhere['joins']
4774 return false; // no edits
4776 return wfTimestamp( TS_MW
, $time );
4780 * Get the permissions associated with a given list of groups
4782 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4783 * ->getGroupPermissions() instead
4785 * @param array $groups Array of Strings List of internal group names
4786 * @return array Array of Strings List of permission key names for given groups combined
4788 public static function getGroupPermissions( $groups ) {
4789 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4793 * Get all the groups who have a given permission
4795 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4796 * ->getGroupsWithPermission() instead
4798 * @param string $role Role to check
4799 * @return array Array of Strings List of internal group names with the given permission
4801 public static function getGroupsWithPermission( $role ) {
4802 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4806 * Check, if the given group has the given permission
4808 * If you're wanting to check whether all users have a permission, use
4809 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4812 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4813 * ->groupHasPermission(..) instead
4816 * @param string $group Group to check
4817 * @param string $role Role to check
4820 public static function groupHasPermission( $group, $role ) {
4821 return MediaWikiServices
::getInstance()->getPermissionManager()
4822 ->groupHasPermission( $group, $role );
4826 * Check if all users may be assumed to have the given permission
4828 * We generally assume so if the right is granted to '*' and isn't revoked
4829 * on any group. It doesn't attempt to take grants or other extension
4830 * limitations on rights into account in the general case, though, as that
4831 * would require it to always return false and defeat the purpose.
4832 * Specifically, session-based rights restrictions (such as OAuth or bot
4833 * passwords) are applied based on the current session.
4835 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4836 * ->isEveryoneAllowed() instead
4838 * @param string $right Right to check
4843 public static function isEveryoneAllowed( $right ) {
4844 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4848 * Return the set of defined explicit groups.
4849 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4850 * are not included, as they are defined automatically, not in the database.
4851 * @return array Array of internal group names
4853 public static function getAllGroups() {
4854 global $wgGroupPermissions, $wgRevokePermissions;
4855 return array_values( array_diff(
4856 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4857 self
::getImplicitGroups()
4862 * Get a list of all available permissions.
4864 * @deprecated since 1.34, use PermissionManager::getAllPermissions() instead
4866 * @return string[] Array of permission names
4868 public static function getAllRights() {
4869 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4873 * Get a list of implicit groups
4874 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4876 * @return array Array of Strings Array of internal group names
4878 public static function getImplicitGroups() {
4879 global $wgImplicitGroups;
4880 return $wgImplicitGroups;
4884 * Returns an array of the groups that a particular group can add/remove.
4886 * @param string $group The group to check for whether it can add/remove
4887 * @return array [ 'add' => [ addablegroups ],
4888 * 'remove' => [ removablegroups ],
4889 * 'add-self' => [ addablegroups to self ],
4890 * 'remove-self' => [ removable groups from self ] ]
4892 public static function changeableByGroup( $group ) {
4893 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4902 if ( empty( $wgAddGroups[$group] ) ) {
4903 // Don't add anything to $groups
4904 } elseif ( $wgAddGroups[$group] === true ) {
4905 // You get everything
4906 $groups['add'] = self
::getAllGroups();
4907 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4908 $groups['add'] = $wgAddGroups[$group];
4911 // Same thing for remove
4912 if ( empty( $wgRemoveGroups[$group] ) ) {
4914 } elseif ( $wgRemoveGroups[$group] === true ) {
4915 $groups['remove'] = self
::getAllGroups();
4916 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4917 $groups['remove'] = $wgRemoveGroups[$group];
4920 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4921 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4922 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4923 if ( is_int( $key ) ) {
4924 $wgGroupsAddToSelf['user'][] = $value;
4929 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4930 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4931 if ( is_int( $key ) ) {
4932 $wgGroupsRemoveFromSelf['user'][] = $value;
4937 // Now figure out what groups the user can add to him/herself
4938 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4940 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4941 // No idea WHY this would be used, but it's there
4942 $groups['add-self'] = self
::getAllGroups();
4943 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4944 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4947 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4949 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4950 $groups['remove-self'] = self
::getAllGroups();
4951 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4952 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4959 * Returns an array of groups that this user can add and remove
4960 * @return array [ 'add' => [ addablegroups ],
4961 * 'remove' => [ removablegroups ],
4962 * 'add-self' => [ addablegroups to self ],
4963 * 'remove-self' => [ removable groups from self ] ]
4965 public function changeableGroups() {
4966 if ( $this->isAllowed( 'userrights' ) ) {
4967 // This group gives the right to modify everything (reverse-
4968 // compatibility with old "userrights lets you change
4970 // Using array_merge to make the groups reindexed
4971 $all = array_merge( self
::getAllGroups() );
4980 // Okay, it's not so simple, we will have to go through the arrays
4987 $addergroups = $this->getEffectiveGroups();
4989 foreach ( $addergroups as $addergroup ) {
4990 $groups = array_merge_recursive(
4991 $groups, $this->changeableByGroup( $addergroup )
4993 $groups['add'] = array_unique( $groups['add'] );
4994 $groups['remove'] = array_unique( $groups['remove'] );
4995 $groups['add-self'] = array_unique( $groups['add-self'] );
4996 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5002 * Schedule a deferred update to update the user's edit count
5004 public function incEditCount() {
5005 if ( $this->isAnon() ) {
5009 DeferredUpdates
::addUpdate(
5010 new UserEditCountUpdate( $this, 1 ),
5011 DeferredUpdates
::POSTSEND
5016 * This method should not be called outside User/UserEditCountUpdate
5020 public function setEditCountInternal( $count ) {
5021 $this->mEditCount
= $count;
5025 * Initialize user_editcount from data out of the revision table
5027 * @internal This method should not be called outside User/UserEditCountUpdate
5028 * @param IDatabase $dbr Replica database
5029 * @return int Number of edits
5031 public function initEditCountInternal( IDatabase
$dbr ) {
5032 // Pull from a replica DB to be less cruel to servers
5033 // Accuracy isn't the point anyway here
5034 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5035 $count = (int)$dbr->selectField(
5036 [ 'revision' ] +
$actorWhere['tables'],
5038 [ $actorWhere['conds'] ],
5041 $actorWhere['joins']
5044 $dbw = wfGetDB( DB_MASTER
);
5047 [ 'user_editcount' => $count ],
5049 'user_id' => $this->getId(),
5050 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5059 * Get the description of a given right
5062 * @param string $right Right to query
5063 * @return string Localized description of the right
5065 public static function getRightDescription( $right ) {
5066 $key = "right-$right";
5067 $msg = wfMessage( $key );
5068 return $msg->isDisabled() ?
$right : $msg->text();
5072 * Get the name of a given grant
5075 * @param string $grant Grant to query
5076 * @return string Localized name of the grant
5078 public static function getGrantName( $grant ) {
5079 $key = "grant-$grant";
5080 $msg = wfMessage( $key );
5081 return $msg->isDisabled() ?
$grant : $msg->text();
5085 * Add a newuser log entry for this user.
5086 * Before 1.19 the return value was always true.
5088 * @deprecated since 1.27, AuthManager handles logging
5089 * @param string|bool $action Account creation type.
5090 * - String, one of the following values:
5091 * - 'create' for an anonymous user creating an account for himself.
5092 * This will force the action's performer to be the created user itself,
5093 * no matter the value of $wgUser
5094 * - 'create2' for a logged in user creating an account for someone else
5095 * - 'byemail' when the created user will receive its password by e-mail
5096 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5097 * - Boolean means whether the account was created by e-mail (deprecated):
5098 * - true will be converted to 'byemail'
5099 * - false will be converted to 'create' if this object is the same as
5100 * $wgUser and to 'create2' otherwise
5101 * @param string $reason User supplied reason
5104 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5105 return true; // disabled
5109 * Add an autocreate newuser log entry for this user
5110 * Used by things like CentralAuth and perhaps other authplugins.
5111 * Consider calling addNewUserLogEntry() directly instead.
5113 * @deprecated since 1.27, AuthManager handles logging
5116 public function addNewUserLogEntryAutoCreate() {
5117 wfDeprecated( __METHOD__
, '1.27' );
5118 $this->addNewUserLogEntry( 'autocreate' );
5124 * Load the user options either from cache, the database or an array
5126 * @param array|null $data Rows for the current user out of the user_properties table
5128 protected function loadOptions( $data = null ) {
5131 if ( $this->mOptionsLoaded
) {
5135 $this->mOptions
= self
::getDefaultOptions();
5137 if ( !$this->getId() ) {
5138 // For unlogged-in users, load language/variant options from request.
5139 // There's no need to do it for logged-in users: they can set preferences,
5140 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5141 // so don't override user's choice (especially when the user chooses site default).
5142 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5143 $this->mOptions
['variant'] = $variant;
5144 $this->mOptions
['language'] = $variant;
5145 $this->mOptionsLoaded
= true;
5149 // Maybe load from the object
5150 if ( !is_null( $this->mOptionOverrides
) ) {
5151 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5152 foreach ( $this->mOptionOverrides
as $key => $value ) {
5153 $this->mOptions
[$key] = $value;
5156 if ( !is_array( $data ) ) {
5157 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5158 // Load from database
5159 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5160 ?
wfGetDB( DB_MASTER
)
5161 : wfGetDB( DB_REPLICA
);
5163 $res = $dbr->select(
5165 [ 'up_property', 'up_value' ],
5166 [ 'up_user' => $this->getId() ],
5170 $this->mOptionOverrides
= [];
5172 foreach ( $res as $row ) {
5173 // Convert '0' to 0. PHP's boolean conversion considers them both
5174 // false, but e.g. JavaScript considers the former as true.
5175 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5176 // and convert all values here.
5177 if ( $row->up_value
=== '0' ) {
5180 $data[$row->up_property
] = $row->up_value
;
5184 foreach ( $data as $property => $value ) {
5185 $this->mOptionOverrides
[$property] = $value;
5186 $this->mOptions
[$property] = $value;
5190 // Replace deprecated language codes
5191 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5192 $this->mOptions
['language']
5195 $this->mOptionsLoaded
= true;
5197 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5201 * Saves the non-default options for this user, as previously set e.g. via
5202 * setOption(), in the database's "user_properties" (preferences) table.
5203 * Usually used via saveSettings().
5205 protected function saveOptions() {
5206 $this->loadOptions();
5208 // Not using getOptions(), to keep hidden preferences in database
5209 $saveOptions = $this->mOptions
;
5211 // Allow hooks to abort, for instance to save to a global profile.
5212 // Reset options to default state before saving.
5213 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5217 $userId = $this->getId();
5219 $insert_rows = []; // all the new preference rows
5220 foreach ( $saveOptions as $key => $value ) {
5221 // Don't bother storing default values
5222 $defaultOption = self
::getDefaultOption( $key );
5223 if ( ( $defaultOption === null && $value !== false && $value !== null )
5224 ||
$value != $defaultOption
5227 'up_user' => $userId,
5228 'up_property' => $key,
5229 'up_value' => $value,
5234 $dbw = wfGetDB( DB_MASTER
);
5236 $res = $dbw->select( 'user_properties',
5237 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5239 // Find prior rows that need to be removed or updated. These rows will
5240 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5242 foreach ( $res as $row ) {
5243 if ( !isset( $saveOptions[$row->up_property
] )
5244 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5246 $keysDelete[] = $row->up_property
;
5250 if ( count( $keysDelete ) ) {
5251 // Do the DELETE by PRIMARY KEY for prior rows.
5252 // In the past a very large portion of calls to this function are for setting
5253 // 'rememberpassword' for new accounts (a preference that has since been removed).
5254 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5255 // caused gap locks on [max user ID,+infinity) which caused high contention since
5256 // updates would pile up on each other as they are for higher (newer) user IDs.
5257 // It might not be necessary these days, but it shouldn't hurt either.
5258 $dbw->delete( 'user_properties',
5259 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5261 // Insert the new preference rows
5262 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5266 * Return the list of user fields that should be selected to create
5267 * a new user object.
5268 * @deprecated since 1.31, use self::getQueryInfo() instead.
5271 public static function selectFields() {
5272 wfDeprecated( __METHOD__
, '1.31' );
5280 'user_email_authenticated',
5282 'user_email_token_expires',
5283 'user_registration',
5289 * Return the tables, fields, and join conditions to be selected to create
5290 * a new user object.
5292 * @return array With three keys:
5293 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5294 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5295 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5297 public static function getQueryInfo() {
5298 global $wgActorTableSchemaMigrationStage;
5301 'tables' => [ 'user' ],
5309 'user_email_authenticated',
5311 'user_email_token_expires',
5312 'user_registration',
5318 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5319 // but it does little harm and might be needed for write callers loading a User.
5320 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5321 $ret['tables']['user_actor'] = 'actor';
5322 $ret['fields'][] = 'user_actor.actor_id';
5323 $ret['joins']['user_actor'] = [
5324 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5325 [ 'user_actor.actor_user = user_id' ]
5333 * Factory function for fatal permission-denied errors
5336 * @param string $permission User right required
5339 static function newFatalPermissionDeniedStatus( $permission ) {
5343 foreach ( MediaWikiServices
::getInstance()
5344 ->getPermissionManager()
5345 ->getGroupsWithPermission( $permission ) as $group ) {
5346 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5350 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5353 return Status
::newFatal( 'badaccess-group0' );
5357 * Get a new instance of this user that was loaded from the master via a locking read
5359 * Use this instead of the main context User when updating that user. This avoids races
5360 * where that user was loaded from a replica DB or even the master but without proper locks.
5362 * @return User|null Returns null if the user was not found in the DB
5365 public function getInstanceForUpdate() {
5366 if ( !$this->getId() ) {
5367 return null; // anon
5370 $user = self
::newFromId( $this->getId() );
5371 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5379 * Checks if two user objects point to the same user.
5381 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5382 * @param UserIdentity $user
5385 public function equals( UserIdentity
$user ) {
5386 // XXX it's not clear whether central ID providers are supposed to obey this
5387 return $this->getName() === $user->getName();
5391 * Checks if usertalk is allowed
5395 public function isAllowUsertalk() {
5396 return $this->mAllowUsertalk
;