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
115 * @var string[] Cached results of getAllRights()
117 protected static $mAllRights = false;
119 /** Cache variables */
132 /** @var string TS_MW timestamp from the DB */
134 /** @var string TS_MW timestamp from cache */
135 protected $mQuickTouched;
139 public $mEmailAuthenticated;
141 protected $mEmailToken;
143 protected $mEmailTokenExpires;
145 protected $mRegistration;
147 protected $mEditCount;
148 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
149 protected $mGroupMemberships;
151 protected $mOptionOverrides;
156 * @var bool Whether the cache variables have been loaded.
158 public $mOptionsLoaded;
161 * @var array|bool Array with already loaded items or true if all items have been loaded.
163 protected $mLoadedItems = [];
167 * @var string Initialization data source if mLoadedItems!==true. May be one of:
168 * - 'defaults' anonymous user initialised from class defaults
169 * - 'name' initialise from mName
170 * - 'id' initialise from mId
171 * - 'actor' initialise from mActorId
172 * - 'session' log in from session if possible
174 * Use the User::newFrom*() family of functions to set this.
179 * Lazy-initialized variables, invalidated with clearInstanceCache
184 protected $mDatePreference;
190 protected $mBlockreason;
192 protected $mEffectiveGroups;
194 protected $mImplicitGroups;
196 protected $mFormerGroups;
197 /** @var AbstractBlock */
198 protected $mGlobalBlock;
206 /** @var WebRequest */
209 /** @var AbstractBlock */
213 protected $mAllowUsertalk;
215 /** @var AbstractBlock|bool */
216 private $mBlockedFromCreateAccount = false;
218 /** @var int User::READ_* constant bitfield used to load data */
219 protected $queryFlagsUsed = self
::READ_NORMAL
;
222 public static $idCacheByName = [];
225 * Lightweight constructor for an anonymous user.
226 * Use the User::newFrom* factory functions for other kinds of users.
230 * @see newFromActorId()
231 * @see newFromConfirmationCode()
232 * @see newFromSession()
235 public function __construct() {
236 $this->clearInstanceCache( 'defaults' );
242 public function __toString() {
243 return (string)$this->getName();
246 public function &__get( $name ) {
247 // A shortcut for $mRights deprecation phase
248 if ( $name === 'mRights' ) {
249 $copy = $this->getRights();
251 } elseif ( !property_exists( $this, $name ) ) {
252 // T227688 - do not break $u->foo['bar'] = 1
253 wfLogWarning( 'tried to get non-existent property' );
257 wfLogWarning( 'tried to get non-visible property' );
262 public function __set( $name, $value ) {
263 // A shortcut for $mRights deprecation phase, only known legitimate use was for
264 // testing purposes, other uses seem bad in principle
265 if ( $name === 'mRights' ) {
266 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
268 is_null( $value ) ?
[] : $value
270 } elseif ( !property_exists( $this, $name ) ) {
271 $this->$name = $value;
273 wfLogWarning( 'tried to set non-visible property' );
278 * Test if it's safe to load this User object.
280 * You should typically check this before using $wgUser or
281 * RequestContext::getUser in a method that might be called before the
282 * system has been fully initialized. If the object is unsafe, you should
283 * use an anonymous user:
285 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
291 public function isSafeToLoad() {
292 global $wgFullyInitialised;
294 // The user is safe to load if:
295 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
296 // * mLoadedItems === true (already loaded)
297 // * mFrom !== 'session' (sessions not involved at all)
299 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
300 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
304 * Load the user table data for this object from the source given by mFrom.
306 * @param int $flags User::READ_* constant bitfield
308 public function load( $flags = self
::READ_NORMAL
) {
309 global $wgFullyInitialised;
311 if ( $this->mLoadedItems
=== true ) {
315 // Set it now to avoid infinite recursion in accessors
316 $oldLoadedItems = $this->mLoadedItems
;
317 $this->mLoadedItems
= true;
318 $this->queryFlagsUsed
= $flags;
320 // If this is called too early, things are likely to break.
321 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
322 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
323 ->warning( 'User::loadFromSession called before the end of Setup.php', [
324 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
326 $this->loadDefaults();
327 $this->mLoadedItems
= $oldLoadedItems;
331 switch ( $this->mFrom
) {
333 $this->loadDefaults();
336 // Make sure this thread sees its own changes
337 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
338 if ( $lb->hasOrMadeRecentMasterChanges() ) {
339 $flags |
= self
::READ_LATEST
;
340 $this->queryFlagsUsed
= $flags;
343 $this->mId
= self
::idFromName( $this->mName
, $flags );
345 // Nonexistent user placeholder object
346 $this->loadDefaults( $this->mName
);
348 $this->loadFromId( $flags );
352 // Make sure this thread sees its own changes, if the ID isn't 0
353 if ( $this->mId
!= 0 ) {
354 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
355 if ( $lb->hasOrMadeRecentMasterChanges() ) {
356 $flags |
= self
::READ_LATEST
;
357 $this->queryFlagsUsed
= $flags;
361 $this->loadFromId( $flags );
364 // Make sure this thread sees its own changes
365 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
366 if ( $lb->hasOrMadeRecentMasterChanges() ) {
367 $flags |
= self
::READ_LATEST
;
368 $this->queryFlagsUsed
= $flags;
371 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
372 $row = wfGetDB( $index )->selectRow(
374 [ 'actor_user', 'actor_name' ],
375 [ 'actor_id' => $this->mActorId
],
382 $this->loadDefaults();
383 } elseif ( $row->actor_user
) {
384 $this->mId
= $row->actor_user
;
385 $this->loadFromId( $flags );
387 $this->loadDefaults( $row->actor_name
);
391 if ( !$this->loadFromSession() ) {
392 // Loading from session failed. Load defaults.
393 $this->loadDefaults();
395 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
398 throw new UnexpectedValueException(
399 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
404 * Load user table data, given mId has already been set.
405 * @param int $flags User::READ_* constant bitfield
406 * @return bool False if the ID does not exist, true otherwise
408 public function loadFromId( $flags = self
::READ_NORMAL
) {
409 if ( $this->mId
== 0 ) {
410 // Anonymous users are not in the database (don't need cache)
411 $this->loadDefaults();
415 // Try cache (unless this needs data from the master DB).
416 // NOTE: if this thread called saveSettings(), the cache was cleared.
417 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
419 if ( !$this->loadFromDatabase( $flags ) ) {
420 // Can't load from ID
424 $this->loadFromCache();
427 $this->mLoadedItems
= true;
428 $this->queryFlagsUsed
= $flags;
435 * @param string $dbDomain
438 public static function purge( $dbDomain, $userId ) {
439 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
440 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
441 $cache->delete( $key );
446 * @param WANObjectCache $cache
449 protected function getCacheKey( WANObjectCache
$cache ) {
450 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
452 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
456 * @param WANObjectCache $cache
460 public function getMutableCacheKeys( WANObjectCache
$cache ) {
461 $id = $this->getId();
463 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
467 * Load user data from shared cache, given mId has already been set.
472 protected function loadFromCache() {
473 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
474 $data = $cache->getWithSetCallback(
475 $this->getCacheKey( $cache ),
477 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
478 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
479 wfDebug( "User: cache miss for user {$this->mId}\n" );
481 $this->loadFromDatabase( self
::READ_NORMAL
);
483 $this->loadOptions();
486 foreach ( self
::$mCacheVars as $name ) {
487 $data[$name] = $this->$name;
490 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
492 // if a user group membership is about to expire, the cache needs to
493 // expire at that time (T163691)
494 foreach ( $this->mGroupMemberships
as $ugm ) {
495 if ( $ugm->getExpiry() ) {
496 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
497 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
498 $ttl = $secondsUntilExpiry;
505 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
508 // Restore from cache
509 foreach ( self
::$mCacheVars as $name ) {
510 $this->$name = $data[$name];
516 /** @name newFrom*() static factory methods */
520 * Static factory method for creation from username.
522 * This is slightly less efficient than newFromId(), so use newFromId() if
523 * you have both an ID and a name handy.
525 * @param string $name Username, validated by Title::newFromText()
526 * @param string|bool $validate Validate username. Takes the same parameters as
527 * User::getCanonicalName(), except that true is accepted as an alias
528 * for 'valid', for BC.
530 * @return User|bool User object, or false if the username is invalid
531 * (e.g. if it contains illegal characters or is an IP address). If the
532 * username is not present in the database, the result will be a user object
533 * with a name, zero user ID and default settings.
535 public static function newFromName( $name, $validate = 'valid' ) {
536 if ( $validate === true ) {
539 $name = self
::getCanonicalName( $name, $validate );
540 if ( $name === false ) {
544 // Create unloaded user object
548 $u->setItemLoaded( 'name' );
554 * Static factory method for creation from a given user ID.
556 * @param int $id Valid user ID
557 * @return User The corresponding User object
559 public static function newFromId( $id ) {
563 $u->setItemLoaded( 'id' );
568 * Static factory method for creation from a given actor ID.
571 * @param int $id Valid actor ID
572 * @return User The corresponding User object
574 public static function newFromActorId( $id ) {
575 global $wgActorTableSchemaMigrationStage;
577 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
578 // but it does little harm and might be needed for write callers loading a User.
579 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
580 throw new BadMethodCallException(
581 'Cannot use ' . __METHOD__
582 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
589 $u->setItemLoaded( 'actor' );
594 * Returns a User object corresponding to the given UserIdentity.
598 * @param UserIdentity $identity
602 public static function newFromIdentity( UserIdentity
$identity ) {
603 if ( $identity instanceof User
) {
607 return self
::newFromAnyId(
608 $identity->getId() === 0 ?
null : $identity->getId(),
609 $identity->getName() === '' ?
null : $identity->getName(),
610 $identity->getActorId() === 0 ?
null : $identity->getActorId()
615 * Static factory method for creation from an ID, name, and/or actor ID
617 * This does not check that the ID, name, and actor ID all correspond to
621 * @param int|null $userId User ID, if known
622 * @param string|null $userName User name, if known
623 * @param int|null $actorId Actor ID, if known
624 * @param bool|string $dbDomain remote wiki to which the User/Actor ID applies, or false if none
627 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
628 global $wgActorTableSchemaMigrationStage;
630 // Stop-gap solution for the problem described in T222212.
631 // Force the User ID and Actor ID to zero for users loaded from the database
632 // of another wiki, to prevent subtle data corruption and confusing failure modes.
633 if ( $dbDomain !== false ) {
639 $user->mFrom
= 'defaults';
641 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
642 // but it does little harm and might be needed for write callers loading a User.
643 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
644 $user->mActorId
= (int)$actorId;
645 if ( $user->mActorId
!== 0 ) {
646 $user->mFrom
= 'actor';
648 $user->setItemLoaded( 'actor' );
651 if ( $userName !== null && $userName !== '' ) {
652 $user->mName
= $userName;
653 $user->mFrom
= 'name';
654 $user->setItemLoaded( 'name' );
657 if ( $userId !== null ) {
658 $user->mId
= (int)$userId;
659 if ( $user->mId
!== 0 ) {
662 $user->setItemLoaded( 'id' );
665 if ( $user->mFrom
=== 'defaults' ) {
666 throw new InvalidArgumentException(
667 'Cannot create a user with no name, no ID, and no actor ID'
675 * Factory method to fetch whichever user has a given email confirmation code.
676 * This code is generated when an account is created or its e-mail address
679 * If the code is invalid or has expired, returns NULL.
681 * @param string $code Confirmation code
682 * @param int $flags User::READ_* bitfield
685 public static function newFromConfirmationCode( $code, $flags = 0 ) {
686 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
687 ?
wfGetDB( DB_MASTER
)
688 : wfGetDB( DB_REPLICA
);
690 $id = $db->selectField(
694 'user_email_token' => md5( $code ),
695 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
699 return $id ? self
::newFromId( $id ) : null;
703 * Create a new user object using data from session. If the login
704 * credentials are invalid, the result is an anonymous user.
706 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
709 public static function newFromSession( WebRequest
$request = null ) {
711 $user->mFrom
= 'session';
712 $user->mRequest
= $request;
717 * Create a new user object from a user row.
718 * The row should have the following fields from the user table in it:
719 * - either user_name or user_id to load further data if needed (or both)
721 * - all other fields (email, etc.)
722 * It is useless to provide the remaining fields if either user_id,
723 * user_name and user_real_name are not provided because the whole row
724 * will be loaded once more from the database when accessing them.
726 * @param stdClass $row A row from the user table
727 * @param array|null $data Further data to load into the object
728 * (see User::loadFromRow for valid keys)
731 public static function newFromRow( $row, $data = null ) {
733 $user->loadFromRow( $row, $data );
738 * Static factory method for creation of a "system" user from username.
740 * A "system" user is an account that's used to attribute logged actions
741 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
742 * might include the 'Maintenance script' or 'Conversion script' accounts
743 * used by various scripts in the maintenance/ directory or accounts such
744 * as 'MediaWiki message delivery' used by the MassMessage extension.
746 * This can optionally create the user if it doesn't exist, and "steal" the
747 * account if it does exist.
749 * "Stealing" an existing user is intended to make it impossible for normal
750 * authentication processes to use the account, effectively disabling the
751 * account for normal use:
752 * - Email is invalidated, to prevent account recovery by emailing a
753 * temporary password and to disassociate the account from the existing
755 * - The token is set to a magic invalid value, to kill existing sessions
756 * and to prevent $this->setToken() calls from resetting the token to a
758 * - SessionManager is instructed to prevent new sessions for the user, to
759 * do things like deauthorizing OAuth consumers.
760 * - AuthManager is instructed to revoke access, to invalidate or remove
761 * passwords and other credentials.
763 * @param string $name Username
764 * @param array $options Options are:
765 * - validate: As for User::getCanonicalName(), default 'valid'
766 * - create: Whether to create the user if it doesn't already exist, default true
767 * - steal: Whether to "disable" the account for normal use if it already
768 * exists, default false
772 public static function newSystemUser( $name, $options = [] ) {
774 'validate' => 'valid',
779 $name = self
::getCanonicalName( $name, $options['validate'] );
780 if ( $name === false ) {
784 $dbr = wfGetDB( DB_REPLICA
);
785 $userQuery = self
::getQueryInfo();
786 $row = $dbr->selectRow(
787 $userQuery['tables'],
788 $userQuery['fields'],
789 [ 'user_name' => $name ],
795 // Try the master database...
796 $dbw = wfGetDB( DB_MASTER
);
797 $row = $dbw->selectRow(
798 $userQuery['tables'],
799 $userQuery['fields'],
800 [ 'user_name' => $name ],
808 // No user. Create it?
809 return $options['create']
810 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
814 $user = self
::newFromRow( $row );
816 // A user is considered to exist as a non-system user if it can
817 // authenticate, or has an email set, or has a non-invalid token.
818 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
819 AuthManager
::singleton()->userCanAuthenticate( $name )
821 // User exists. Steal it?
822 if ( !$options['steal'] ) {
826 AuthManager
::singleton()->revokeAccessForUser( $name );
828 $user->invalidateEmail();
829 $user->mToken
= self
::INVALID_TOKEN
;
830 $user->saveSettings();
831 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
840 * Get the username corresponding to a given user ID
841 * @param int $id User ID
842 * @return string|bool The corresponding username
844 public static function whoIs( $id ) {
845 return UserCache
::singleton()->getProp( $id, 'name' );
849 * Get the real name of a user given their user ID
851 * @param int $id User ID
852 * @return string|bool The corresponding user's real name
854 public static function whoIsReal( $id ) {
855 return UserCache
::singleton()->getProp( $id, 'real_name' );
859 * Get database id given a user name
860 * @param string $name Username
861 * @param int $flags User::READ_* constant bitfield
862 * @return int|null The corresponding user's ID, or null if user is nonexistent
864 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
865 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
866 $name = (string)$name;
867 $nt = Title
::makeTitleSafe( NS_USER
, $name );
868 if ( is_null( $nt ) ) {
873 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
874 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
877 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
878 $db = wfGetDB( $index );
883 [ 'user_name' => $nt->getText() ],
888 if ( $s === false ) {
891 $result = (int)$s->user_id
;
894 if ( count( self
::$idCacheByName ) >= 1000 ) {
895 self
::$idCacheByName = [];
898 self
::$idCacheByName[$name] = $result;
904 * Reset the cache used in idFromName(). For use in tests.
906 public static function resetIdByNameCache() {
907 self
::$idCacheByName = [];
911 * Does the string match an anonymous IP address?
913 * This function exists for username validation, in order to reject
914 * usernames which are similar in form to IP addresses. Strings such
915 * as 300.300.300.300 will return true because it looks like an IP
916 * address, despite not being strictly valid.
918 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
919 * address because the usemod software would "cloak" anonymous IP
920 * addresses like this, if we allowed accounts like this to be created
921 * new users could get the old edits of these anonymous users.
923 * @param string $name Name to match
926 public static function isIP( $name ) {
927 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
928 || IP
::isIPv6( $name );
932 * Is the user an IP range?
937 public function isIPRange() {
938 return IP
::isValidRange( $this->mName
);
942 * Is the input a valid username?
944 * Checks if the input is a valid username, we don't want an empty string,
945 * an IP address, anything that contains slashes (would mess up subpages),
946 * is longer than the maximum allowed username size or doesn't begin with
949 * @param string $name Name to match
952 public static function isValidUserName( $name ) {
953 global $wgMaxNameChars;
956 || self
::isIP( $name )
957 ||
strpos( $name, '/' ) !== false
958 ||
strlen( $name ) > $wgMaxNameChars
959 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
964 // Ensure that the name can't be misresolved as a different title,
965 // such as with extra namespace keys at the start.
966 $parsed = Title
::newFromText( $name );
967 if ( is_null( $parsed )
968 ||
$parsed->getNamespace()
969 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
973 // Check an additional blacklist of troublemaker characters.
974 // Should these be merged into the title char list?
975 $unicodeBlacklist = '/[' .
976 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
977 '\x{00a0}' . # non-breaking space
978 '\x{2000}-\x{200f}' . # various whitespace
979 '\x{2028}-\x{202f}' . # breaks and control chars
980 '\x{3000}' . # ideographic space
981 '\x{e000}-\x{f8ff}' . # private use
983 if ( preg_match( $unicodeBlacklist, $name ) ) {
991 * Usernames which fail to pass this function will be blocked
992 * from user login and new account registrations, but may be used
993 * internally by batch processes.
995 * If an account already exists in this form, login will be blocked
996 * by a failure to pass this function.
998 * @param string $name Name to match
1001 public static function isUsableName( $name ) {
1002 global $wgReservedUsernames;
1003 // Must be a valid username, obviously ;)
1004 if ( !self
::isValidUserName( $name ) ) {
1008 static $reservedUsernames = false;
1009 if ( !$reservedUsernames ) {
1010 $reservedUsernames = $wgReservedUsernames;
1011 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1014 // Certain names may be reserved for batch processes.
1015 foreach ( $reservedUsernames as $reserved ) {
1016 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1017 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1019 if ( $reserved == $name ) {
1027 * Return the users who are members of the given group(s). In case of multiple groups,
1028 * users who are members of at least one of them are returned.
1030 * @param string|array $groups A single group name or an array of group names
1031 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1032 * records; larger values are ignored.
1033 * @param int|null $after ID the user to start after
1034 * @return UserArrayFromResult
1036 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1037 if ( $groups === [] ) {
1038 return UserArrayFromResult
::newFromIDs( [] );
1041 $groups = array_unique( (array)$groups );
1042 $limit = min( 5000, $limit );
1044 $conds = [ 'ug_group' => $groups ];
1045 if ( $after !== null ) {
1046 $conds[] = 'ug_user > ' . (int)$after;
1049 $dbr = wfGetDB( DB_REPLICA
);
1050 $ids = $dbr->selectFieldValues(
1057 'ORDER BY' => 'ug_user',
1061 return UserArray
::newFromIDs( $ids );
1065 * Usernames which fail to pass this function will be blocked
1066 * from new account registrations, but may be used internally
1067 * either by batch processes or by user accounts which have
1068 * already been created.
1070 * Additional blacklisting may be added here rather than in
1071 * isValidUserName() to avoid disrupting existing accounts.
1073 * @param string $name String to match
1076 public static function isCreatableName( $name ) {
1077 global $wgInvalidUsernameCharacters;
1079 // Ensure that the username isn't longer than 235 bytes, so that
1080 // (at least for the builtin skins) user javascript and css files
1081 // will work. (T25080)
1082 if ( strlen( $name ) > 235 ) {
1083 wfDebugLog( 'username', __METHOD__
.
1084 ": '$name' invalid due to length" );
1088 // Preg yells if you try to give it an empty string
1089 if ( $wgInvalidUsernameCharacters !== '' &&
1090 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1092 wfDebugLog( 'username', __METHOD__
.
1093 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1097 return self
::isUsableName( $name );
1101 * Is the input a valid password for this user?
1103 * @param string $password Desired password
1106 public function isValidPassword( $password ) {
1107 // simple boolean wrapper for checkPasswordValidity
1108 return $this->checkPasswordValidity( $password )->isGood();
1112 * Check if this is a valid password for this user
1114 * Returns a Status object with a set of messages describing
1115 * problems with the password. If the return status is fatal,
1116 * the action should be refused and the password should not be
1117 * checked at all (this is mainly meant for DoS mitigation).
1118 * If the return value is OK but not good, the password can be checked,
1119 * but the user should not be able to set their password to this.
1120 * The value of the returned Status object will be an array which
1121 * can have the following fields:
1122 * - forceChange (bool): if set to true, the user should not be
1123 * allowed to log with this password unless they change it during
1124 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1125 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1126 * a password change on login.
1128 * @param string $password Desired password
1132 public function checkPasswordValidity( $password ) {
1133 global $wgPasswordPolicy;
1135 $upp = new UserPasswordPolicy(
1136 $wgPasswordPolicy['policies'],
1137 $wgPasswordPolicy['checks']
1140 $status = Status
::newGood( [] );
1141 $result = false; // init $result to false for the internal checks
1143 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1144 $status->error( $result );
1148 if ( $result === false ) {
1149 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1153 if ( $result === true ) {
1157 $status->error( $result );
1158 return $status; // the isValidPassword hook set a string $result and returned true
1162 * Given unvalidated user input, return a canonical username, or false if
1163 * the username is invalid.
1164 * @param string $name User input
1165 * @param string|bool $validate Type of validation to use:
1166 * - false No validation
1167 * - 'valid' Valid for batch processes
1168 * - 'usable' Valid for batch processes and login
1169 * - 'creatable' Valid for batch processes, login and account creation
1171 * @throws InvalidArgumentException
1172 * @return bool|string
1174 public static function getCanonicalName( $name, $validate = 'valid' ) {
1175 // Force usernames to capital
1176 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1178 # Reject names containing '#'; these will be cleaned up
1179 # with title normalisation, but then it's too late to
1181 if ( strpos( $name, '#' ) !== false ) {
1185 // Clean up name according to title rules,
1186 // but only when validation is requested (T14654)
1187 $t = ( $validate !== false ) ?
1188 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1189 // Check for invalid titles
1190 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1194 $name = $t->getText();
1196 switch ( $validate ) {
1200 if ( !self
::isValidUserName( $name ) ) {
1205 if ( !self
::isUsableName( $name ) ) {
1210 if ( !self
::isCreatableName( $name ) ) {
1215 throw new InvalidArgumentException(
1216 'Invalid parameter value for $validate in ' . __METHOD__
);
1222 * Set cached properties to default.
1224 * @note This no longer clears uncached lazy-initialised properties;
1225 * the constructor does that instead.
1227 * @param string|bool $name
1229 public function loadDefaults( $name = false ) {
1231 $this->mName
= $name;
1232 $this->mActorId
= null;
1233 $this->mRealName
= '';
1235 $this->mOptionOverrides
= null;
1236 $this->mOptionsLoaded
= false;
1238 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1239 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1240 if ( $loggedOut !== 0 ) {
1241 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1243 $this->mTouched
= '1'; # Allow any pages to be cached
1246 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1247 $this->mEmailAuthenticated
= null;
1248 $this->mEmailToken
= '';
1249 $this->mEmailTokenExpires
= null;
1250 $this->mRegistration
= wfTimestamp( TS_MW
);
1251 $this->mGroupMemberships
= [];
1253 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1257 * Return whether an item has been loaded.
1259 * @param string $item Item to check. Current possibilities:
1263 * @param string $all 'all' to check if the whole object has been loaded
1264 * or any other string to check if only the item is available (e.g.
1268 public function isItemLoaded( $item, $all = 'all' ) {
1269 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1270 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1274 * Set that an item has been loaded
1276 * @param string $item
1278 protected function setItemLoaded( $item ) {
1279 if ( is_array( $this->mLoadedItems
) ) {
1280 $this->mLoadedItems
[$item] = true;
1285 * Load user data from the session.
1287 * @return bool True if the user is logged in, false otherwise.
1289 private function loadFromSession() {
1290 // MediaWiki\Session\Session already did the necessary authentication of the user
1291 // returned here, so just use it if applicable.
1292 $session = $this->getRequest()->getSession();
1293 $user = $session->getUser();
1294 if ( $user->isLoggedIn() ) {
1295 $this->loadFromUserObject( $user );
1297 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1298 // every session load, because an autoblocked editor might not edit again from the same
1299 // IP address after being blocked.
1300 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1302 // Other code expects these to be set in the session, so set them.
1303 $session->set( 'wsUserID', $this->getId() );
1304 $session->set( 'wsUserName', $this->getName() );
1305 $session->set( 'wsToken', $this->getToken() );
1314 * Set the 'BlockID' cookie depending on block type and user authentication status.
1316 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1318 public function trackBlockWithCookie() {
1319 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1323 * Load user and user_group data from the database.
1324 * $this->mId must be set, this is how the user is identified.
1326 * @param int $flags User::READ_* constant bitfield
1327 * @return bool True if the user exists, false if the user is anonymous
1329 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1331 $this->mId
= intval( $this->mId
);
1333 if ( !$this->mId
) {
1334 // Anonymous users are not in the database
1335 $this->loadDefaults();
1339 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1340 $db = wfGetDB( $index );
1342 $userQuery = self
::getQueryInfo();
1343 $s = $db->selectRow(
1344 $userQuery['tables'],
1345 $userQuery['fields'],
1346 [ 'user_id' => $this->mId
],
1352 $this->queryFlagsUsed
= $flags;
1353 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1355 if ( $s !== false ) {
1356 // Initialise user table data
1357 $this->loadFromRow( $s );
1358 $this->mGroupMemberships
= null; // deferred
1359 $this->getEditCount(); // revalidation for nulls
1365 $this->loadDefaults();
1371 * Initialize this object from a row from the user table.
1373 * @param stdClass $row Row from the user table to load.
1374 * @param array|null $data Further user data to load into the object
1376 * user_groups Array of arrays or stdClass result rows out of the user_groups
1377 * table. Previously you were supposed to pass an array of strings
1378 * here, but we also need expiry info nowadays, so an array of
1379 * strings is ignored.
1380 * user_properties Array with properties out of the user_properties table
1382 protected function loadFromRow( $row, $data = null ) {
1383 global $wgActorTableSchemaMigrationStage;
1385 if ( !is_object( $row ) ) {
1386 throw new InvalidArgumentException( '$row must be an object' );
1391 $this->mGroupMemberships
= null; // deferred
1393 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1394 // but it does little harm and might be needed for write callers loading a User.
1395 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1396 if ( isset( $row->actor_id
) ) {
1397 $this->mActorId
= (int)$row->actor_id
;
1398 if ( $this->mActorId
!== 0 ) {
1399 $this->mFrom
= 'actor';
1401 $this->setItemLoaded( 'actor' );
1407 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1408 $this->mName
= $row->user_name
;
1409 $this->mFrom
= 'name';
1410 $this->setItemLoaded( 'name' );
1415 if ( isset( $row->user_real_name
) ) {
1416 $this->mRealName
= $row->user_real_name
;
1417 $this->setItemLoaded( 'realname' );
1422 if ( isset( $row->user_id
) ) {
1423 $this->mId
= intval( $row->user_id
);
1424 if ( $this->mId
!== 0 ) {
1425 $this->mFrom
= 'id';
1427 $this->setItemLoaded( 'id' );
1432 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1433 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1436 if ( isset( $row->user_editcount
) ) {
1437 $this->mEditCount
= $row->user_editcount
;
1442 if ( isset( $row->user_touched
) ) {
1443 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1448 if ( isset( $row->user_token
) ) {
1449 // The definition for the column is binary(32), so trim the NULs
1450 // that appends. The previous definition was char(32), so trim
1452 $this->mToken
= rtrim( $row->user_token
, " \0" );
1453 if ( $this->mToken
=== '' ) {
1454 $this->mToken
= null;
1460 if ( isset( $row->user_email
) ) {
1461 $this->mEmail
= $row->user_email
;
1462 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1463 $this->mEmailToken
= $row->user_email_token
;
1464 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1465 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1471 $this->mLoadedItems
= true;
1474 if ( is_array( $data ) ) {
1475 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1476 if ( $data['user_groups'] === [] ) {
1477 $this->mGroupMemberships
= [];
1479 $firstGroup = reset( $data['user_groups'] );
1480 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1481 $this->mGroupMemberships
= [];
1482 foreach ( $data['user_groups'] as $row ) {
1483 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1484 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1489 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1490 $this->loadOptions( $data['user_properties'] );
1496 * Load the data for this user object from another user object.
1500 protected function loadFromUserObject( $user ) {
1502 foreach ( self
::$mCacheVars as $var ) {
1503 $this->$var = $user->$var;
1508 * Load the groups from the database if they aren't already loaded.
1510 private function loadGroups() {
1511 if ( is_null( $this->mGroupMemberships
) ) {
1512 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1513 ?
wfGetDB( DB_MASTER
)
1514 : wfGetDB( DB_REPLICA
);
1515 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1521 * Add the user to the group if he/she meets given criteria.
1523 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1524 * possible to remove manually via Special:UserRights. In such case it
1525 * will not be re-added automatically. The user will also not lose the
1526 * group if they no longer meet the criteria.
1528 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1530 * @return array Array of groups the user has been promoted to.
1532 * @see $wgAutopromoteOnce
1534 public function addAutopromoteOnceGroups( $event ) {
1535 global $wgAutopromoteOnceLogInRC;
1537 if ( wfReadOnly() ||
!$this->getId() ) {
1541 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1542 if ( $toPromote === [] ) {
1546 if ( !$this->checkAndSetTouched() ) {
1547 return []; // raced out (bug T48834)
1550 $oldGroups = $this->getGroups(); // previous groups
1551 $oldUGMs = $this->getGroupMemberships();
1552 foreach ( $toPromote as $group ) {
1553 $this->addGroup( $group );
1555 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1556 $newUGMs = $this->getGroupMemberships();
1558 // update groups in external authentication database
1559 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1561 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1562 $logEntry->setPerformer( $this );
1563 $logEntry->setTarget( $this->getUserPage() );
1564 $logEntry->setParameters( [
1565 '4::oldgroups' => $oldGroups,
1566 '5::newgroups' => $newGroups,
1568 $logid = $logEntry->insert();
1569 if ( $wgAutopromoteOnceLogInRC ) {
1570 $logEntry->publish( $logid );
1577 * Builds update conditions. Additional conditions may be added to $conditions to
1578 * protected against race conditions using a compare-and-set (CAS) mechanism
1579 * based on comparing $this->mTouched with the user_touched field.
1581 * @param IDatabase $db
1582 * @param array $conditions WHERE conditions for use with Database::update
1583 * @return array WHERE conditions for use with Database::update
1585 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1586 if ( $this->mTouched
) {
1587 // CAS check: only update if the row wasn't changed sicne it was loaded.
1588 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1595 * Bump user_touched if it didn't change since this object was loaded
1597 * On success, the mTouched field is updated.
1598 * The user serialization cache is always cleared.
1600 * @return bool Whether user_touched was actually updated
1603 protected function checkAndSetTouched() {
1606 if ( !$this->mId
) {
1607 return false; // anon
1610 // Get a new user_touched that is higher than the old one
1611 $newTouched = $this->newTouchedTimestamp();
1613 $dbw = wfGetDB( DB_MASTER
);
1614 $dbw->update( 'user',
1615 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1616 $this->makeUpdateConditions( $dbw, [
1617 'user_id' => $this->mId
,
1621 $success = ( $dbw->affectedRows() > 0 );
1624 $this->mTouched
= $newTouched;
1625 $this->clearSharedCache( 'changed' );
1627 // Clears on failure too since that is desired if the cache is stale
1628 $this->clearSharedCache( 'refresh' );
1635 * Clear various cached data stored in this object. The cache of the user table
1636 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1638 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1639 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1641 public function clearInstanceCache( $reloadFrom = false ) {
1642 global $wgFullyInitialised;
1644 $this->mNewtalk
= -1;
1645 $this->mDatePreference
= null;
1646 $this->mBlockedby
= -1; # Unset
1647 $this->mHash
= false;
1648 $this->mEffectiveGroups
= null;
1649 $this->mImplicitGroups
= null;
1650 $this->mGroupMemberships
= null;
1651 $this->mOptions
= null;
1652 $this->mOptionsLoaded
= false;
1653 $this->mEditCount
= null;
1655 // Replacement of former `$this->mRights = null` line
1656 if ( $wgFullyInitialised && $this->mFrom
) {
1657 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1662 if ( $reloadFrom ) {
1663 $this->mLoadedItems
= [];
1664 $this->mFrom
= $reloadFrom;
1668 /** @var array|null */
1669 private static $defOpt = null;
1670 /** @var string|null */
1671 private static $defOptLang = null;
1674 * Reset the process cache of default user options. This is only necessary
1675 * if the wiki configuration has changed since defaults were calculated,
1676 * and as such should only be performed inside the testing suite that
1677 * regularly changes wiki configuration.
1679 public static function resetGetDefaultOptionsForTestsOnly() {
1680 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1681 self
::$defOpt = null;
1682 self
::$defOptLang = null;
1686 * Combine the language default options with any site-specific options
1687 * and add the default language variants.
1689 * @return array Array of String options
1691 public static function getDefaultOptions() {
1692 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1694 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1695 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1696 // The content language does not change (and should not change) mid-request, but the
1697 // unit tests change it anyway, and expect this method to return values relevant to the
1698 // current content language.
1699 return self
::$defOpt;
1702 self
::$defOpt = $wgDefaultUserOptions;
1703 // Default language setting
1704 self
::$defOptLang = $contLang->getCode();
1705 self
::$defOpt['language'] = self
::$defOptLang;
1706 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1707 if ( $langCode === $contLang->getCode() ) {
1708 self
::$defOpt['variant'] = $langCode;
1710 self
::$defOpt["variant-$langCode"] = $langCode;
1714 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1715 // since extensions may change the set of searchable namespaces depending
1716 // on user groups/permissions.
1717 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1718 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1720 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1722 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1724 return self
::$defOpt;
1728 * Get a given default option value.
1730 * @param string $opt Name of option to retrieve
1731 * @return string Default option value
1733 public static function getDefaultOption( $opt ) {
1734 $defOpts = self
::getDefaultOptions();
1735 return $defOpts[$opt] ??
null;
1739 * Get blocking information
1741 * TODO: Move this into the BlockManager, along with block-related properties.
1743 * @param bool $fromReplica Whether to check the replica DB first.
1744 * To improve performance, non-critical checks are done against replica DBs.
1745 * Check when actually saving should be done against master.
1747 private function getBlockedStatus( $fromReplica = true ) {
1748 if ( $this->mBlockedby
!= -1 ) {
1752 wfDebug( __METHOD__
. ": checking...\n" );
1754 // Initialize data...
1755 // Otherwise something ends up stomping on $this->mBlockedby when
1756 // things get lazy-loaded later, causing false positive block hits
1757 // due to -1 !== 0. Probably session-related... Nothing should be
1758 // overwriting mBlockedby, surely?
1761 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1767 $this->mBlock
= $block;
1768 $this->mBlockedby
= $block->getByName();
1769 $this->mBlockreason
= $block->getReason();
1770 $this->mHideName
= $block->getHideName();
1771 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1773 $this->mBlock
= null;
1774 $this->mBlockedby
= '';
1775 $this->mBlockreason
= '';
1776 $this->mHideName
= 0;
1777 $this->mAllowUsertalk
= false;
1780 // Avoid PHP 7.1 warning of passing $this by reference
1783 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1787 * Whether the given IP is in a DNS blacklist.
1789 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1790 * @param string $ip IP to check
1791 * @param bool $checkWhitelist Whether to check the whitelist first
1792 * @return bool True if blacklisted.
1794 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1795 return MediaWikiServices
::getInstance()->getBlockManager()
1796 ->isDnsBlacklisted( $ip, $checkWhitelist );
1800 * Whether the given IP is in a given DNS blacklist.
1802 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1803 * @param string $ip IP to check
1804 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1805 * @return bool True if blacklisted.
1807 public function inDnsBlacklist( $ip, $bases ) {
1808 wfDeprecated( __METHOD__
, '1.34' );
1811 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1812 if ( IP
::isIPv4( $ip ) ) {
1813 // Reverse IP, T23255
1814 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1816 foreach ( (array)$bases as $base ) {
1818 // If we have an access key, use that too (ProjectHoneypot, etc.)
1820 if ( is_array( $base ) ) {
1821 if ( count( $base ) >= 2 ) {
1822 // Access key is 1, base URL is 0
1823 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1825 $host = "$ipReversed.{$base[0]}";
1827 $basename = $base[0];
1829 $host = "$ipReversed.$base";
1833 $ipList = gethostbynamel( $host );
1836 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1841 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1849 * Check if an IP address is in the local proxy list
1851 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1855 public static function isLocallyBlockedProxy( $ip ) {
1856 wfDeprecated( __METHOD__
, '1.34' );
1858 global $wgProxyList;
1860 if ( !$wgProxyList ) {
1864 if ( !is_array( $wgProxyList ) ) {
1865 // Load values from the specified file
1866 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1869 $resultProxyList = [];
1870 $deprecatedIPEntries = [];
1872 // backward compatibility: move all ip addresses in keys to values
1873 foreach ( $wgProxyList as $key => $value ) {
1874 $keyIsIP = IP
::isIPAddress( $key );
1875 $valueIsIP = IP
::isIPAddress( $value );
1876 if ( $keyIsIP && !$valueIsIP ) {
1877 $deprecatedIPEntries[] = $key;
1878 $resultProxyList[] = $key;
1879 } elseif ( $keyIsIP && $valueIsIP ) {
1880 $deprecatedIPEntries[] = $key;
1881 $resultProxyList[] = $key;
1882 $resultProxyList[] = $value;
1884 $resultProxyList[] = $value;
1888 if ( $deprecatedIPEntries ) {
1890 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1891 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1894 $proxyListIPSet = new IPSet( $resultProxyList );
1895 return $proxyListIPSet->match( $ip );
1899 * Is this user subject to rate limiting?
1901 * @return bool True if rate limited
1903 public function isPingLimitable() {
1904 global $wgRateLimitsExcludedIPs;
1905 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1906 // No other good way currently to disable rate limits
1907 // for specific IPs. :P
1908 // But this is a crappy hack and should die.
1911 return !$this->isAllowed( 'noratelimit' );
1915 * Primitive rate limits: enforce maximum actions per time period
1916 * to put a brake on flooding.
1918 * The method generates both a generic profiling point and a per action one
1919 * (suffix being "-$action".
1921 * @note When using a shared cache like memcached, IP-address
1922 * last-hit counters will be shared across wikis.
1924 * @param string $action Action to enforce; 'edit' if unspecified
1925 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1926 * @return bool True if a rate limiter was tripped
1928 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1929 // Avoid PHP 7.1 warning of passing $this by reference
1931 // Call the 'PingLimiter' hook
1933 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1937 global $wgRateLimits;
1938 if ( !isset( $wgRateLimits[$action] ) ) {
1942 $limits = array_merge(
1943 [ '&can-bypass' => true ],
1944 $wgRateLimits[$action]
1947 // Some groups shouldn't trigger the ping limiter, ever
1948 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1953 $id = $this->getId();
1955 $isNewbie = $this->isNewbie();
1956 $cache = ObjectCache
::getLocalClusterInstance();
1960 if ( isset( $limits['anon'] ) ) {
1961 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1963 } elseif ( isset( $limits['user'] ) ) {
1964 // limits for logged-in users
1965 $userLimit = $limits['user'];
1968 // limits for anons and for newbie logged-in users
1971 if ( isset( $limits['ip'] ) ) {
1972 $ip = $this->getRequest()->getIP();
1973 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1975 // subnet-based limits
1976 if ( isset( $limits['subnet'] ) ) {
1977 $ip = $this->getRequest()->getIP();
1978 $subnet = IP
::getSubnet( $ip );
1979 if ( $subnet !== false ) {
1980 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1985 // Check for group-specific permissions
1986 // If more than one group applies, use the group with the highest limit ratio (max/period)
1987 foreach ( $this->getGroups() as $group ) {
1988 if ( isset( $limits[$group] ) ) {
1989 if ( $userLimit === false
1990 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1992 $userLimit = $limits[$group];
1997 // limits for newbie logged-in users (override all the normal user limits)
1998 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1999 $userLimit = $limits['newbie'];
2002 // Set the user limit key
2003 if ( $userLimit !== false ) {
2004 // phan is confused because &can-bypass's value is a bool, so it assumes
2005 // that $userLimit is also a bool here.
2006 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2007 list( $max, $period ) = $userLimit;
2008 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2009 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2012 // ip-based limits for all ping-limitable users
2013 if ( isset( $limits['ip-all'] ) ) {
2014 $ip = $this->getRequest()->getIP();
2015 // ignore if user limit is more permissive
2016 if ( $isNewbie ||
$userLimit === false
2017 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2018 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2022 // subnet-based limits for all ping-limitable users
2023 if ( isset( $limits['subnet-all'] ) ) {
2024 $ip = $this->getRequest()->getIP();
2025 $subnet = IP
::getSubnet( $ip );
2026 if ( $subnet !== false ) {
2027 // ignore if user limit is more permissive
2028 if ( $isNewbie ||
$userLimit === false
2029 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2030 > $userLimit[0] / $userLimit[1] ) {
2031 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2037 foreach ( $keys as $key => $limit ) {
2038 // phan is confused because &can-bypass's value is a bool, so it assumes
2039 // that $userLimit is also a bool here.
2040 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2041 list( $max, $period ) = $limit;
2042 $summary = "(limit $max in {$period}s)";
2043 $count = $cache->get( $key );
2046 if ( $count >= $max ) {
2047 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2048 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2051 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2054 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2055 if ( $incrBy > 0 ) {
2056 $cache->add( $key, 0, intval( $period ) ); // first ping
2059 if ( $incrBy > 0 ) {
2060 $cache->incr( $key, $incrBy );
2068 * Check if user is blocked
2070 * @deprecated since 1.34, use User::getBlock() or
2071 * PermissionManager::isBlockedFrom() or
2072 * PermissionManager::userCan() instead.
2074 * @param bool $fromReplica Whether to check the replica DB instead of
2075 * the master. Hacked from false due to horrible probs on site.
2076 * @return bool True if blocked, false otherwise
2078 public function isBlocked( $fromReplica = true ) {
2079 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2080 $this->getBlock()->appliesToRight( 'edit' );
2084 * Get the block affecting the user, or null if the user is not blocked
2086 * @param bool $fromReplica Whether to check the replica DB instead of the master
2087 * @return AbstractBlock|null
2089 public function getBlock( $fromReplica = true ) {
2090 $this->getBlockedStatus( $fromReplica );
2091 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2095 * Check if user is blocked from editing a particular article
2097 * @param Title $title Title to check
2098 * @param bool $fromReplica Whether to check the replica DB instead of the master
2101 * @deprecated since 1.33,
2102 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2105 public function isBlockedFrom( $title, $fromReplica = false ) {
2106 return MediaWikiServices
::getInstance()->getPermissionManager()
2107 ->isBlockedFrom( $this, $title, $fromReplica );
2111 * If user is blocked, return the name of the user who placed the block
2112 * @return string Name of blocker
2114 public function blockedBy() {
2115 $this->getBlockedStatus();
2116 return $this->mBlockedby
;
2120 * If user is blocked, return the specified reason for the block
2121 * @return string Blocking reason
2123 public function blockedFor() {
2124 $this->getBlockedStatus();
2125 return $this->mBlockreason
;
2129 * If user is blocked, return the ID for the block
2130 * @return int Block ID
2132 public function getBlockId() {
2133 $this->getBlockedStatus();
2134 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2138 * Check if user is blocked on all wikis.
2139 * Do not use for actual edit permission checks!
2140 * This is intended for quick UI checks.
2142 * @param string $ip IP address, uses current client if none given
2143 * @return bool True if blocked, false otherwise
2145 public function isBlockedGlobally( $ip = '' ) {
2146 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2150 * Check if user is blocked on all wikis.
2151 * Do not use for actual edit permission checks!
2152 * This is intended for quick UI checks.
2154 * @param string $ip IP address, uses current client if none given
2155 * @return AbstractBlock|null Block object if blocked, null otherwise
2156 * @throws FatalError
2157 * @throws MWException
2159 public function getGlobalBlock( $ip = '' ) {
2160 if ( $this->mGlobalBlock
!== null ) {
2161 return $this->mGlobalBlock ?
: null;
2163 // User is already an IP?
2164 if ( IP
::isIPAddress( $this->getName() ) ) {
2165 $ip = $this->getName();
2167 $ip = $this->getRequest()->getIP();
2169 // Avoid PHP 7.1 warning of passing $this by reference
2173 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2175 if ( $blocked && $block === null ) {
2176 // back-compat: UserIsBlockedGlobally didn't have $block param first
2177 $block = new SystemBlock( [
2179 'systemBlock' => 'global-block'
2183 $this->mGlobalBlock
= $blocked ?
$block : false;
2184 return $this->mGlobalBlock ?
: null;
2188 * Check if user account is locked
2190 * @return bool True if locked, false otherwise
2192 public function isLocked() {
2193 if ( $this->mLocked
!== null ) {
2194 return $this->mLocked
;
2197 $this->mLocked
= false;
2198 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2199 return $this->mLocked
;
2203 * Check if user account is hidden
2205 * @return bool True if hidden, false otherwise
2207 public function isHidden() {
2208 if ( $this->mHideName
!== null ) {
2209 return (bool)$this->mHideName
;
2211 $this->getBlockedStatus();
2212 if ( !$this->mHideName
) {
2214 $this->mHideName
= false;
2215 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2217 return (bool)$this->mHideName
;
2221 * Get the user's ID.
2222 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2224 public function getId() {
2225 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2226 // Special case, we know the user is anonymous
2230 if ( !$this->isItemLoaded( 'id' ) ) {
2231 // Don't load if this was initialized from an ID
2235 return (int)$this->mId
;
2239 * Set the user and reload all fields according to a given ID
2240 * @param int $v User ID to reload
2242 public function setId( $v ) {
2244 $this->clearInstanceCache( 'id' );
2248 * Get the user name, or the IP of an anonymous user
2249 * @return string User's name or IP address
2251 public function getName() {
2252 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2253 // Special case optimisation
2254 return $this->mName
;
2258 if ( $this->mName
=== false ) {
2260 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2263 return $this->mName
;
2267 * Set the user name.
2269 * This does not reload fields from the database according to the given
2270 * name. Rather, it is used to create a temporary "nonexistent user" for
2271 * later addition to the database. It can also be used to set the IP
2272 * address for an anonymous user to something other than the current
2275 * @note User::newFromName() has roughly the same function, when the named user
2277 * @param string $str New user name to set
2279 public function setName( $str ) {
2281 $this->mName
= $str;
2285 * Get the user's actor ID.
2287 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2288 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2290 public function getActorId( IDatabase
$dbw = null ) {
2291 global $wgActorTableSchemaMigrationStage;
2293 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2294 // but it does little harm and might be needed for write callers loading a User.
2295 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2299 if ( !$this->isItemLoaded( 'actor' ) ) {
2303 // Currently $this->mActorId might be null if $this was loaded from a
2304 // cache entry that was written when $wgActorTableSchemaMigrationStage
2305 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2306 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2307 // has been removed), that condition may be removed.
2308 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2310 'actor_user' => $this->getId() ?
: null,
2311 'actor_name' => (string)$this->getName(),
2314 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2315 throw new CannotCreateActorException(
2316 'Cannot create an actor for a usable name that is not an existing user'
2319 if ( $q['actor_name'] === '' ) {
2320 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2322 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2323 if ( $dbw->affectedRows() ) {
2324 $this->mActorId
= (int)$dbw->insertId();
2327 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2328 $this->mActorId
= (int)$dbw->selectField(
2333 [ 'LOCK IN SHARE MODE' ]
2335 if ( !$this->mActorId
) {
2336 throw new CannotCreateActorException(
2337 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2341 $this->invalidateCache();
2343 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2344 $db = wfGetDB( $index );
2345 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2347 $this->setItemLoaded( 'actor' );
2350 return (int)$this->mActorId
;
2354 * Get the user's name escaped by underscores.
2355 * @return string Username escaped by underscores.
2357 public function getTitleKey() {
2358 return str_replace( ' ', '_', $this->getName() );
2362 * Check if the user has new messages.
2363 * @return bool True if the user has new messages
2365 public function getNewtalk() {
2368 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2369 if ( $this->mNewtalk
=== -1 ) {
2370 $this->mNewtalk
= false; # reset talk page status
2372 // Check memcached separately for anons, who have no
2373 // entire User object stored in there.
2374 if ( !$this->mId
) {
2375 global $wgDisableAnonTalk;
2376 if ( $wgDisableAnonTalk ) {
2377 // Anon newtalk disabled by configuration.
2378 $this->mNewtalk
= false;
2380 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2383 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2387 return (bool)$this->mNewtalk
;
2391 * Return the data needed to construct links for new talk page message
2392 * alerts. If there are new messages, this will return an associative array
2393 * with the following data:
2394 * wiki: The database name of the wiki
2395 * link: Root-relative link to the user's talk page
2396 * rev: The last talk page revision that the user has seen or null. This
2397 * is useful for building diff links.
2398 * If there are no new messages, it returns an empty array.
2399 * @note This function was designed to accomodate multiple talk pages, but
2400 * currently only returns a single link and revision.
2403 public function getNewMessageLinks() {
2404 // Avoid PHP 7.1 warning of passing $this by reference
2407 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2411 if ( !$this->getNewtalk() ) {
2414 $utp = $this->getTalkPage();
2415 $dbr = wfGetDB( DB_REPLICA
);
2416 // Get the "last viewed rev" timestamp from the oldest message notification
2417 $timestamp = $dbr->selectField( 'user_newtalk',
2418 'MIN(user_last_timestamp)',
2419 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2421 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2424 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2425 'link' => $utp->getLocalURL(),
2432 * Get the revision ID for the last talk page revision viewed by the talk
2434 * @return int|null Revision ID or null
2436 public function getNewMessageRevisionId() {
2437 $newMessageRevisionId = null;
2438 $newMessageLinks = $this->getNewMessageLinks();
2440 // Note: getNewMessageLinks() never returns more than a single link
2441 // and it is always for the same wiki, but we double-check here in
2442 // case that changes some time in the future.
2443 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2444 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2445 && $newMessageLinks[0]['rev']
2447 /** @var Revision $newMessageRevision */
2448 $newMessageRevision = $newMessageLinks[0]['rev'];
2449 $newMessageRevisionId = $newMessageRevision->getId();
2452 return $newMessageRevisionId;
2456 * Internal uncached check for new messages
2459 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2460 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2461 * @return bool True if the user has new messages
2463 protected function checkNewtalk( $field, $id ) {
2464 $dbr = wfGetDB( DB_REPLICA
);
2466 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2468 return $ok !== false;
2472 * Add or update the new messages flag
2473 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2474 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2475 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2476 * @return bool True if successful, false otherwise
2478 protected function updateNewtalk( $field, $id, $curRev = null ) {
2479 // Get timestamp of the talk page revision prior to the current one
2480 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2481 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2482 // Mark the user as having new messages since this revision
2483 $dbw = wfGetDB( DB_MASTER
);
2484 $dbw->insert( 'user_newtalk',
2485 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2488 if ( $dbw->affectedRows() ) {
2489 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2493 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2498 * Clear the new messages flag for the given user
2499 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2500 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2501 * @return bool True if successful, false otherwise
2503 protected function deleteNewtalk( $field, $id ) {
2504 $dbw = wfGetDB( DB_MASTER
);
2505 $dbw->delete( 'user_newtalk',
2508 if ( $dbw->affectedRows() ) {
2509 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2513 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2518 * Update the 'You have new messages!' status.
2519 * @param bool $val Whether the user has new messages
2520 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2521 * page. Ignored if null or !$val.
2523 public function setNewtalk( $val, $curRev = null ) {
2524 if ( wfReadOnly() ) {
2529 $this->mNewtalk
= $val;
2531 if ( $this->isAnon() ) {
2533 $id = $this->getName();
2536 $id = $this->getId();
2540 $changed = $this->updateNewtalk( $field, $id, $curRev );
2542 $changed = $this->deleteNewtalk( $field, $id );
2546 $this->invalidateCache();
2551 * Generate a current or new-future timestamp to be stored in the
2552 * user_touched field when we update things.
2554 * @return string Timestamp in TS_MW format
2556 private function newTouchedTimestamp() {
2558 if ( $this->mTouched
) {
2559 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2562 return wfTimestamp( TS_MW
, $time );
2566 * Clear user data from memcached
2568 * Use after applying updates to the database; caller's
2569 * responsibility to update user_touched if appropriate.
2571 * Called implicitly from invalidateCache() and saveSettings().
2573 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2575 public function clearSharedCache( $mode = 'refresh' ) {
2576 if ( !$this->getId() ) {
2580 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2581 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2582 $key = $this->getCacheKey( $cache );
2584 if ( $mode === 'refresh' ) {
2585 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2587 $lb->getConnectionRef( DB_MASTER
)->onTransactionPreCommitOrIdle(
2588 function () use ( $cache, $key ) {
2589 $cache->delete( $key );
2597 * Immediately touch the user data cache for this account
2599 * Calls touch() and removes account data from memcached
2601 public function invalidateCache() {
2603 $this->clearSharedCache( 'changed' );
2607 * Update the "touched" timestamp for the user
2609 * This is useful on various login/logout events when making sure that
2610 * a browser or proxy that has multiple tenants does not suffer cache
2611 * pollution where the new user sees the old users content. The value
2612 * of getTouched() is checked when determining 304 vs 200 responses.
2613 * Unlike invalidateCache(), this preserves the User object cache and
2614 * avoids database writes.
2618 public function touch() {
2619 $id = $this->getId();
2621 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2622 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2623 $cache->touchCheckKey( $key );
2624 $this->mQuickTouched
= null;
2629 * Validate the cache for this account.
2630 * @param string $timestamp A timestamp in TS_MW format
2633 public function validateCache( $timestamp ) {
2634 return ( $timestamp >= $this->getTouched() );
2638 * Get the user touched timestamp
2640 * Use this value only to validate caches via inequalities
2641 * such as in the case of HTTP If-Modified-Since response logic
2643 * @return string TS_MW Timestamp
2645 public function getTouched() {
2649 if ( $this->mQuickTouched
=== null ) {
2650 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2651 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2653 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2656 return max( $this->mTouched
, $this->mQuickTouched
);
2659 return $this->mTouched
;
2663 * Get the user_touched timestamp field (time of last DB updates)
2664 * @return string TS_MW Timestamp
2667 public function getDBTouched() {
2670 return $this->mTouched
;
2674 * Set the password and reset the random token.
2675 * Calls through to authentication plugin if necessary;
2676 * will have no effect if the auth plugin refuses to
2677 * pass the change through or if the legal password
2680 * As a special case, setting the password to null
2681 * wipes it, so the account cannot be logged in until
2682 * a new password is set, for instance via e-mail.
2684 * @deprecated since 1.27, use AuthManager instead
2685 * @param string $str New password to set
2686 * @throws PasswordError On failure
2689 public function setPassword( $str ) {
2690 wfDeprecated( __METHOD__
, '1.27' );
2691 return $this->setPasswordInternal( $str );
2695 * Set the password and reset the random token unconditionally.
2697 * @deprecated since 1.27, use AuthManager instead
2698 * @param string|null $str New password to set or null to set an invalid
2699 * password hash meaning that the user will not be able to log in
2700 * through the web interface.
2702 public function setInternalPassword( $str ) {
2703 wfDeprecated( __METHOD__
, '1.27' );
2704 $this->setPasswordInternal( $str );
2708 * Actually set the password and such
2709 * @since 1.27 cannot set a password for a user not in the database
2710 * @param string|null $str New password to set or null to set an invalid
2711 * password hash meaning that the user will not be able to log in
2712 * through the web interface.
2713 * @return bool Success
2715 private function setPasswordInternal( $str ) {
2716 $manager = AuthManager
::singleton();
2718 // If the user doesn't exist yet, fail
2719 if ( !$manager->userExists( $this->getName() ) ) {
2720 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2723 $status = $this->changeAuthenticationData( [
2724 'username' => $this->getName(),
2728 if ( !$status->isGood() ) {
2729 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2730 ->info( __METHOD__
. ': Password change rejected: '
2731 . $status->getWikiText( null, null, 'en' ) );
2735 $this->setOption( 'watchlisttoken', false );
2736 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2742 * Changes credentials of the user.
2744 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2745 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2746 * e.g. when no provider handled the change.
2748 * @param array $data A set of authentication data in fieldname => value format. This is the
2749 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2753 public function changeAuthenticationData( array $data ) {
2754 $manager = AuthManager
::singleton();
2755 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2756 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2758 $status = Status
::newGood( 'ignored' );
2759 foreach ( $reqs as $req ) {
2760 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2762 if ( $status->getValue() === 'ignored' ) {
2763 $status->warning( 'authenticationdatachange-ignored' );
2766 if ( $status->isGood() ) {
2767 foreach ( $reqs as $req ) {
2768 $manager->changeAuthenticationData( $req );
2775 * Get the user's current token.
2776 * @param bool $forceCreation Force the generation of a new token if the
2777 * user doesn't have one (default=true for backwards compatibility).
2778 * @return string|null Token
2780 public function getToken( $forceCreation = true ) {
2781 global $wgAuthenticationTokenVersion;
2784 if ( !$this->mToken
&& $forceCreation ) {
2788 if ( !$this->mToken
) {
2789 // The user doesn't have a token, return null to indicate that.
2793 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2794 // We return a random value here so existing token checks are very
2796 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2799 if ( $wgAuthenticationTokenVersion === null ) {
2800 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2801 return $this->mToken
;
2804 // $wgAuthenticationTokenVersion in use, so hmac it.
2805 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2807 // The raw hash can be overly long. Shorten it up.
2808 $len = max( 32, self
::TOKEN_LENGTH
);
2809 if ( strlen( $ret ) < $len ) {
2810 // Should never happen, even md5 is 128 bits
2811 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2814 return substr( $ret, -$len );
2818 * Set the random token (used for persistent authentication)
2819 * Called from loadDefaults() among other places.
2821 * @param string|bool $token If specified, set the token to this value
2823 public function setToken( $token = false ) {
2825 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2826 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2827 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2828 } elseif ( !$token ) {
2829 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2831 $this->mToken
= $token;
2836 * Set the password for a password reminder or new account email
2838 * @deprecated Removed in 1.27. Use PasswordReset instead.
2839 * @param string $str New password to set or null to set an invalid
2840 * password hash meaning that the user will not be able to use it
2841 * @param bool $throttle If true, reset the throttle timestamp to the present
2843 public function setNewpassword( $str, $throttle = true ) {
2844 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2848 * Get the user's e-mail address
2849 * @return string User's email address
2851 public function getEmail() {
2853 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2854 return $this->mEmail
;
2858 * Get the timestamp of the user's e-mail authentication
2859 * @return string TS_MW timestamp
2861 public function getEmailAuthenticationTimestamp() {
2863 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2864 return $this->mEmailAuthenticated
;
2868 * Set the user's e-mail address
2869 * @param string $str New e-mail address
2871 public function setEmail( $str ) {
2873 if ( $str == $this->mEmail
) {
2876 $this->invalidateEmail();
2877 $this->mEmail
= $str;
2878 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2882 * Set the user's e-mail address and a confirmation mail if needed.
2885 * @param string $str New e-mail address
2888 public function setEmailWithConfirmation( $str ) {
2889 global $wgEnableEmail, $wgEmailAuthentication;
2891 if ( !$wgEnableEmail ) {
2892 return Status
::newFatal( 'emaildisabled' );
2895 $oldaddr = $this->getEmail();
2896 if ( $str === $oldaddr ) {
2897 return Status
::newGood( true );
2900 $type = $oldaddr != '' ?
'changed' : 'set';
2901 $notificationResult = null;
2903 if ( $wgEmailAuthentication && $type === 'changed' ) {
2904 // Send the user an email notifying the user of the change in registered
2905 // email address on their previous email address
2906 $change = $str != '' ?
'changed' : 'removed';
2907 $notificationResult = $this->sendMail(
2908 wfMessage( 'notificationemail_subject_' . $change )->text(),
2909 wfMessage( 'notificationemail_body_' . $change,
2910 $this->getRequest()->getIP(),
2916 $this->setEmail( $str );
2918 if ( $str !== '' && $wgEmailAuthentication ) {
2919 // Send a confirmation request to the new address if needed
2920 $result = $this->sendConfirmationMail( $type );
2922 if ( $notificationResult !== null ) {
2923 $result->merge( $notificationResult );
2926 if ( $result->isGood() ) {
2927 // Say to the caller that a confirmation and notification mail has been sent
2928 $result->value
= 'eauth';
2931 $result = Status
::newGood( true );
2938 * Get the user's real name
2939 * @return string User's real name
2941 public function getRealName() {
2942 if ( !$this->isItemLoaded( 'realname' ) ) {
2946 return $this->mRealName
;
2950 * Set the user's real name
2951 * @param string $str New real name
2953 public function setRealName( $str ) {
2955 $this->mRealName
= $str;
2959 * Get the user's current setting for a given option.
2961 * @param string $oname The option to check
2962 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2963 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2964 * @return string|array|int|null User's current value for the option
2965 * @see getBoolOption()
2966 * @see getIntOption()
2968 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2969 global $wgHiddenPrefs;
2970 $this->loadOptions();
2972 # We want 'disabled' preferences to always behave as the default value for
2973 # users, even if they have set the option explicitly in their settings (ie they
2974 # set it, and then it was disabled removing their ability to change it). But
2975 # we don't want to erase the preferences in the database in case the preference
2976 # is re-enabled again. So don't touch $mOptions, just override the returned value
2977 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2978 return self
::getDefaultOption( $oname );
2981 if ( array_key_exists( $oname, $this->mOptions
) ) {
2982 return $this->mOptions
[$oname];
2985 return $defaultOverride;
2989 * Get all user's options
2991 * @param int $flags Bitwise combination of:
2992 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2993 * to the default value. (Since 1.25)
2996 public function getOptions( $flags = 0 ) {
2997 global $wgHiddenPrefs;
2998 $this->loadOptions();
2999 $options = $this->mOptions
;
3001 # We want 'disabled' preferences to always behave as the default value for
3002 # users, even if they have set the option explicitly in their settings (ie they
3003 # set it, and then it was disabled removing their ability to change it). But
3004 # we don't want to erase the preferences in the database in case the preference
3005 # is re-enabled again. So don't touch $mOptions, just override the returned value
3006 foreach ( $wgHiddenPrefs as $pref ) {
3007 $default = self
::getDefaultOption( $pref );
3008 if ( $default !== null ) {
3009 $options[$pref] = $default;
3013 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3014 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3021 * Get the user's current setting for a given option, as a boolean value.
3023 * @param string $oname The option to check
3024 * @return bool User's current value for the option
3027 public function getBoolOption( $oname ) {
3028 return (bool)$this->getOption( $oname );
3032 * Get the user's current setting for a given option, as an integer value.
3034 * @param string $oname The option to check
3035 * @param int $defaultOverride A default value returned if the option does not exist
3036 * @return int User's current value for the option
3039 public function getIntOption( $oname, $defaultOverride = 0 ) {
3040 $val = $this->getOption( $oname );
3042 $val = $defaultOverride;
3044 return intval( $val );
3048 * Set the given option for a user.
3050 * You need to call saveSettings() to actually write to the database.
3052 * @param string $oname The option to set
3053 * @param mixed $val New value to set
3055 public function setOption( $oname, $val ) {
3056 $this->loadOptions();
3058 // Explicitly NULL values should refer to defaults
3059 if ( is_null( $val ) ) {
3060 $val = self
::getDefaultOption( $oname );
3063 $this->mOptions
[$oname] = $val;
3067 * Get a token stored in the preferences (like the watchlist one),
3068 * resetting it if it's empty (and saving changes).
3070 * @param string $oname The option name to retrieve the token from
3071 * @return string|bool User's current value for the option, or false if this option is disabled.
3072 * @see resetTokenFromOption()
3074 * @deprecated since 1.26 Applications should use the OAuth extension
3076 public function getTokenFromOption( $oname ) {
3077 global $wgHiddenPrefs;
3079 $id = $this->getId();
3080 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3084 $token = $this->getOption( $oname );
3086 // Default to a value based on the user token to avoid space
3087 // wasted on storing tokens for all users. When this option
3088 // is set manually by the user, only then is it stored.
3089 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3096 * Reset a token stored in the preferences (like the watchlist one).
3097 * *Does not* save user's preferences (similarly to setOption()).
3099 * @param string $oname The option name to reset the token in
3100 * @return string|bool New token value, or false if this option is disabled.
3101 * @see getTokenFromOption()
3104 public function resetTokenFromOption( $oname ) {
3105 global $wgHiddenPrefs;
3106 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3110 $token = MWCryptRand
::generateHex( 40 );
3111 $this->setOption( $oname, $token );
3116 * Return a list of the types of user options currently returned by
3117 * User::getOptionKinds().
3119 * Currently, the option kinds are:
3120 * - 'registered' - preferences which are registered in core MediaWiki or
3121 * by extensions using the UserGetDefaultOptions hook.
3122 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3123 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3124 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3125 * be used by user scripts.
3126 * - 'special' - "preferences" that are not accessible via User::getOptions
3127 * or User::setOptions.
3128 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3129 * These are usually legacy options, removed in newer versions.
3131 * The API (and possibly others) use this function to determine the possible
3132 * option types for validation purposes, so make sure to update this when a
3133 * new option kind is added.
3135 * @see User::getOptionKinds
3136 * @return array Option kinds
3138 public static function listOptionKinds() {
3141 'registered-multiselect',
3142 'registered-checkmatrix',
3150 * Return an associative array mapping preferences keys to the kind of a preference they're
3151 * used for. Different kinds are handled differently when setting or reading preferences.
3153 * See User::listOptionKinds for the list of valid option types that can be provided.
3155 * @see User::listOptionKinds
3156 * @param IContextSource $context
3157 * @param array|null $options Assoc. array with options keys to check as keys.
3158 * Defaults to $this->mOptions.
3159 * @return array The key => kind mapping data
3161 public function getOptionKinds( IContextSource
$context, $options = null ) {
3162 $this->loadOptions();
3163 if ( $options === null ) {
3164 $options = $this->mOptions
;
3167 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3168 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3171 // Pull out the "special" options, so they don't get converted as
3172 // multiselect or checkmatrix.
3173 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3174 foreach ( $specialOptions as $name => $value ) {
3175 unset( $prefs[$name] );
3178 // Multiselect and checkmatrix options are stored in the database with
3179 // one key per option, each having a boolean value. Extract those keys.
3180 $multiselectOptions = [];
3181 foreach ( $prefs as $name => $info ) {
3182 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3183 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3184 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3185 $prefix = $info['prefix'] ??
$name;
3187 foreach ( $opts as $value ) {
3188 $multiselectOptions["$prefix$value"] = true;
3191 unset( $prefs[$name] );
3194 $checkmatrixOptions = [];
3195 foreach ( $prefs as $name => $info ) {
3196 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3197 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3198 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3199 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3200 $prefix = $info['prefix'] ??
$name;
3202 foreach ( $columns as $column ) {
3203 foreach ( $rows as $row ) {
3204 $checkmatrixOptions["$prefix$column-$row"] = true;
3208 unset( $prefs[$name] );
3212 // $value is ignored
3213 foreach ( $options as $key => $value ) {
3214 if ( isset( $prefs[$key] ) ) {
3215 $mapping[$key] = 'registered';
3216 } elseif ( isset( $multiselectOptions[$key] ) ) {
3217 $mapping[$key] = 'registered-multiselect';
3218 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3219 $mapping[$key] = 'registered-checkmatrix';
3220 } elseif ( isset( $specialOptions[$key] ) ) {
3221 $mapping[$key] = 'special';
3222 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3223 $mapping[$key] = 'userjs';
3225 $mapping[$key] = 'unused';
3233 * Reset certain (or all) options to the site defaults
3235 * The optional parameter determines which kinds of preferences will be reset.
3236 * Supported values are everything that can be reported by getOptionKinds()
3237 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3239 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3240 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3241 * for backwards-compatibility.
3242 * @param IContextSource|null $context Context source used when $resetKinds
3243 * does not contain 'all', passed to getOptionKinds().
3244 * Defaults to RequestContext::getMain() when null.
3246 public function resetOptions(
3247 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3248 IContextSource
$context = null
3251 $defaultOptions = self
::getDefaultOptions();
3253 if ( !is_array( $resetKinds ) ) {
3254 $resetKinds = [ $resetKinds ];
3257 if ( in_array( 'all', $resetKinds ) ) {
3258 $newOptions = $defaultOptions;
3260 if ( $context === null ) {
3261 $context = RequestContext
::getMain();
3264 $optionKinds = $this->getOptionKinds( $context );
3265 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3268 // Use default values for the options that should be deleted, and
3269 // copy old values for the ones that shouldn't.
3270 foreach ( $this->mOptions
as $key => $value ) {
3271 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3272 if ( array_key_exists( $key, $defaultOptions ) ) {
3273 $newOptions[$key] = $defaultOptions[$key];
3276 $newOptions[$key] = $value;
3281 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3283 $this->mOptions
= $newOptions;
3284 $this->mOptionsLoaded
= true;
3288 * Get the user's preferred date format.
3289 * @return string User's preferred date format
3291 public function getDatePreference() {
3292 // Important migration for old data rows
3293 if ( is_null( $this->mDatePreference
) ) {
3295 $value = $this->getOption( 'date' );
3296 $map = $wgLang->getDatePreferenceMigrationMap();
3297 if ( isset( $map[$value] ) ) {
3298 $value = $map[$value];
3300 $this->mDatePreference
= $value;
3302 return $this->mDatePreference
;
3306 * Determine based on the wiki configuration and the user's options,
3307 * whether this user must be over HTTPS no matter what.
3311 public function requiresHTTPS() {
3312 global $wgSecureLogin;
3313 if ( !$wgSecureLogin ) {
3317 $https = $this->getBoolOption( 'prefershttps' );
3318 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3320 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3327 * Get the user preferred stub threshold
3331 public function getStubThreshold() {
3332 global $wgMaxArticleSize; # Maximum article size, in Kb
3333 $threshold = $this->getIntOption( 'stubthreshold' );
3334 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3335 // If they have set an impossible value, disable the preference
3336 // so we can use the parser cache again.
3343 * Get the permissions this user has.
3344 * @return string[] permission names
3346 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3347 * ->getUserPermissions(..) instead
3350 public function getRights() {
3351 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3355 * Get the list of explicit group memberships this user has.
3356 * The implicit * and user groups are not included.
3358 * @return string[] Array of internal group names (sorted since 1.33)
3360 public function getGroups() {
3362 $this->loadGroups();
3363 return array_keys( $this->mGroupMemberships
);
3367 * Get the list of explicit group memberships this user has, stored as
3368 * UserGroupMembership objects. Implicit groups are not included.
3370 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3373 public function getGroupMemberships() {
3375 $this->loadGroups();
3376 return $this->mGroupMemberships
;
3380 * Get the list of implicit group memberships this user has.
3381 * This includes all explicit groups, plus 'user' if logged in,
3382 * '*' for all accounts, and autopromoted groups
3383 * @param bool $recache Whether to avoid the cache
3384 * @return array Array of String internal group names
3386 public function getEffectiveGroups( $recache = false ) {
3387 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3388 $this->mEffectiveGroups
= array_unique( array_merge(
3389 $this->getGroups(), // explicit groups
3390 $this->getAutomaticGroups( $recache ) // implicit groups
3392 // Avoid PHP 7.1 warning of passing $this by reference
3394 // Hook for additional groups
3395 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3396 // Force reindexation of groups when a hook has unset one of them
3397 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3399 return $this->mEffectiveGroups
;
3403 * Get the list of implicit group memberships this user has.
3404 * This includes 'user' if logged in, '*' for all accounts,
3405 * and autopromoted groups
3406 * @param bool $recache Whether to avoid the cache
3407 * @return array Array of String internal group names
3409 public function getAutomaticGroups( $recache = false ) {
3410 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3411 $this->mImplicitGroups
= [ '*' ];
3412 if ( $this->getId() ) {
3413 $this->mImplicitGroups
[] = 'user';
3415 $this->mImplicitGroups
= array_unique( array_merge(
3416 $this->mImplicitGroups
,
3417 Autopromote
::getAutopromoteGroups( $this )
3421 // Assure data consistency with rights/groups,
3422 // as getEffectiveGroups() depends on this function
3423 $this->mEffectiveGroups
= null;
3426 return $this->mImplicitGroups
;
3430 * Returns the groups the user has belonged to.
3432 * The user may still belong to the returned groups. Compare with getGroups().
3434 * The function will not return groups the user had belonged to before MW 1.17
3436 * @return array Names of the groups the user has belonged to.
3438 public function getFormerGroups() {
3441 if ( is_null( $this->mFormerGroups
) ) {
3442 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3443 ?
wfGetDB( DB_MASTER
)
3444 : wfGetDB( DB_REPLICA
);
3445 $res = $db->select( 'user_former_groups',
3447 [ 'ufg_user' => $this->mId
],
3449 $this->mFormerGroups
= [];
3450 foreach ( $res as $row ) {
3451 $this->mFormerGroups
[] = $row->ufg_group
;
3455 return $this->mFormerGroups
;
3459 * Get the user's edit count.
3460 * @return int|null Null for anonymous users
3462 public function getEditCount() {
3463 if ( !$this->getId() ) {
3467 if ( $this->mEditCount
=== null ) {
3468 /* Populate the count, if it has not been populated yet */
3469 $dbr = wfGetDB( DB_REPLICA
);
3470 // check if the user_editcount field has been initialized
3471 $count = $dbr->selectField(
3472 'user', 'user_editcount',
3473 [ 'user_id' => $this->mId
],
3477 if ( $count === null ) {
3478 // it has not been initialized. do so.
3479 $count = $this->initEditCountInternal( $dbr );
3481 $this->mEditCount
= $count;
3483 return (int)$this->mEditCount
;
3487 * Add the user to the given group. This takes immediate effect.
3488 * If the user is already in the group, the expiry time will be updated to the new
3489 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3492 * @param string $group Name of the group to add
3493 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3494 * wfTimestamp(), or null if the group assignment should not expire
3497 public function addGroup( $group, $expiry = null ) {
3499 $this->loadGroups();
3502 $expiry = wfTimestamp( TS_MW
, $expiry );
3505 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3509 // create the new UserGroupMembership and put it in the DB
3510 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3511 if ( !$ugm->insert( true ) ) {
3515 $this->mGroupMemberships
[$group] = $ugm;
3517 // Refresh the groups caches, and clear the rights cache so it will be
3518 // refreshed on the next call to $this->getRights().
3519 $this->getEffectiveGroups( true );
3520 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3521 $this->invalidateCache();
3527 * Remove the user from the given group.
3528 * This takes immediate effect.
3529 * @param string $group Name of the group to remove
3532 public function removeGroup( $group ) {
3535 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3539 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3540 // delete the membership entry
3541 if ( !$ugm ||
!$ugm->delete() ) {
3545 $this->loadGroups();
3546 unset( $this->mGroupMemberships
[$group] );
3548 // Refresh the groups caches, and clear the rights cache so it will be
3549 // refreshed on the next call to $this->getRights().
3550 $this->getEffectiveGroups( true );
3551 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3552 $this->invalidateCache();
3558 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3559 * only this new name and not the old isLoggedIn() variant.
3561 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3562 * anonymous or has no local account (which can happen when importing). This is equivalent to
3563 * getId() != 0 and is provided for code readability.
3566 public function isRegistered() {
3567 return $this->getId() != 0;
3571 * Get whether the user is logged in
3574 public function isLoggedIn() {
3575 return $this->isRegistered();
3579 * Get whether the user is anonymous
3582 public function isAnon() {
3583 return !$this->isRegistered();
3587 * @return bool Whether this user is flagged as being a bot role account
3590 public function isBot() {
3591 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3596 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3602 * Check if user is allowed to access a feature / make an action
3604 * @param string $permissions,... Permissions to test
3605 * @return bool True if user is allowed to perform *any* of the given actions
3607 public function isAllowedAny() {
3608 $permissions = func_get_args();
3609 foreach ( $permissions as $permission ) {
3610 if ( $this->isAllowed( $permission ) ) {
3619 * @param string $permissions,... Permissions to test
3620 * @return bool True if the user is allowed to perform *all* of the given actions
3622 public function isAllowedAll() {
3623 $permissions = func_get_args();
3624 foreach ( $permissions as $permission ) {
3625 if ( !$this->isAllowed( $permission ) ) {
3633 * Internal mechanics of testing a permission
3635 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3636 * ->getPermissionManager()->userHasRight(...) instead
3638 * @param string $action
3642 public function isAllowed( $action = '' ) {
3643 return MediaWikiServices
::getInstance()->getPermissionManager()
3644 ->userHasRight( $this, $action );
3648 * Check whether to enable recent changes patrol features for this user
3649 * @return bool True or false
3651 public function useRCPatrol() {
3652 global $wgUseRCPatrol;
3653 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3657 * Check whether to enable new pages patrol features for this user
3658 * @return bool True or false
3660 public function useNPPatrol() {
3661 global $wgUseRCPatrol, $wgUseNPPatrol;
3663 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3664 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3669 * Check whether to enable new files patrol features for this user
3670 * @return bool True or false
3672 public function useFilePatrol() {
3673 global $wgUseRCPatrol, $wgUseFilePatrol;
3675 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3676 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3681 * Get the WebRequest object to use with this object
3683 * @return WebRequest
3685 public function getRequest() {
3686 if ( $this->mRequest
) {
3687 return $this->mRequest
;
3695 * Check the watched status of an article.
3696 * @since 1.22 $checkRights parameter added
3697 * @param Title $title Title of the article to look at
3698 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3699 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3702 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3703 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3704 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3711 * @since 1.22 $checkRights parameter added
3712 * @param Title $title Title of the article to look at
3713 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3714 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3716 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3717 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3718 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3720 [ $title->getSubjectPage(), $title->getTalkPage() ]
3723 $this->invalidateCache();
3727 * Stop watching an article.
3728 * @since 1.22 $checkRights parameter added
3729 * @param Title $title Title of the article to look at
3730 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3731 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3733 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3734 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3735 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3736 $store->removeWatch( $this, $title->getSubjectPage() );
3737 $store->removeWatch( $this, $title->getTalkPage() );
3739 $this->invalidateCache();
3743 * Clear the user's notification timestamp for the given title.
3744 * If e-notif e-mails are on, they will receive notification mails on
3745 * the next change of the page if it's watched etc.
3746 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3747 * @param Title &$title Title of the article to look at
3748 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3750 public function clearNotification( &$title, $oldid = 0 ) {
3751 global $wgUseEnotif, $wgShowUpdatedMarker;
3753 // Do nothing if the database is locked to writes
3754 if ( wfReadOnly() ) {
3758 // Do nothing if not allowed to edit the watchlist
3759 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3763 // If we're working on user's talk page, we should update the talk page message indicator
3764 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3765 // Avoid PHP 7.1 warning of passing $this by reference
3767 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3771 // Try to update the DB post-send and only if needed...
3772 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3773 if ( !$this->getNewtalk() ) {
3774 return; // no notifications to clear
3777 // Delete the last notifications (they stack up)
3778 $this->setNewtalk( false );
3780 // If there is a new, unseen, revision, use its timestamp
3782 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3785 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3790 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3794 if ( $this->isAnon() ) {
3795 // Nothing else to do...
3799 // Only update the timestamp if the page is being watched.
3800 // The query to find out if it is watched is cached both in memcached and per-invocation,
3801 // and when it does have to be executed, it can be on a replica DB
3802 // If this is the user's newtalk page, we always update the timestamp
3804 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3808 MediaWikiServices
::getInstance()->getWatchedItemStore()
3809 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3813 * Resets all of the given user's page-change notification timestamps.
3814 * If e-notif e-mails are on, they will receive notification mails on
3815 * the next change of any watched page.
3816 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3818 public function clearAllNotifications() {
3819 global $wgUseEnotif, $wgShowUpdatedMarker;
3820 // Do nothing if not allowed to edit the watchlist
3821 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3825 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3826 $this->setNewtalk( false );
3830 $id = $this->getId();
3835 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3836 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3838 // We also need to clear here the "you have new message" notification for the own
3839 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3843 * Compute experienced level based on edit count and registration date.
3845 * @return string 'newcomer', 'learner', or 'experienced'
3847 public function getExperienceLevel() {
3848 global $wgLearnerEdits,
3849 $wgExperiencedUserEdits,
3850 $wgLearnerMemberSince,
3851 $wgExperiencedUserMemberSince;
3853 if ( $this->isAnon() ) {
3857 $editCount = $this->getEditCount();
3858 $registration = $this->getRegistration();
3860 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3861 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3863 if ( $editCount < $wgLearnerEdits ||
3864 $registration > $learnerRegistration ) {
3868 if ( $editCount > $wgExperiencedUserEdits &&
3869 $registration <= $experiencedRegistration
3871 return 'experienced';
3878 * Persist this user's session (e.g. set cookies)
3880 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3882 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3883 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3885 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3887 if ( $this->mId
== 0 ) {
3891 $session = $this->getRequest()->getSession();
3892 if ( $request && $session->getRequest() !== $request ) {
3893 $session = $session->sessionWithRequest( $request );
3895 $delay = $session->delaySave();
3897 if ( !$session->getUser()->equals( $this ) ) {
3898 if ( !$session->canSetUser() ) {
3899 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3900 ->warning( __METHOD__
.
3901 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3905 $session->setUser( $this );
3908 $session->setRememberUser( $rememberMe );
3909 if ( $secure !== null ) {
3910 $session->setForceHTTPS( $secure );
3913 $session->persist();
3915 ScopedCallback
::consume( $delay );
3919 * Log this user out.
3921 public function logout() {
3922 // Avoid PHP 7.1 warning of passing $this by reference
3924 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3930 * Clear the user's session, and reset the instance cache.
3933 public function doLogout() {
3934 $session = $this->getRequest()->getSession();
3935 if ( !$session->canSetUser() ) {
3936 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3937 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3938 $error = 'immutable';
3939 } elseif ( !$session->getUser()->equals( $this ) ) {
3940 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3941 ->warning( __METHOD__
.
3942 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3944 // But we still may as well make this user object anon
3945 $this->clearInstanceCache( 'defaults' );
3946 $error = 'wronguser';
3948 $this->clearInstanceCache( 'defaults' );
3949 $delay = $session->delaySave();
3950 $session->unpersist(); // Clear cookies (T127436)
3951 $session->setLoggedOutTimestamp( time() );
3952 $session->setUser( new User
);
3953 $session->set( 'wsUserID', 0 ); // Other code expects this
3954 $session->resetAllTokens();
3955 ScopedCallback
::consume( $delay );
3958 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3959 'event' => 'logout',
3960 'successful' => $error === false,
3961 'status' => $error ?
: 'success',
3966 * Save this user's settings into the database.
3967 * @todo Only rarely do all these fields need to be set!
3969 public function saveSettings() {
3970 if ( wfReadOnly() ) {
3971 // @TODO: caller should deal with this instead!
3972 // This should really just be an exception.
3973 MWExceptionHandler
::logException( new DBExpectedError(
3975 "Could not update user with ID '{$this->mId}'; DB is read-only."
3981 if ( $this->mId
== 0 ) {
3985 // Get a new user_touched that is higher than the old one.
3986 // This will be used for a CAS check as a last-resort safety
3987 // check against race conditions and replica DB lag.
3988 $newTouched = $this->newTouchedTimestamp();
3990 $dbw = wfGetDB( DB_MASTER
);
3991 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3992 global $wgActorTableSchemaMigrationStage;
3994 $dbw->update( 'user',
3996 'user_name' => $this->mName
,
3997 'user_real_name' => $this->mRealName
,
3998 'user_email' => $this->mEmail
,
3999 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4000 'user_touched' => $dbw->timestamp( $newTouched ),
4001 'user_token' => strval( $this->mToken
),
4002 'user_email_token' => $this->mEmailToken
,
4003 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4004 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4005 'user_id' => $this->mId
,
4009 if ( !$dbw->affectedRows() ) {
4010 // Maybe the problem was a missed cache update; clear it to be safe
4011 $this->clearSharedCache( 'refresh' );
4012 // User was changed in the meantime or loaded with stale data
4013 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4014 LoggerFactory
::getInstance( 'preferences' )->warning(
4015 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4016 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4018 throw new MWException( "CAS update failed on user_touched. " .
4019 "The version of the user to be saved is older than the current version."
4023 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4026 [ 'actor_name' => $this->mName
],
4027 [ 'actor_user' => $this->mId
],
4033 $this->mTouched
= $newTouched;
4034 $this->saveOptions();
4036 Hooks
::run( 'UserSaveSettings', [ $this ] );
4037 $this->clearSharedCache( 'changed' );
4038 $this->getUserPage()->purgeSquid();
4042 * If only this user's username is known, and it exists, return the user ID.
4044 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4047 public function idForName( $flags = 0 ) {
4048 $s = trim( $this->getName() );
4053 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4054 ?
wfGetDB( DB_MASTER
)
4055 : wfGetDB( DB_REPLICA
);
4057 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4058 ?
[ 'LOCK IN SHARE MODE' ]
4061 $id = $db->selectField( 'user',
4062 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4068 * Add a user to the database, return the user object
4070 * @param string $name Username to add
4071 * @param array $params Array of Strings Non-default parameters to save to
4072 * the database as user_* fields:
4073 * - email: The user's email address.
4074 * - email_authenticated: The email authentication timestamp.
4075 * - real_name: The user's real name.
4076 * - options: An associative array of non-default options.
4077 * - token: Random authentication token. Do not set.
4078 * - registration: Registration timestamp. Do not set.
4080 * @return User|null User object, or null if the username already exists.
4082 public static function createNew( $name, $params = [] ) {
4083 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4084 if ( isset( $params[$field] ) ) {
4085 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4086 unset( $params[$field] );
4092 $user->setToken(); // init token
4093 if ( isset( $params['options'] ) ) {
4094 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4095 unset( $params['options'] );
4097 $dbw = wfGetDB( DB_MASTER
);
4099 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4102 'user_name' => $name,
4103 'user_password' => $noPass,
4104 'user_newpassword' => $noPass,
4105 'user_email' => $user->mEmail
,
4106 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4107 'user_real_name' => $user->mRealName
,
4108 'user_token' => strval( $user->mToken
),
4109 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4110 'user_editcount' => 0,
4111 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4113 foreach ( $params as $name => $value ) {
4114 $fields["user_$name"] = $value;
4117 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4118 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4119 if ( $dbw->affectedRows() ) {
4120 $newUser = self
::newFromId( $dbw->insertId() );
4121 $newUser->mName
= $fields['user_name'];
4122 $newUser->updateActorId( $dbw );
4123 // Load the user from master to avoid replica lag
4124 $newUser->load( self
::READ_LATEST
);
4133 * Add this existing user object to the database. If the user already
4134 * exists, a fatal status object is returned, and the user object is
4135 * initialised with the data from the database.
4137 * Previously, this function generated a DB error due to a key conflict
4138 * if the user already existed. Many extension callers use this function
4139 * in code along the lines of:
4141 * $user = User::newFromName( $name );
4142 * if ( !$user->isLoggedIn() ) {
4143 * $user->addToDatabase();
4145 * // do something with $user...
4147 * However, this was vulnerable to a race condition (T18020). By
4148 * initialising the user object if the user exists, we aim to support this
4149 * calling sequence as far as possible.
4151 * Note that if the user exists, this function will acquire a write lock,
4152 * so it is still advisable to make the call conditional on isLoggedIn(),
4153 * and to commit the transaction after calling.
4155 * @throws MWException
4158 public function addToDatabase() {
4160 if ( !$this->mToken
) {
4161 $this->setToken(); // init token
4164 if ( !is_string( $this->mName
) ) {
4165 throw new RuntimeException( "User name field is not set." );
4168 $this->mTouched
= $this->newTouchedTimestamp();
4170 $dbw = wfGetDB( DB_MASTER
);
4171 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4172 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4173 $dbw->insert( 'user',
4175 'user_name' => $this->mName
,
4176 'user_password' => $noPass,
4177 'user_newpassword' => $noPass,
4178 'user_email' => $this->mEmail
,
4179 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4180 'user_real_name' => $this->mRealName
,
4181 'user_token' => strval( $this->mToken
),
4182 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4183 'user_editcount' => 0,
4184 'user_touched' => $dbw->timestamp( $this->mTouched
),
4188 if ( !$dbw->affectedRows() ) {
4189 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4190 $this->mId
= $dbw->selectField(
4193 [ 'user_name' => $this->mName
],
4195 [ 'LOCK IN SHARE MODE' ]
4198 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4202 throw new MWException( $fname . ": hit a key conflict attempting " .
4203 "to insert user '{$this->mName}' row, but it was not present in select!" );
4205 return Status
::newFatal( 'userexists' );
4207 $this->mId
= $dbw->insertId();
4208 self
::$idCacheByName[$this->mName
] = $this->mId
;
4209 $this->updateActorId( $dbw );
4211 return Status
::newGood();
4213 if ( !$status->isGood() ) {
4217 // Clear instance cache other than user table data and actor, which is already accurate
4218 $this->clearInstanceCache();
4220 $this->saveOptions();
4221 return Status
::newGood();
4225 * Update the actor ID after an insert
4226 * @param IDatabase $dbw Writable database handle
4228 private function updateActorId( IDatabase
$dbw ) {
4229 global $wgActorTableSchemaMigrationStage;
4231 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4234 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4237 $this->mActorId
= (int)$dbw->insertId();
4242 * If this user is logged-in and blocked,
4243 * block any IP address they've successfully logged in from.
4244 * @return bool A block was spread
4246 public function spreadAnyEditBlock() {
4247 if ( $this->isLoggedIn() && $this->getBlock() ) {
4248 return $this->spreadBlock();
4255 * If this (non-anonymous) user is blocked,
4256 * block the IP address they've successfully logged in from.
4257 * @return bool A block was spread
4259 protected function spreadBlock() {
4260 wfDebug( __METHOD__
. "()\n" );
4262 if ( $this->mId
== 0 ) {
4266 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4267 if ( !$userblock ) {
4271 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4275 * Get whether the user is explicitly blocked from account creation.
4276 * @return bool|AbstractBlock
4278 public function isBlockedFromCreateAccount() {
4279 $this->getBlockedStatus();
4280 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4281 return $this->mBlock
;
4284 # T15611: if the IP address the user is trying to create an account from is
4285 # blocked with createaccount disabled, prevent new account creation there even
4286 # when the user is logged in
4287 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4288 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4289 null, $this->getRequest()->getIP()
4292 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4293 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4294 ?
$this->mBlockedFromCreateAccount
4299 * Get whether the user is blocked from using Special:Emailuser.
4302 public function isBlockedFromEmailuser() {
4303 $this->getBlockedStatus();
4304 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4308 * Get whether the user is blocked from using Special:Upload
4313 public function isBlockedFromUpload() {
4314 $this->getBlockedStatus();
4315 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4319 * Get whether the user is allowed to create an account.
4322 public function isAllowedToCreateAccount() {
4323 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4327 * Get this user's personal page title.
4329 * @return Title User's personal page title
4331 public function getUserPage() {
4332 return Title
::makeTitle( NS_USER
, $this->getName() );
4336 * Get this user's talk page title.
4338 * @return Title User's talk page title
4340 public function getTalkPage() {
4341 $title = $this->getUserPage();
4342 return $title->getTalkPage();
4346 * Determine whether the user is a newbie. Newbies are either
4347 * anonymous IPs, or the most recently created accounts.
4350 public function isNewbie() {
4351 return !$this->isAllowed( 'autoconfirmed' );
4355 * Check to see if the given clear-text password is one of the accepted passwords
4356 * @deprecated since 1.27, use AuthManager instead
4357 * @param string $password User password
4358 * @return bool True if the given password is correct, otherwise False
4360 public function checkPassword( $password ) {
4361 wfDeprecated( __METHOD__
, '1.27' );
4363 $manager = AuthManager
::singleton();
4364 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4365 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4367 'username' => $this->getName(),
4368 'password' => $password,
4371 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4372 switch ( $res->status
) {
4373 case AuthenticationResponse
::PASS
:
4375 case AuthenticationResponse
::FAIL
:
4376 // Hope it's not a PreAuthenticationProvider that failed...
4377 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4378 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4381 throw new BadMethodCallException(
4382 'AuthManager returned a response unsupported by ' . __METHOD__
4388 * Check if the given clear-text password matches the temporary password
4389 * sent by e-mail for password reset operations.
4391 * @deprecated since 1.27, use AuthManager instead
4392 * @param string $plaintext
4393 * @return bool True if matches, false otherwise
4395 public function checkTemporaryPassword( $plaintext ) {
4396 wfDeprecated( __METHOD__
, '1.27' );
4397 // Can't check the temporary password individually.
4398 return $this->checkPassword( $plaintext );
4402 * Initialize (if necessary) and return a session token value
4403 * which can be used in edit forms to show that the user's
4404 * login credentials aren't being hijacked with a foreign form
4408 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4409 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4410 * @return MediaWiki\Session\Token The new edit token
4412 public function getEditTokenObject( $salt = '', $request = null ) {
4413 if ( $this->isAnon() ) {
4414 return new LoggedOutEditToken();
4418 $request = $this->getRequest();
4420 return $request->getSession()->getToken( $salt );
4424 * Initialize (if necessary) and return a session token value
4425 * which can be used in edit forms to show that the user's
4426 * login credentials aren't being hijacked with a foreign form
4429 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4432 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4433 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4434 * @return string The new edit token
4436 public function getEditToken( $salt = '', $request = null ) {
4437 return $this->getEditTokenObject( $salt, $request )->toString();
4441 * Check given value against the token value stored in the session.
4442 * A match should confirm that the form was submitted from the
4443 * user's own login session, not a form submission from a third-party
4446 * @param string $val Input value to compare
4447 * @param string|array $salt Optional function-specific data for hashing
4448 * @param WebRequest|null $request Object to use or null to use $wgRequest
4449 * @param int|null $maxage Fail tokens older than this, in seconds
4450 * @return bool Whether the token matches
4452 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4453 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4457 * Check given value against the token value stored in the session,
4458 * ignoring the suffix.
4460 * @param string $val Input value to compare
4461 * @param string|array $salt Optional function-specific data for hashing
4462 * @param WebRequest|null $request Object to use or null to use $wgRequest
4463 * @param int|null $maxage Fail tokens older than this, in seconds
4464 * @return bool Whether the token matches
4466 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4467 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4468 return $this->matchEditToken( $val, $salt, $request, $maxage );
4472 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4473 * mail to the user's given address.
4475 * @param string $type Message to send, either "created", "changed" or "set"
4478 public function sendConfirmationMail( $type = 'created' ) {
4480 $expiration = null; // gets passed-by-ref and defined in next line.
4481 $token = $this->confirmationToken( $expiration );
4482 $url = $this->confirmationTokenUrl( $token );
4483 $invalidateURL = $this->invalidationTokenUrl( $token );
4484 $this->saveSettings();
4486 if ( $type == 'created' ||
$type === false ) {
4487 $message = 'confirmemail_body';
4489 } elseif ( $type === true ) {
4490 $message = 'confirmemail_body_changed';
4493 // Messages: confirmemail_body_changed, confirmemail_body_set
4494 $message = 'confirmemail_body_' . $type;
4498 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4499 'body' => wfMessage( $message,
4500 $this->getRequest()->getIP(),
4503 $wgLang->userTimeAndDate( $expiration, $this ),
4505 $wgLang->userDate( $expiration, $this ),
4506 $wgLang->userTime( $expiration, $this ) )->text(),
4512 'ip' => $this->getRequest()->getIP(),
4513 'confirmURL' => $url,
4514 'invalidateURL' => $invalidateURL,
4515 'expiration' => $expiration
4518 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4519 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4523 * Send an e-mail to this user's account. Does not check for
4524 * confirmed status or validity.
4526 * @param string $subject Message subject
4527 * @param string $body Message body
4528 * @param User|null $from Optional sending user; if unspecified, default
4529 * $wgPasswordSender will be used.
4530 * @param MailAddress|null $replyto Reply-To address
4533 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4534 global $wgPasswordSender;
4536 if ( $from instanceof User
) {
4537 $sender = MailAddress
::newFromUser( $from );
4539 $sender = new MailAddress( $wgPasswordSender,
4540 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4542 $to = MailAddress
::newFromUser( $this );
4544 return UserMailer
::send( $to, $sender, $subject, $body, [
4545 'replyTo' => $replyto,
4550 * Generate, store, and return a new e-mail confirmation code.
4551 * A hash (unsalted, since it's used as a key) is stored.
4553 * @note Call saveSettings() after calling this function to commit
4554 * this change to the database.
4556 * @param string &$expiration Accepts the expiration time
4557 * @return string New token
4559 protected function confirmationToken( &$expiration ) {
4560 global $wgUserEmailConfirmationTokenExpiry;
4562 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4563 $expiration = wfTimestamp( TS_MW
, $expires );
4565 $token = MWCryptRand
::generateHex( 32 );
4566 $hash = md5( $token );
4567 $this->mEmailToken
= $hash;
4568 $this->mEmailTokenExpires
= $expiration;
4573 * Return a URL the user can use to confirm their email address.
4574 * @param string $token Accepts the email confirmation token
4575 * @return string New token URL
4577 protected function confirmationTokenUrl( $token ) {
4578 return $this->getTokenUrl( 'ConfirmEmail', $token );
4582 * Return a URL the user can use to invalidate their email address.
4583 * @param string $token Accepts the email confirmation token
4584 * @return string New token URL
4586 protected function invalidationTokenUrl( $token ) {
4587 return $this->getTokenUrl( 'InvalidateEmail', $token );
4591 * Internal function to format the e-mail validation/invalidation URLs.
4592 * This uses a quickie hack to use the
4593 * hardcoded English names of the Special: pages, for ASCII safety.
4595 * @note Since these URLs get dropped directly into emails, using the
4596 * short English names avoids insanely long URL-encoded links, which
4597 * also sometimes can get corrupted in some browsers/mailers
4598 * (T8957 with Gmail and Internet Explorer).
4600 * @param string $page Special page
4601 * @param string $token
4602 * @return string Formatted URL
4604 protected function getTokenUrl( $page, $token ) {
4605 // Hack to bypass localization of 'Special:'
4606 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4607 return $title->getCanonicalURL();
4611 * Mark the e-mail address confirmed.
4613 * @note Call saveSettings() after calling this function to commit the change.
4617 public function confirmEmail() {
4618 // Check if it's already confirmed, so we don't touch the database
4619 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4620 if ( !$this->isEmailConfirmed() ) {
4621 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4622 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4628 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4629 * address if it was already confirmed.
4631 * @note Call saveSettings() after calling this function to commit the change.
4632 * @return bool Returns true
4634 public function invalidateEmail() {
4636 $this->mEmailToken
= null;
4637 $this->mEmailTokenExpires
= null;
4638 $this->setEmailAuthenticationTimestamp( null );
4640 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4645 * Set the e-mail authentication timestamp.
4646 * @param string $timestamp TS_MW timestamp
4648 public function setEmailAuthenticationTimestamp( $timestamp ) {
4650 $this->mEmailAuthenticated
= $timestamp;
4651 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4655 * Is this user allowed to send e-mails within limits of current
4656 * site configuration?
4659 public function canSendEmail() {
4660 global $wgEnableEmail, $wgEnableUserEmail;
4661 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4664 $canSend = $this->isEmailConfirmed();
4665 // Avoid PHP 7.1 warning of passing $this by reference
4667 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4672 * Is this user allowed to receive e-mails within limits of current
4673 * site configuration?
4676 public function canReceiveEmail() {
4677 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4681 * Is this user's e-mail address valid-looking and confirmed within
4682 * limits of the current site configuration?
4684 * @note If $wgEmailAuthentication is on, this may require the user to have
4685 * confirmed their address by returning a code or using a password
4686 * sent to the address from the wiki.
4690 public function isEmailConfirmed() {
4691 global $wgEmailAuthentication;
4693 // Avoid PHP 7.1 warning of passing $this by reference
4696 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4697 if ( $this->isAnon() ) {
4700 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4703 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4713 * Check whether there is an outstanding request for e-mail confirmation.
4716 public function isEmailConfirmationPending() {
4717 global $wgEmailAuthentication;
4718 return $wgEmailAuthentication &&
4719 !$this->isEmailConfirmed() &&
4720 $this->mEmailToken
&&
4721 $this->mEmailTokenExpires
> wfTimestamp();
4725 * Get the timestamp of account creation.
4727 * @return string|bool|null Timestamp of account creation, false for
4728 * non-existent/anonymous user accounts, or null if existing account
4729 * but information is not in database.
4731 public function getRegistration() {
4732 if ( $this->isAnon() ) {
4736 return $this->mRegistration
;
4740 * Get the timestamp of the first edit
4742 * @return string|bool Timestamp of first edit, or false for
4743 * non-existent/anonymous user accounts.
4745 public function getFirstEditTimestamp() {
4746 return $this->getEditTimestamp( true );
4750 * Get the timestamp of the latest edit
4753 * @return string|bool Timestamp of first edit, or false for
4754 * non-existent/anonymous user accounts.
4756 public function getLatestEditTimestamp() {
4757 return $this->getEditTimestamp( false );
4761 * Get the timestamp of the first or latest edit
4763 * @param bool $first True for the first edit, false for the latest one
4764 * @return string|bool Timestamp of first or latest edit, or false for
4765 * non-existent/anonymous user accounts.
4767 private function getEditTimestamp( $first ) {
4768 if ( $this->getId() == 0 ) {
4769 return false; // anons
4771 $dbr = wfGetDB( DB_REPLICA
);
4772 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4773 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4774 ?
'revactor_timestamp' : 'rev_timestamp';
4775 $sortOrder = $first ?
'ASC' : 'DESC';
4776 $time = $dbr->selectField(
4777 [ 'revision' ] +
$actorWhere['tables'],
4779 [ $actorWhere['conds'] ],
4781 [ 'ORDER BY' => "$tsField $sortOrder" ],
4782 $actorWhere['joins']
4785 return false; // no edits
4787 return wfTimestamp( TS_MW
, $time );
4791 * Get the permissions associated with a given list of groups
4793 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4794 * ->getGroupPermissions() instead
4796 * @param array $groups Array of Strings List of internal group names
4797 * @return array Array of Strings List of permission key names for given groups combined
4799 public static function getGroupPermissions( $groups ) {
4800 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4804 * Get all the groups who have a given permission
4806 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4807 * ->getGroupsWithPermission() instead
4809 * @param string $role Role to check
4810 * @return array Array of Strings List of internal group names with the given permission
4812 public static function getGroupsWithPermission( $role ) {
4813 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4817 * Check, if the given group has the given permission
4819 * If you're wanting to check whether all users have a permission, use
4820 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4823 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4824 * ->groupHasPermission(..) instead
4827 * @param string $group Group to check
4828 * @param string $role Role to check
4831 public static function groupHasPermission( $group, $role ) {
4832 return MediaWikiServices
::getInstance()->getPermissionManager()
4833 ->groupHasPermission( $group, $role );
4837 * Check if all users may be assumed to have the given permission
4839 * We generally assume so if the right is granted to '*' and isn't revoked
4840 * on any group. It doesn't attempt to take grants or other extension
4841 * limitations on rights into account in the general case, though, as that
4842 * would require it to always return false and defeat the purpose.
4843 * Specifically, session-based rights restrictions (such as OAuth or bot
4844 * passwords) are applied based on the current session.
4846 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4847 * ->isEveryoneAllowed() instead
4849 * @param string $right Right to check
4854 public static function isEveryoneAllowed( $right ) {
4855 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4859 * Return the set of defined explicit groups.
4860 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4861 * are not included, as they are defined automatically, not in the database.
4862 * @return array Array of internal group names
4864 public static function getAllGroups() {
4865 global $wgGroupPermissions, $wgRevokePermissions;
4866 return array_values( array_diff(
4867 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4868 self
::getImplicitGroups()
4873 * Get a list of all available permissions.
4875 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4876 * ->getAllPermissions() instead
4878 * @return string[] Array of permission names
4880 public static function getAllRights() {
4881 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4885 * Get a list of implicit groups
4886 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4888 * @return array Array of Strings Array of internal group names
4890 public static function getImplicitGroups() {
4891 global $wgImplicitGroups;
4892 return $wgImplicitGroups;
4896 * Returns an array of the groups that a particular group can add/remove.
4898 * @param string $group The group to check for whether it can add/remove
4899 * @return array [ 'add' => [ addablegroups ],
4900 * 'remove' => [ removablegroups ],
4901 * 'add-self' => [ addablegroups to self ],
4902 * 'remove-self' => [ removable groups from self ] ]
4904 public static function changeableByGroup( $group ) {
4905 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4914 if ( empty( $wgAddGroups[$group] ) ) {
4915 // Don't add anything to $groups
4916 } elseif ( $wgAddGroups[$group] === true ) {
4917 // You get everything
4918 $groups['add'] = self
::getAllGroups();
4919 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4920 $groups['add'] = $wgAddGroups[$group];
4923 // Same thing for remove
4924 if ( empty( $wgRemoveGroups[$group] ) ) {
4926 } elseif ( $wgRemoveGroups[$group] === true ) {
4927 $groups['remove'] = self
::getAllGroups();
4928 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4929 $groups['remove'] = $wgRemoveGroups[$group];
4932 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4933 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4934 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4935 if ( is_int( $key ) ) {
4936 $wgGroupsAddToSelf['user'][] = $value;
4941 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4942 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4943 if ( is_int( $key ) ) {
4944 $wgGroupsRemoveFromSelf['user'][] = $value;
4949 // Now figure out what groups the user can add to him/herself
4950 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4952 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4953 // No idea WHY this would be used, but it's there
4954 $groups['add-self'] = self
::getAllGroups();
4955 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4956 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4959 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4961 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4962 $groups['remove-self'] = self
::getAllGroups();
4963 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4964 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4971 * Returns an array of groups that this user can add and remove
4972 * @return array [ 'add' => [ addablegroups ],
4973 * 'remove' => [ removablegroups ],
4974 * 'add-self' => [ addablegroups to self ],
4975 * 'remove-self' => [ removable groups from self ] ]
4977 public function changeableGroups() {
4978 if ( $this->isAllowed( 'userrights' ) ) {
4979 // This group gives the right to modify everything (reverse-
4980 // compatibility with old "userrights lets you change
4982 // Using array_merge to make the groups reindexed
4983 $all = array_merge( self
::getAllGroups() );
4992 // Okay, it's not so simple, we will have to go through the arrays
4999 $addergroups = $this->getEffectiveGroups();
5001 foreach ( $addergroups as $addergroup ) {
5002 $groups = array_merge_recursive(
5003 $groups, $this->changeableByGroup( $addergroup )
5005 $groups['add'] = array_unique( $groups['add'] );
5006 $groups['remove'] = array_unique( $groups['remove'] );
5007 $groups['add-self'] = array_unique( $groups['add-self'] );
5008 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5014 * Schedule a deferred update to update the user's edit count
5016 public function incEditCount() {
5017 if ( $this->isAnon() ) {
5021 DeferredUpdates
::addUpdate(
5022 new UserEditCountUpdate( $this, 1 ),
5023 DeferredUpdates
::POSTSEND
5028 * This method should not be called outside User/UserEditCountUpdate
5032 public function setEditCountInternal( $count ) {
5033 $this->mEditCount
= $count;
5037 * Initialize user_editcount from data out of the revision table
5039 * @internal This method should not be called outside User/UserEditCountUpdate
5040 * @param IDatabase $dbr Replica database
5041 * @return int Number of edits
5043 public function initEditCountInternal( IDatabase
$dbr ) {
5044 // Pull from a replica DB to be less cruel to servers
5045 // Accuracy isn't the point anyway here
5046 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5047 $count = (int)$dbr->selectField(
5048 [ 'revision' ] +
$actorWhere['tables'],
5050 [ $actorWhere['conds'] ],
5053 $actorWhere['joins']
5056 $dbw = wfGetDB( DB_MASTER
);
5059 [ 'user_editcount' => $count ],
5061 'user_id' => $this->getId(),
5062 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5071 * Get the description of a given right
5074 * @param string $right Right to query
5075 * @return string Localized description of the right
5077 public static function getRightDescription( $right ) {
5078 $key = "right-$right";
5079 $msg = wfMessage( $key );
5080 return $msg->isDisabled() ?
$right : $msg->text();
5084 * Get the name of a given grant
5087 * @param string $grant Grant to query
5088 * @return string Localized name of the grant
5090 public static function getGrantName( $grant ) {
5091 $key = "grant-$grant";
5092 $msg = wfMessage( $key );
5093 return $msg->isDisabled() ?
$grant : $msg->text();
5097 * Add a newuser log entry for this user.
5098 * Before 1.19 the return value was always true.
5100 * @deprecated since 1.27, AuthManager handles logging
5101 * @param string|bool $action Account creation type.
5102 * - String, one of the following values:
5103 * - 'create' for an anonymous user creating an account for himself.
5104 * This will force the action's performer to be the created user itself,
5105 * no matter the value of $wgUser
5106 * - 'create2' for a logged in user creating an account for someone else
5107 * - 'byemail' when the created user will receive its password by e-mail
5108 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5109 * - Boolean means whether the account was created by e-mail (deprecated):
5110 * - true will be converted to 'byemail'
5111 * - false will be converted to 'create' if this object is the same as
5112 * $wgUser and to 'create2' otherwise
5113 * @param string $reason User supplied reason
5116 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5117 return true; // disabled
5121 * Add an autocreate newuser log entry for this user
5122 * Used by things like CentralAuth and perhaps other authplugins.
5123 * Consider calling addNewUserLogEntry() directly instead.
5125 * @deprecated since 1.27, AuthManager handles logging
5128 public function addNewUserLogEntryAutoCreate() {
5129 $this->addNewUserLogEntry( 'autocreate' );
5135 * Load the user options either from cache, the database or an array
5137 * @param array|null $data Rows for the current user out of the user_properties table
5139 protected function loadOptions( $data = null ) {
5142 if ( $this->mOptionsLoaded
) {
5146 $this->mOptions
= self
::getDefaultOptions();
5148 if ( !$this->getId() ) {
5149 // For unlogged-in users, load language/variant options from request.
5150 // There's no need to do it for logged-in users: they can set preferences,
5151 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5152 // so don't override user's choice (especially when the user chooses site default).
5153 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5154 $this->mOptions
['variant'] = $variant;
5155 $this->mOptions
['language'] = $variant;
5156 $this->mOptionsLoaded
= true;
5160 // Maybe load from the object
5161 if ( !is_null( $this->mOptionOverrides
) ) {
5162 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5163 foreach ( $this->mOptionOverrides
as $key => $value ) {
5164 $this->mOptions
[$key] = $value;
5167 if ( !is_array( $data ) ) {
5168 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5169 // Load from database
5170 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5171 ?
wfGetDB( DB_MASTER
)
5172 : wfGetDB( DB_REPLICA
);
5174 $res = $dbr->select(
5176 [ 'up_property', 'up_value' ],
5177 [ 'up_user' => $this->getId() ],
5181 $this->mOptionOverrides
= [];
5183 foreach ( $res as $row ) {
5184 // Convert '0' to 0. PHP's boolean conversion considers them both
5185 // false, but e.g. JavaScript considers the former as true.
5186 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5187 // and convert all values here.
5188 if ( $row->up_value
=== '0' ) {
5191 $data[$row->up_property
] = $row->up_value
;
5195 foreach ( $data as $property => $value ) {
5196 $this->mOptionOverrides
[$property] = $value;
5197 $this->mOptions
[$property] = $value;
5201 // Replace deprecated language codes
5202 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5203 $this->mOptions
['language']
5206 $this->mOptionsLoaded
= true;
5208 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5212 * Saves the non-default options for this user, as previously set e.g. via
5213 * setOption(), in the database's "user_properties" (preferences) table.
5214 * Usually used via saveSettings().
5216 protected function saveOptions() {
5217 $this->loadOptions();
5219 // Not using getOptions(), to keep hidden preferences in database
5220 $saveOptions = $this->mOptions
;
5222 // Allow hooks to abort, for instance to save to a global profile.
5223 // Reset options to default state before saving.
5224 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5228 $userId = $this->getId();
5230 $insert_rows = []; // all the new preference rows
5231 foreach ( $saveOptions as $key => $value ) {
5232 // Don't bother storing default values
5233 $defaultOption = self
::getDefaultOption( $key );
5234 if ( ( $defaultOption === null && $value !== false && $value !== null )
5235 ||
$value != $defaultOption
5238 'up_user' => $userId,
5239 'up_property' => $key,
5240 'up_value' => $value,
5245 $dbw = wfGetDB( DB_MASTER
);
5247 $res = $dbw->select( 'user_properties',
5248 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5250 // Find prior rows that need to be removed or updated. These rows will
5251 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5253 foreach ( $res as $row ) {
5254 if ( !isset( $saveOptions[$row->up_property
] )
5255 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5257 $keysDelete[] = $row->up_property
;
5261 if ( count( $keysDelete ) ) {
5262 // Do the DELETE by PRIMARY KEY for prior rows.
5263 // In the past a very large portion of calls to this function are for setting
5264 // 'rememberpassword' for new accounts (a preference that has since been removed).
5265 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5266 // caused gap locks on [max user ID,+infinity) which caused high contention since
5267 // updates would pile up on each other as they are for higher (newer) user IDs.
5268 // It might not be necessary these days, but it shouldn't hurt either.
5269 $dbw->delete( 'user_properties',
5270 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5272 // Insert the new preference rows
5273 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5277 * Return the list of user fields that should be selected to create
5278 * a new user object.
5279 * @deprecated since 1.31, use self::getQueryInfo() instead.
5282 public static function selectFields() {
5283 wfDeprecated( __METHOD__
, '1.31' );
5291 'user_email_authenticated',
5293 'user_email_token_expires',
5294 'user_registration',
5300 * Return the tables, fields, and join conditions to be selected to create
5301 * a new user object.
5303 * @return array With three keys:
5304 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5305 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5306 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5308 public static function getQueryInfo() {
5309 global $wgActorTableSchemaMigrationStage;
5312 'tables' => [ 'user' ],
5320 'user_email_authenticated',
5322 'user_email_token_expires',
5323 'user_registration',
5329 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5330 // but it does little harm and might be needed for write callers loading a User.
5331 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5332 $ret['tables']['user_actor'] = 'actor';
5333 $ret['fields'][] = 'user_actor.actor_id';
5334 $ret['joins']['user_actor'] = [
5335 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5336 [ 'user_actor.actor_user = user_id' ]
5344 * Factory function for fatal permission-denied errors
5347 * @param string $permission User right required
5350 static function newFatalPermissionDeniedStatus( $permission ) {
5354 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5355 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5359 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5362 return Status
::newFatal( 'badaccess-group0' );
5366 * Get a new instance of this user that was loaded from the master via a locking read
5368 * Use this instead of the main context User when updating that user. This avoids races
5369 * where that user was loaded from a replica DB or even the master but without proper locks.
5371 * @return User|null Returns null if the user was not found in the DB
5374 public function getInstanceForUpdate() {
5375 if ( !$this->getId() ) {
5376 return null; // anon
5379 $user = self
::newFromId( $this->getId() );
5380 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5388 * Checks if two user objects point to the same user.
5390 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5391 * @param UserIdentity $user
5394 public function equals( UserIdentity
$user ) {
5395 // XXX it's not clear whether central ID providers are supposed to obey this
5396 return $this->getName() === $user->getName();
5400 * Checks if usertalk is allowed
5404 public function isAllowUsertalk() {
5405 return $this->mAllowUsertalk
;