3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\Block\DatabaseBlock
;
25 use MediaWiki\Block\SystemBlock
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Session\SessionManager
;
28 use MediaWiki\Session\Token
;
29 use MediaWiki\Auth\AuthManager
;
30 use MediaWiki\Auth\AuthenticationResponse
;
31 use MediaWiki\Auth\AuthenticationRequest
;
32 use MediaWiki\User\UserIdentity
;
33 use MediaWiki\Logger\LoggerFactory
;
34 use Wikimedia\Assert\Assert
;
36 use Wikimedia\ScopedCallback
;
37 use Wikimedia\Rdbms\Database
;
38 use Wikimedia\Rdbms\DBExpectedError
;
39 use Wikimedia\Rdbms\IDatabase
;
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
, UserIdentity
{
54 * Number of characters required for the user_token field.
56 const TOKEN_LENGTH
= 32;
59 * An invalid string value for the user_token field.
61 const INVALID_TOKEN
= '*** INVALID ***';
64 * Version number to tag cached versions of serialized User objects. Should be increased when
65 * {@link $mCacheVars} or one of it's members changes.
70 * Exclude user options that are set to their default value.
73 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
78 const CHECK_USER_RIGHTS
= true;
83 const IGNORE_USER_RIGHTS
= false;
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
113 /** Cache variables */
126 /** @var string TS_MW timestamp from the DB */
128 /** @var string TS_MW timestamp from cache */
129 protected $mQuickTouched;
133 public $mEmailAuthenticated;
135 protected $mEmailToken;
137 protected $mEmailTokenExpires;
139 protected $mRegistration;
141 protected $mEditCount;
142 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
143 protected $mGroupMemberships;
145 protected $mOptionOverrides;
150 * @var bool Whether the cache variables have been loaded.
152 public $mOptionsLoaded;
155 * @var array|bool Array with already loaded items or true if all items have been loaded.
157 protected $mLoadedItems = [];
161 * @var string Initialization data source if mLoadedItems!==true. May be one of:
162 * - 'defaults' anonymous user initialised from class defaults
163 * - 'name' initialise from mName
164 * - 'id' initialise from mId
165 * - 'actor' initialise from mActorId
166 * - 'session' log in from session if possible
168 * Use the User::newFrom*() family of functions to set this.
173 * Lazy-initialized variables, invalidated with clearInstanceCache
178 protected $mDatePreference;
184 protected $mBlockreason;
186 protected $mEffectiveGroups;
188 protected $mImplicitGroups;
190 protected $mFormerGroups;
191 /** @var AbstractBlock */
192 protected $mGlobalBlock;
200 /** @var WebRequest */
203 /** @var AbstractBlock */
207 protected $mAllowUsertalk;
209 /** @var AbstractBlock|bool */
210 private $mBlockedFromCreateAccount = false;
212 /** @var int User::READ_* constant bitfield used to load data */
213 protected $queryFlagsUsed = self
::READ_NORMAL
;
216 public static $idCacheByName = [];
219 * Lightweight constructor for an anonymous user.
220 * Use the User::newFrom* factory functions for other kinds of users.
224 * @see newFromActorId()
225 * @see newFromConfirmationCode()
226 * @see newFromSession()
229 public function __construct() {
230 $this->clearInstanceCache( 'defaults' );
236 public function __toString() {
237 return (string)$this->getName();
240 public function &__get( $name ) {
241 // A shortcut for $mRights deprecation phase
242 if ( $name === 'mRights' ) {
243 $copy = $this->getRights();
245 } elseif ( !property_exists( $this, $name ) ) {
246 // T227688 - do not break $u->foo['bar'] = 1
247 wfLogWarning( 'tried to get non-existent property' );
251 wfLogWarning( 'tried to get non-visible property' );
257 public function __set( $name, $value ) {
258 // A shortcut for $mRights deprecation phase, only known legitimate use was for
259 // testing purposes, other uses seem bad in principle
260 if ( $name === 'mRights' ) {
261 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
263 is_null( $value ) ?
[] : $value
265 } elseif ( !property_exists( $this, $name ) ) {
266 $this->$name = $value;
268 wfLogWarning( 'tried to set non-visible property' );
273 * Test if it's safe to load this User object.
275 * You should typically check this before using $wgUser or
276 * RequestContext::getUser in a method that might be called before the
277 * system has been fully initialized. If the object is unsafe, you should
278 * use an anonymous user:
280 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
286 public function isSafeToLoad() {
287 global $wgFullyInitialised;
289 // The user is safe to load if:
290 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
291 // * mLoadedItems === true (already loaded)
292 // * mFrom !== 'session' (sessions not involved at all)
294 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
295 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
299 * Load the user table data for this object from the source given by mFrom.
301 * @param int $flags User::READ_* constant bitfield
303 public function load( $flags = self
::READ_NORMAL
) {
304 global $wgFullyInitialised;
306 if ( $this->mLoadedItems
=== true ) {
310 // Set it now to avoid infinite recursion in accessors
311 $oldLoadedItems = $this->mLoadedItems
;
312 $this->mLoadedItems
= true;
313 $this->queryFlagsUsed
= $flags;
315 // If this is called too early, things are likely to break.
316 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
317 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
318 ->warning( 'User::loadFromSession called before the end of Setup.php', [
319 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
321 $this->loadDefaults();
322 $this->mLoadedItems
= $oldLoadedItems;
326 switch ( $this->mFrom
) {
328 $this->loadDefaults();
331 // Make sure this thread sees its own changes
332 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
333 if ( $lb->hasOrMadeRecentMasterChanges() ) {
334 $flags |
= self
::READ_LATEST
;
335 $this->queryFlagsUsed
= $flags;
338 $this->mId
= self
::idFromName( $this->mName
, $flags );
340 // Nonexistent user placeholder object
341 $this->loadDefaults( $this->mName
);
343 $this->loadFromId( $flags );
347 // Make sure this thread sees its own changes, if the ID isn't 0
348 if ( $this->mId
!= 0 ) {
349 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
350 if ( $lb->hasOrMadeRecentMasterChanges() ) {
351 $flags |
= self
::READ_LATEST
;
352 $this->queryFlagsUsed
= $flags;
356 $this->loadFromId( $flags );
359 // Make sure this thread sees its own changes
360 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
361 if ( $lb->hasOrMadeRecentMasterChanges() ) {
362 $flags |
= self
::READ_LATEST
;
363 $this->queryFlagsUsed
= $flags;
366 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
367 $row = wfGetDB( $index )->selectRow(
369 [ 'actor_user', 'actor_name' ],
370 [ 'actor_id' => $this->mActorId
],
377 $this->loadDefaults();
378 } elseif ( $row->actor_user
) {
379 $this->mId
= $row->actor_user
;
380 $this->loadFromId( $flags );
382 $this->loadDefaults( $row->actor_name
);
386 if ( !$this->loadFromSession() ) {
387 // Loading from session failed. Load defaults.
388 $this->loadDefaults();
390 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
393 throw new UnexpectedValueException(
394 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
399 * Load user table data, given mId has already been set.
400 * @param int $flags User::READ_* constant bitfield
401 * @return bool False if the ID does not exist, true otherwise
403 public function loadFromId( $flags = self
::READ_NORMAL
) {
404 if ( $this->mId
== 0 ) {
405 // Anonymous users are not in the database (don't need cache)
406 $this->loadDefaults();
410 // Try cache (unless this needs data from the master DB).
411 // NOTE: if this thread called saveSettings(), the cache was cleared.
412 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
414 if ( !$this->loadFromDatabase( $flags ) ) {
415 // Can't load from ID
419 $this->loadFromCache();
422 $this->mLoadedItems
= true;
423 $this->queryFlagsUsed
= $flags;
430 * @param string $dbDomain
433 public static function purge( $dbDomain, $userId ) {
434 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
435 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
436 $cache->delete( $key );
441 * @param WANObjectCache $cache
444 protected function getCacheKey( WANObjectCache
$cache ) {
445 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
447 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
451 * @param WANObjectCache $cache
455 public function getMutableCacheKeys( WANObjectCache
$cache ) {
456 $id = $this->getId();
458 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
462 * Load user data from shared cache, given mId has already been set.
467 protected function loadFromCache() {
468 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
469 $data = $cache->getWithSetCallback(
470 $this->getCacheKey( $cache ),
472 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
473 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
474 wfDebug( "User: cache miss for user {$this->mId}\n" );
476 $this->loadFromDatabase( self
::READ_NORMAL
);
478 $this->loadOptions();
481 foreach ( self
::$mCacheVars as $name ) {
482 $data[$name] = $this->$name;
485 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
487 // if a user group membership is about to expire, the cache needs to
488 // expire at that time (T163691)
489 foreach ( $this->mGroupMemberships
as $ugm ) {
490 if ( $ugm->getExpiry() ) {
491 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
492 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
493 $ttl = $secondsUntilExpiry;
500 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
503 // Restore from cache
504 foreach ( self
::$mCacheVars as $name ) {
505 $this->$name = $data[$name];
511 /** @name newFrom*() static factory methods */
515 * Static factory method for creation from username.
517 * This is slightly less efficient than newFromId(), so use newFromId() if
518 * you have both an ID and a name handy.
520 * @param string $name Username, validated by Title::newFromText()
521 * @param string|bool $validate Validate username. Takes the same parameters as
522 * User::getCanonicalName(), except that true is accepted as an alias
523 * for 'valid', for BC.
525 * @return User|bool User object, or false if the username is invalid
526 * (e.g. if it contains illegal characters or is an IP address). If the
527 * username is not present in the database, the result will be a user object
528 * with a name, zero user ID and default settings.
530 public static function newFromName( $name, $validate = 'valid' ) {
531 if ( $validate === true ) {
534 $name = self
::getCanonicalName( $name, $validate );
535 if ( $name === false ) {
539 // Create unloaded user object
543 $u->setItemLoaded( 'name' );
549 * Static factory method for creation from a given user ID.
551 * @param int $id Valid user ID
552 * @return User The corresponding User object
554 public static function newFromId( $id ) {
558 $u->setItemLoaded( 'id' );
563 * Static factory method for creation from a given actor ID.
566 * @param int $id Valid actor ID
567 * @return User The corresponding User object
569 public static function newFromActorId( $id ) {
570 global $wgActorTableSchemaMigrationStage;
572 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
573 // but it does little harm and might be needed for write callers loading a User.
574 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
575 throw new BadMethodCallException(
576 'Cannot use ' . __METHOD__
577 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
584 $u->setItemLoaded( 'actor' );
589 * Returns a User object corresponding to the given UserIdentity.
593 * @param UserIdentity $identity
597 public static function newFromIdentity( UserIdentity
$identity ) {
598 if ( $identity instanceof User
) {
602 return self
::newFromAnyId(
603 $identity->getId() === 0 ?
null : $identity->getId(),
604 $identity->getName() === '' ?
null : $identity->getName(),
605 $identity->getActorId() === 0 ?
null : $identity->getActorId()
610 * Static factory method for creation from an ID, name, and/or actor ID
612 * This does not check that the ID, name, and actor ID all correspond to
616 * @param int|null $userId User ID, if known
617 * @param string|null $userName User name, if known
618 * @param int|null $actorId Actor ID, if known
619 * @param bool|string $dbDomain remote wiki to which the User/Actor ID applies, or false if none
622 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
623 global $wgActorTableSchemaMigrationStage;
625 // Stop-gap solution for the problem described in T222212.
626 // Force the User ID and Actor ID to zero for users loaded from the database
627 // of another wiki, to prevent subtle data corruption and confusing failure modes.
628 if ( $dbDomain !== false ) {
634 $user->mFrom
= 'defaults';
636 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
637 // but it does little harm and might be needed for write callers loading a User.
638 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
639 $user->mActorId
= (int)$actorId;
640 if ( $user->mActorId
!== 0 ) {
641 $user->mFrom
= 'actor';
643 $user->setItemLoaded( 'actor' );
646 if ( $userName !== null && $userName !== '' ) {
647 $user->mName
= $userName;
648 $user->mFrom
= 'name';
649 $user->setItemLoaded( 'name' );
652 if ( $userId !== null ) {
653 $user->mId
= (int)$userId;
654 if ( $user->mId
!== 0 ) {
657 $user->setItemLoaded( 'id' );
660 if ( $user->mFrom
=== 'defaults' ) {
661 throw new InvalidArgumentException(
662 'Cannot create a user with no name, no ID, and no actor ID'
670 * Factory method to fetch whichever user has a given email confirmation code.
671 * This code is generated when an account is created or its e-mail address
674 * If the code is invalid or has expired, returns NULL.
676 * @param string $code Confirmation code
677 * @param int $flags User::READ_* bitfield
680 public static function newFromConfirmationCode( $code, $flags = 0 ) {
681 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
682 ?
wfGetDB( DB_MASTER
)
683 : wfGetDB( DB_REPLICA
);
685 $id = $db->selectField(
689 'user_email_token' => md5( $code ),
690 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
694 return $id ? self
::newFromId( $id ) : null;
698 * Create a new user object using data from session. If the login
699 * credentials are invalid, the result is an anonymous user.
701 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
704 public static function newFromSession( WebRequest
$request = null ) {
706 $user->mFrom
= 'session';
707 $user->mRequest
= $request;
712 * Create a new user object from a user row.
713 * The row should have the following fields from the user table in it:
714 * - either user_name or user_id to load further data if needed (or both)
716 * - all other fields (email, etc.)
717 * It is useless to provide the remaining fields if either user_id,
718 * user_name and user_real_name are not provided because the whole row
719 * will be loaded once more from the database when accessing them.
721 * @param stdClass $row A row from the user table
722 * @param array|null $data Further data to load into the object
723 * (see User::loadFromRow for valid keys)
726 public static function newFromRow( $row, $data = null ) {
728 $user->loadFromRow( $row, $data );
733 * Static factory method for creation of a "system" user from username.
735 * A "system" user is an account that's used to attribute logged actions
736 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
737 * might include the 'Maintenance script' or 'Conversion script' accounts
738 * used by various scripts in the maintenance/ directory or accounts such
739 * as 'MediaWiki message delivery' used by the MassMessage extension.
741 * This can optionally create the user if it doesn't exist, and "steal" the
742 * account if it does exist.
744 * "Stealing" an existing user is intended to make it impossible for normal
745 * authentication processes to use the account, effectively disabling the
746 * account for normal use:
747 * - Email is invalidated, to prevent account recovery by emailing a
748 * temporary password and to disassociate the account from the existing
750 * - The token is set to a magic invalid value, to kill existing sessions
751 * and to prevent $this->setToken() calls from resetting the token to a
753 * - SessionManager is instructed to prevent new sessions for the user, to
754 * do things like deauthorizing OAuth consumers.
755 * - AuthManager is instructed to revoke access, to invalidate or remove
756 * passwords and other credentials.
758 * @param string $name Username
759 * @param array $options Options are:
760 * - validate: As for User::getCanonicalName(), default 'valid'
761 * - create: Whether to create the user if it doesn't already exist, default true
762 * - steal: Whether to "disable" the account for normal use if it already
763 * exists, default false
767 public static function newSystemUser( $name, $options = [] ) {
769 'validate' => 'valid',
774 $name = self
::getCanonicalName( $name, $options['validate'] );
775 if ( $name === false ) {
779 $dbr = wfGetDB( DB_REPLICA
);
780 $userQuery = self
::getQueryInfo();
781 $row = $dbr->selectRow(
782 $userQuery['tables'],
783 $userQuery['fields'],
784 [ 'user_name' => $name ],
790 // Try the master database...
791 $dbw = wfGetDB( DB_MASTER
);
792 $row = $dbw->selectRow(
793 $userQuery['tables'],
794 $userQuery['fields'],
795 [ 'user_name' => $name ],
803 // No user. Create it?
804 return $options['create']
805 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
809 $user = self
::newFromRow( $row );
811 // A user is considered to exist as a non-system user if it can
812 // authenticate, or has an email set, or has a non-invalid token.
813 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
814 AuthManager
::singleton()->userCanAuthenticate( $name )
816 // User exists. Steal it?
817 if ( !$options['steal'] ) {
821 AuthManager
::singleton()->revokeAccessForUser( $name );
823 $user->invalidateEmail();
824 $user->mToken
= self
::INVALID_TOKEN
;
825 $user->saveSettings();
826 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
835 * Get the username corresponding to a given user ID
836 * @param int $id User ID
837 * @return string|bool The corresponding username
839 public static function whoIs( $id ) {
840 return UserCache
::singleton()->getProp( $id, 'name' );
844 * Get the real name of a user given their user ID
846 * @param int $id User ID
847 * @return string|bool The corresponding user's real name
849 public static function whoIsReal( $id ) {
850 return UserCache
::singleton()->getProp( $id, 'real_name' );
854 * Get database id given a user name
855 * @param string $name Username
856 * @param int $flags User::READ_* constant bitfield
857 * @return int|null The corresponding user's ID, or null if user is nonexistent
859 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
860 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
861 $name = (string)$name;
862 $nt = Title
::makeTitleSafe( NS_USER
, $name );
863 if ( is_null( $nt ) ) {
868 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
869 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
872 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
873 $db = wfGetDB( $index );
878 [ 'user_name' => $nt->getText() ],
883 if ( $s === false ) {
886 $result = (int)$s->user_id
;
889 if ( count( self
::$idCacheByName ) >= 1000 ) {
890 self
::$idCacheByName = [];
893 self
::$idCacheByName[$name] = $result;
899 * Reset the cache used in idFromName(). For use in tests.
901 public static function resetIdByNameCache() {
902 self
::$idCacheByName = [];
906 * Does the string match an anonymous IP address?
908 * This function exists for username validation, in order to reject
909 * usernames which are similar in form to IP addresses. Strings such
910 * as 300.300.300.300 will return true because it looks like an IP
911 * address, despite not being strictly valid.
913 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
914 * address because the usemod software would "cloak" anonymous IP
915 * addresses like this, if we allowed accounts like this to be created
916 * new users could get the old edits of these anonymous users.
918 * @param string $name Name to match
921 public static function isIP( $name ) {
922 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
923 || IP
::isIPv6( $name );
927 * Is the user an IP range?
932 public function isIPRange() {
933 return IP
::isValidRange( $this->mName
);
937 * Is the input a valid username?
939 * Checks if the input is a valid username, we don't want an empty string,
940 * an IP address, anything that contains slashes (would mess up subpages),
941 * is longer than the maximum allowed username size or doesn't begin with
944 * @param string $name Name to match
947 public static function isValidUserName( $name ) {
948 global $wgMaxNameChars;
951 || self
::isIP( $name )
952 ||
strpos( $name, '/' ) !== false
953 ||
strlen( $name ) > $wgMaxNameChars
954 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
959 // Ensure that the name can't be misresolved as a different title,
960 // such as with extra namespace keys at the start.
961 $parsed = Title
::newFromText( $name );
962 if ( is_null( $parsed )
963 ||
$parsed->getNamespace()
964 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
968 // Check an additional blacklist of troublemaker characters.
969 // Should these be merged into the title char list?
970 $unicodeBlacklist = '/[' .
971 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
972 '\x{00a0}' . # non-breaking space
973 '\x{2000}-\x{200f}' . # various whitespace
974 '\x{2028}-\x{202f}' . # breaks and control chars
975 '\x{3000}' . # ideographic space
976 '\x{e000}-\x{f8ff}' . # private use
978 if ( preg_match( $unicodeBlacklist, $name ) ) {
986 * Usernames which fail to pass this function will be blocked
987 * from user login and new account registrations, but may be used
988 * internally by batch processes.
990 * If an account already exists in this form, login will be blocked
991 * by a failure to pass this function.
993 * @param string $name Name to match
996 public static function isUsableName( $name ) {
997 global $wgReservedUsernames;
998 // Must be a valid username, obviously ;)
999 if ( !self
::isValidUserName( $name ) ) {
1003 static $reservedUsernames = false;
1004 if ( !$reservedUsernames ) {
1005 $reservedUsernames = $wgReservedUsernames;
1006 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1009 // Certain names may be reserved for batch processes.
1010 foreach ( $reservedUsernames as $reserved ) {
1011 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1012 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1014 if ( $reserved == $name ) {
1022 * Return the users who are members of the given group(s). In case of multiple groups,
1023 * users who are members of at least one of them are returned.
1025 * @param string|array $groups A single group name or an array of group names
1026 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1027 * records; larger values are ignored.
1028 * @param int|null $after ID the user to start after
1029 * @return UserArrayFromResult
1031 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1032 if ( $groups === [] ) {
1033 return UserArrayFromResult
::newFromIDs( [] );
1036 $groups = array_unique( (array)$groups );
1037 $limit = min( 5000, $limit );
1039 $conds = [ 'ug_group' => $groups ];
1040 if ( $after !== null ) {
1041 $conds[] = 'ug_user > ' . (int)$after;
1044 $dbr = wfGetDB( DB_REPLICA
);
1045 $ids = $dbr->selectFieldValues(
1052 'ORDER BY' => 'ug_user',
1056 return UserArray
::newFromIDs( $ids );
1060 * Usernames which fail to pass this function will be blocked
1061 * from new account registrations, but may be used internally
1062 * either by batch processes or by user accounts which have
1063 * already been created.
1065 * Additional blacklisting may be added here rather than in
1066 * isValidUserName() to avoid disrupting existing accounts.
1068 * @param string $name String to match
1071 public static function isCreatableName( $name ) {
1072 global $wgInvalidUsernameCharacters;
1074 // Ensure that the username isn't longer than 235 bytes, so that
1075 // (at least for the builtin skins) user javascript and css files
1076 // will work. (T25080)
1077 if ( strlen( $name ) > 235 ) {
1078 wfDebugLog( 'username', __METHOD__
.
1079 ": '$name' invalid due to length" );
1083 // Preg yells if you try to give it an empty string
1084 if ( $wgInvalidUsernameCharacters !== '' &&
1085 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1087 wfDebugLog( 'username', __METHOD__
.
1088 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1092 return self
::isUsableName( $name );
1096 * Is the input a valid password for this user?
1098 * @param string $password Desired password
1101 public function isValidPassword( $password ) {
1102 // simple boolean wrapper for checkPasswordValidity
1103 return $this->checkPasswordValidity( $password )->isGood();
1107 * Check if this is a valid password for this user
1109 * Returns a Status object with a set of messages describing
1110 * problems with the password. If the return status is fatal,
1111 * the action should be refused and the password should not be
1112 * checked at all (this is mainly meant for DoS mitigation).
1113 * If the return value is OK but not good, the password can be checked,
1114 * but the user should not be able to set their password to this.
1115 * The value of the returned Status object will be an array which
1116 * can have the following fields:
1117 * - forceChange (bool): if set to true, the user should not be
1118 * allowed to log with this password unless they change it during
1119 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1120 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1121 * a password change on login.
1123 * @param string $password Desired password
1127 public function checkPasswordValidity( $password ) {
1128 global $wgPasswordPolicy;
1130 $upp = new UserPasswordPolicy(
1131 $wgPasswordPolicy['policies'],
1132 $wgPasswordPolicy['checks']
1135 $status = Status
::newGood( [] );
1136 $result = false; // init $result to false for the internal checks
1138 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1139 $status->error( $result );
1143 if ( $result === false ) {
1144 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1148 if ( $result === true ) {
1152 $status->error( $result );
1153 return $status; // the isValidPassword hook set a string $result and returned true
1157 * Given unvalidated user input, return a canonical username, or false if
1158 * the username is invalid.
1159 * @param string $name User input
1160 * @param string|bool $validate Type of validation to use:
1161 * - false No validation
1162 * - 'valid' Valid for batch processes
1163 * - 'usable' Valid for batch processes and login
1164 * - 'creatable' Valid for batch processes, login and account creation
1166 * @throws InvalidArgumentException
1167 * @return bool|string
1169 public static function getCanonicalName( $name, $validate = 'valid' ) {
1170 // Force usernames to capital
1171 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1173 # Reject names containing '#'; these will be cleaned up
1174 # with title normalisation, but then it's too late to
1176 if ( strpos( $name, '#' ) !== false ) {
1180 // Clean up name according to title rules,
1181 // but only when validation is requested (T14654)
1182 $t = ( $validate !== false ) ?
1183 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1184 // Check for invalid titles
1185 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1189 $name = $t->getText();
1191 switch ( $validate ) {
1195 if ( !self
::isValidUserName( $name ) ) {
1200 if ( !self
::isUsableName( $name ) ) {
1205 if ( !self
::isCreatableName( $name ) ) {
1210 throw new InvalidArgumentException(
1211 'Invalid parameter value for $validate in ' . __METHOD__
);
1217 * Set cached properties to default.
1219 * @note This no longer clears uncached lazy-initialised properties;
1220 * the constructor does that instead.
1222 * @param string|bool $name
1224 public function loadDefaults( $name = false ) {
1226 $this->mName
= $name;
1227 $this->mActorId
= null;
1228 $this->mRealName
= '';
1230 $this->mOptionOverrides
= null;
1231 $this->mOptionsLoaded
= false;
1233 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1234 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1235 if ( $loggedOut !== 0 ) {
1236 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1238 $this->mTouched
= '1'; # Allow any pages to be cached
1241 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1242 $this->mEmailAuthenticated
= null;
1243 $this->mEmailToken
= '';
1244 $this->mEmailTokenExpires
= null;
1245 $this->mRegistration
= wfTimestamp( TS_MW
);
1246 $this->mGroupMemberships
= [];
1248 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1252 * Return whether an item has been loaded.
1254 * @param string $item Item to check. Current possibilities:
1258 * @param string $all 'all' to check if the whole object has been loaded
1259 * or any other string to check if only the item is available (e.g.
1263 public function isItemLoaded( $item, $all = 'all' ) {
1264 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1265 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1269 * Set that an item has been loaded
1271 * @param string $item
1273 protected function setItemLoaded( $item ) {
1274 if ( is_array( $this->mLoadedItems
) ) {
1275 $this->mLoadedItems
[$item] = true;
1280 * Load user data from the session.
1282 * @return bool True if the user is logged in, false otherwise.
1284 private function loadFromSession() {
1285 // MediaWiki\Session\Session already did the necessary authentication of the user
1286 // returned here, so just use it if applicable.
1287 $session = $this->getRequest()->getSession();
1288 $user = $session->getUser();
1289 if ( $user->isLoggedIn() ) {
1290 $this->loadFromUserObject( $user );
1292 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1293 // every session load, because an autoblocked editor might not edit again from the same
1294 // IP address after being blocked.
1295 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1297 // Other code expects these to be set in the session, so set them.
1298 $session->set( 'wsUserID', $this->getId() );
1299 $session->set( 'wsUserName', $this->getName() );
1300 $session->set( 'wsToken', $this->getToken() );
1309 * Set the 'BlockID' cookie depending on block type and user authentication status.
1311 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1313 public function trackBlockWithCookie() {
1314 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1318 * Load user and user_group data from the database.
1319 * $this->mId must be set, this is how the user is identified.
1321 * @param int $flags User::READ_* constant bitfield
1322 * @return bool True if the user exists, false if the user is anonymous
1324 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1326 $this->mId
= intval( $this->mId
);
1328 if ( !$this->mId
) {
1329 // Anonymous users are not in the database
1330 $this->loadDefaults();
1334 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1335 $db = wfGetDB( $index );
1337 $userQuery = self
::getQueryInfo();
1338 $s = $db->selectRow(
1339 $userQuery['tables'],
1340 $userQuery['fields'],
1341 [ 'user_id' => $this->mId
],
1347 $this->queryFlagsUsed
= $flags;
1348 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1350 if ( $s !== false ) {
1351 // Initialise user table data
1352 $this->loadFromRow( $s );
1353 $this->mGroupMemberships
= null; // deferred
1354 $this->getEditCount(); // revalidation for nulls
1360 $this->loadDefaults();
1366 * Initialize this object from a row from the user table.
1368 * @param stdClass $row Row from the user table to load.
1369 * @param array|null $data Further user data to load into the object
1371 * user_groups Array of arrays or stdClass result rows out of the user_groups
1372 * table. Previously you were supposed to pass an array of strings
1373 * here, but we also need expiry info nowadays, so an array of
1374 * strings is ignored.
1375 * user_properties Array with properties out of the user_properties table
1377 protected function loadFromRow( $row, $data = null ) {
1378 global $wgActorTableSchemaMigrationStage;
1380 if ( !is_object( $row ) ) {
1381 throw new InvalidArgumentException( '$row must be an object' );
1386 $this->mGroupMemberships
= null; // deferred
1388 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1389 // but it does little harm and might be needed for write callers loading a User.
1390 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1391 if ( isset( $row->actor_id
) ) {
1392 $this->mActorId
= (int)$row->actor_id
;
1393 if ( $this->mActorId
!== 0 ) {
1394 $this->mFrom
= 'actor';
1396 $this->setItemLoaded( 'actor' );
1402 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1403 $this->mName
= $row->user_name
;
1404 $this->mFrom
= 'name';
1405 $this->setItemLoaded( 'name' );
1410 if ( isset( $row->user_real_name
) ) {
1411 $this->mRealName
= $row->user_real_name
;
1412 $this->setItemLoaded( 'realname' );
1417 if ( isset( $row->user_id
) ) {
1418 $this->mId
= intval( $row->user_id
);
1419 if ( $this->mId
!== 0 ) {
1420 $this->mFrom
= 'id';
1422 $this->setItemLoaded( 'id' );
1427 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1428 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1431 if ( isset( $row->user_editcount
) ) {
1432 $this->mEditCount
= $row->user_editcount
;
1437 if ( isset( $row->user_touched
) ) {
1438 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1443 if ( isset( $row->user_token
) ) {
1444 // The definition for the column is binary(32), so trim the NULs
1445 // that appends. The previous definition was char(32), so trim
1447 $this->mToken
= rtrim( $row->user_token
, " \0" );
1448 if ( $this->mToken
=== '' ) {
1449 $this->mToken
= null;
1455 if ( isset( $row->user_email
) ) {
1456 $this->mEmail
= $row->user_email
;
1457 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1458 $this->mEmailToken
= $row->user_email_token
;
1459 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1460 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1466 $this->mLoadedItems
= true;
1469 if ( is_array( $data ) ) {
1470 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1471 if ( $data['user_groups'] === [] ) {
1472 $this->mGroupMemberships
= [];
1474 $firstGroup = reset( $data['user_groups'] );
1475 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1476 $this->mGroupMemberships
= [];
1477 foreach ( $data['user_groups'] as $row ) {
1478 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1479 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1484 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1485 $this->loadOptions( $data['user_properties'] );
1491 * Load the data for this user object from another user object.
1495 protected function loadFromUserObject( $user ) {
1497 foreach ( self
::$mCacheVars as $var ) {
1498 $this->$var = $user->$var;
1503 * Load the groups from the database if they aren't already loaded.
1505 private function loadGroups() {
1506 if ( is_null( $this->mGroupMemberships
) ) {
1507 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1508 ?
wfGetDB( DB_MASTER
)
1509 : wfGetDB( DB_REPLICA
);
1510 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1516 * Add the user to the group if he/she meets given criteria.
1518 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1519 * possible to remove manually via Special:UserRights. In such case it
1520 * will not be re-added automatically. The user will also not lose the
1521 * group if they no longer meet the criteria.
1523 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1525 * @return array Array of groups the user has been promoted to.
1527 * @see $wgAutopromoteOnce
1529 public function addAutopromoteOnceGroups( $event ) {
1530 global $wgAutopromoteOnceLogInRC;
1532 if ( wfReadOnly() ||
!$this->getId() ) {
1536 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1537 if ( $toPromote === [] ) {
1541 if ( !$this->checkAndSetTouched() ) {
1542 return []; // raced out (bug T48834)
1545 $oldGroups = $this->getGroups(); // previous groups
1546 $oldUGMs = $this->getGroupMemberships();
1547 foreach ( $toPromote as $group ) {
1548 $this->addGroup( $group );
1550 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1551 $newUGMs = $this->getGroupMemberships();
1553 // update groups in external authentication database
1554 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1556 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1557 $logEntry->setPerformer( $this );
1558 $logEntry->setTarget( $this->getUserPage() );
1559 $logEntry->setParameters( [
1560 '4::oldgroups' => $oldGroups,
1561 '5::newgroups' => $newGroups,
1563 $logid = $logEntry->insert();
1564 if ( $wgAutopromoteOnceLogInRC ) {
1565 $logEntry->publish( $logid );
1572 * Builds update conditions. Additional conditions may be added to $conditions to
1573 * protected against race conditions using a compare-and-set (CAS) mechanism
1574 * based on comparing $this->mTouched with the user_touched field.
1576 * @param IDatabase $db
1577 * @param array $conditions WHERE conditions for use with Database::update
1578 * @return array WHERE conditions for use with Database::update
1580 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1581 if ( $this->mTouched
) {
1582 // CAS check: only update if the row wasn't changed sicne it was loaded.
1583 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1590 * Bump user_touched if it didn't change since this object was loaded
1592 * On success, the mTouched field is updated.
1593 * The user serialization cache is always cleared.
1595 * @return bool Whether user_touched was actually updated
1598 protected function checkAndSetTouched() {
1601 if ( !$this->mId
) {
1602 return false; // anon
1605 // Get a new user_touched that is higher than the old one
1606 $newTouched = $this->newTouchedTimestamp();
1608 $dbw = wfGetDB( DB_MASTER
);
1609 $dbw->update( 'user',
1610 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1611 $this->makeUpdateConditions( $dbw, [
1612 'user_id' => $this->mId
,
1616 $success = ( $dbw->affectedRows() > 0 );
1619 $this->mTouched
= $newTouched;
1620 $this->clearSharedCache( 'changed' );
1622 // Clears on failure too since that is desired if the cache is stale
1623 $this->clearSharedCache( 'refresh' );
1630 * Clear various cached data stored in this object. The cache of the user table
1631 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1633 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1634 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1636 public function clearInstanceCache( $reloadFrom = false ) {
1637 global $wgFullyInitialised;
1639 $this->mNewtalk
= -1;
1640 $this->mDatePreference
= null;
1641 $this->mBlockedby
= -1; # Unset
1642 $this->mHash
= false;
1643 $this->mEffectiveGroups
= null;
1644 $this->mImplicitGroups
= null;
1645 $this->mGroupMemberships
= null;
1646 $this->mOptions
= null;
1647 $this->mOptionsLoaded
= false;
1648 $this->mEditCount
= null;
1650 // Replacement of former `$this->mRights = null` line
1651 if ( $wgFullyInitialised && $this->mFrom
) {
1652 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1657 if ( $reloadFrom ) {
1658 $this->mLoadedItems
= [];
1659 $this->mFrom
= $reloadFrom;
1663 /** @var array|null */
1664 private static $defOpt = null;
1665 /** @var string|null */
1666 private static $defOptLang = null;
1669 * Reset the process cache of default user options. This is only necessary
1670 * if the wiki configuration has changed since defaults were calculated,
1671 * and as such should only be performed inside the testing suite that
1672 * regularly changes wiki configuration.
1674 public static function resetGetDefaultOptionsForTestsOnly() {
1675 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1676 self
::$defOpt = null;
1677 self
::$defOptLang = null;
1681 * Combine the language default options with any site-specific options
1682 * and add the default language variants.
1684 * @return array Array of String options
1686 public static function getDefaultOptions() {
1687 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1689 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1690 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1691 // The content language does not change (and should not change) mid-request, but the
1692 // unit tests change it anyway, and expect this method to return values relevant to the
1693 // current content language.
1694 return self
::$defOpt;
1697 self
::$defOpt = $wgDefaultUserOptions;
1698 // Default language setting
1699 self
::$defOptLang = $contLang->getCode();
1700 self
::$defOpt['language'] = self
::$defOptLang;
1701 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1702 if ( $langCode === $contLang->getCode() ) {
1703 self
::$defOpt['variant'] = $langCode;
1705 self
::$defOpt["variant-$langCode"] = $langCode;
1709 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1710 // since extensions may change the set of searchable namespaces depending
1711 // on user groups/permissions.
1712 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1713 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1715 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1717 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1719 return self
::$defOpt;
1723 * Get a given default option value.
1725 * @param string $opt Name of option to retrieve
1726 * @return string Default option value
1728 public static function getDefaultOption( $opt ) {
1729 $defOpts = self
::getDefaultOptions();
1730 return $defOpts[$opt] ??
null;
1734 * Get blocking information
1736 * TODO: Move this into the BlockManager, along with block-related properties.
1738 * @param bool $fromReplica Whether to check the replica DB first.
1739 * To improve performance, non-critical checks are done against replica DBs.
1740 * Check when actually saving should be done against master.
1742 private function getBlockedStatus( $fromReplica = true ) {
1743 if ( $this->mBlockedby
!= -1 ) {
1747 wfDebug( __METHOD__
. ": checking...\n" );
1749 // Initialize data...
1750 // Otherwise something ends up stomping on $this->mBlockedby when
1751 // things get lazy-loaded later, causing false positive block hits
1752 // due to -1 !== 0. Probably session-related... Nothing should be
1753 // overwriting mBlockedby, surely?
1756 // @phan-suppress-next-line PhanAccessMethodInternal It's the only allowed use
1757 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1763 $this->mBlock
= $block;
1764 $this->mBlockedby
= $block->getByName();
1765 $this->mBlockreason
= $block->getReason();
1766 $this->mHideName
= $block->getHideName();
1767 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1769 $this->mBlock
= null;
1770 $this->mBlockedby
= '';
1771 $this->mBlockreason
= '';
1772 $this->mHideName
= 0;
1773 $this->mAllowUsertalk
= false;
1776 // Avoid PHP 7.1 warning of passing $this by reference
1779 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1783 * Whether the given IP is in a DNS blacklist.
1785 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1786 * @param string $ip IP to check
1787 * @param bool $checkWhitelist Whether to check the whitelist first
1788 * @return bool True if blacklisted.
1790 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1791 return MediaWikiServices
::getInstance()->getBlockManager()
1792 ->isDnsBlacklisted( $ip, $checkWhitelist );
1796 * Whether the given IP is in a given DNS blacklist.
1798 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1799 * @param string $ip IP to check
1800 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1801 * @return bool True if blacklisted.
1803 public function inDnsBlacklist( $ip, $bases ) {
1804 wfDeprecated( __METHOD__
, '1.34' );
1807 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1808 if ( IP
::isIPv4( $ip ) ) {
1809 // Reverse IP, T23255
1810 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1812 foreach ( (array)$bases as $base ) {
1814 // If we have an access key, use that too (ProjectHoneypot, etc.)
1816 if ( is_array( $base ) ) {
1817 if ( count( $base ) >= 2 ) {
1818 // Access key is 1, base URL is 0
1819 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1821 $host = "$ipReversed.{$base[0]}";
1823 $basename = $base[0];
1825 $host = "$ipReversed.$base";
1829 $ipList = gethostbynamel( $host );
1832 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1837 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1845 * Check if an IP address is in the local proxy list
1847 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1851 public static function isLocallyBlockedProxy( $ip ) {
1852 wfDeprecated( __METHOD__
, '1.34' );
1854 global $wgProxyList;
1856 if ( !$wgProxyList ) {
1860 if ( !is_array( $wgProxyList ) ) {
1861 // Load values from the specified file
1862 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1865 $resultProxyList = [];
1866 $deprecatedIPEntries = [];
1868 // backward compatibility: move all ip addresses in keys to values
1869 foreach ( $wgProxyList as $key => $value ) {
1870 $keyIsIP = IP
::isIPAddress( $key );
1871 $valueIsIP = IP
::isIPAddress( $value );
1872 if ( $keyIsIP && !$valueIsIP ) {
1873 $deprecatedIPEntries[] = $key;
1874 $resultProxyList[] = $key;
1875 } elseif ( $keyIsIP && $valueIsIP ) {
1876 $deprecatedIPEntries[] = $key;
1877 $resultProxyList[] = $key;
1878 $resultProxyList[] = $value;
1880 $resultProxyList[] = $value;
1884 if ( $deprecatedIPEntries ) {
1886 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1887 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1890 $proxyListIPSet = new IPSet( $resultProxyList );
1891 return $proxyListIPSet->match( $ip );
1895 * Is this user subject to rate limiting?
1897 * @return bool True if rate limited
1899 public function isPingLimitable() {
1900 global $wgRateLimitsExcludedIPs;
1901 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1902 // No other good way currently to disable rate limits
1903 // for specific IPs. :P
1904 // But this is a crappy hack and should die.
1907 return !$this->isAllowed( 'noratelimit' );
1911 * Primitive rate limits: enforce maximum actions per time period
1912 * to put a brake on flooding.
1914 * The method generates both a generic profiling point and a per action one
1915 * (suffix being "-$action".
1917 * @note When using a shared cache like memcached, IP-address
1918 * last-hit counters will be shared across wikis.
1920 * @param string $action Action to enforce; 'edit' if unspecified
1921 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1922 * @return bool True if a rate limiter was tripped
1924 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1925 // Avoid PHP 7.1 warning of passing $this by reference
1927 // Call the 'PingLimiter' hook
1929 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1933 global $wgRateLimits;
1934 if ( !isset( $wgRateLimits[$action] ) ) {
1938 $limits = array_merge(
1939 [ '&can-bypass' => true ],
1940 $wgRateLimits[$action]
1943 // Some groups shouldn't trigger the ping limiter, ever
1944 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1949 $id = $this->getId();
1951 $isNewbie = $this->isNewbie();
1952 $cache = ObjectCache
::getLocalClusterInstance();
1956 if ( isset( $limits['anon'] ) ) {
1957 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1959 } elseif ( isset( $limits['user'] ) ) {
1960 // limits for logged-in users
1961 $userLimit = $limits['user'];
1964 // limits for anons and for newbie logged-in users
1967 if ( isset( $limits['ip'] ) ) {
1968 $ip = $this->getRequest()->getIP();
1969 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1971 // subnet-based limits
1972 if ( isset( $limits['subnet'] ) ) {
1973 $ip = $this->getRequest()->getIP();
1974 $subnet = IP
::getSubnet( $ip );
1975 if ( $subnet !== false ) {
1976 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1981 // Check for group-specific permissions
1982 // If more than one group applies, use the group with the highest limit ratio (max/period)
1983 foreach ( $this->getGroups() as $group ) {
1984 if ( isset( $limits[$group] ) ) {
1985 if ( $userLimit === false
1986 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1988 $userLimit = $limits[$group];
1993 // limits for newbie logged-in users (override all the normal user limits)
1994 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1995 $userLimit = $limits['newbie'];
1998 // Set the user limit key
1999 if ( $userLimit !== false ) {
2000 // phan is confused because &can-bypass's value is a bool, so it assumes
2001 // that $userLimit is also a bool here.
2002 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2003 list( $max, $period ) = $userLimit;
2004 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2005 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2008 // ip-based limits for all ping-limitable users
2009 if ( isset( $limits['ip-all'] ) ) {
2010 $ip = $this->getRequest()->getIP();
2011 // ignore if user limit is more permissive
2012 if ( $isNewbie ||
$userLimit === false
2013 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2014 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2018 // subnet-based limits for all ping-limitable users
2019 if ( isset( $limits['subnet-all'] ) ) {
2020 $ip = $this->getRequest()->getIP();
2021 $subnet = IP
::getSubnet( $ip );
2022 if ( $subnet !== false ) {
2023 // ignore if user limit is more permissive
2024 if ( $isNewbie ||
$userLimit === false
2025 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2026 > $userLimit[0] / $userLimit[1] ) {
2027 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2033 foreach ( $keys as $key => $limit ) {
2034 // phan is confused because &can-bypass's value is a bool, so it assumes
2035 // that $userLimit is also a bool here.
2036 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2037 list( $max, $period ) = $limit;
2038 $summary = "(limit $max in {$period}s)";
2039 $count = $cache->get( $key );
2041 if ( $count && $count >= $max ) {
2042 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2043 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2046 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2047 if ( $incrBy > 0 ) {
2048 $cache->add( $key, 0, intval( $period ) ); // first ping
2051 if ( $incrBy > 0 ) {
2052 $cache->incrWithInit( $key, (int)$period, $incrBy, $incrBy );
2060 * Check if user is blocked
2062 * @deprecated since 1.34, use User::getBlock() or
2063 * PermissionManager::isBlockedFrom() or
2064 * PermissionManager::userCan() instead.
2066 * @param bool $fromReplica Whether to check the replica DB instead of
2067 * the master. Hacked from false due to horrible probs on site.
2068 * @return bool True if blocked, false otherwise
2070 public function isBlocked( $fromReplica = true ) {
2071 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2072 $this->getBlock()->appliesToRight( 'edit' );
2076 * Get the block affecting the user, or null if the user is not blocked
2078 * @param bool $fromReplica Whether to check the replica DB instead of the master
2079 * @return AbstractBlock|null
2081 public function getBlock( $fromReplica = true ) {
2082 $this->getBlockedStatus( $fromReplica );
2083 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2087 * Check if user is blocked from editing a particular article
2089 * @param Title $title Title to check
2090 * @param bool $fromReplica Whether to check the replica DB instead of the master
2093 * @deprecated since 1.33,
2094 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2097 public function isBlockedFrom( $title, $fromReplica = false ) {
2098 return MediaWikiServices
::getInstance()->getPermissionManager()
2099 ->isBlockedFrom( $this, $title, $fromReplica );
2103 * If user is blocked, return the name of the user who placed the block
2104 * @return string Name of blocker
2106 public function blockedBy() {
2107 $this->getBlockedStatus();
2108 return $this->mBlockedby
;
2112 * If user is blocked, return the specified reason for the block
2113 * @return string Blocking reason
2115 public function blockedFor() {
2116 $this->getBlockedStatus();
2117 return $this->mBlockreason
;
2121 * If user is blocked, return the ID for the block
2122 * @return int Block ID
2124 public function getBlockId() {
2125 $this->getBlockedStatus();
2126 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2130 * Check if user is blocked on all wikis.
2131 * Do not use for actual edit permission checks!
2132 * This is intended for quick UI checks.
2134 * @param string $ip IP address, uses current client if none given
2135 * @return bool True if blocked, false otherwise
2137 public function isBlockedGlobally( $ip = '' ) {
2138 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2142 * Check if user is blocked on all wikis.
2143 * Do not use for actual edit permission checks!
2144 * This is intended for quick UI checks.
2146 * @param string $ip IP address, uses current client if none given
2147 * @return AbstractBlock|null Block object if blocked, null otherwise
2148 * @throws FatalError
2149 * @throws MWException
2151 public function getGlobalBlock( $ip = '' ) {
2152 if ( $this->mGlobalBlock
!== null ) {
2153 return $this->mGlobalBlock ?
: null;
2155 // User is already an IP?
2156 if ( IP
::isIPAddress( $this->getName() ) ) {
2157 $ip = $this->getName();
2159 $ip = $this->getRequest()->getIP();
2161 // Avoid PHP 7.1 warning of passing $this by reference
2165 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2167 if ( $blocked && $block === null ) {
2168 // back-compat: UserIsBlockedGlobally didn't have $block param first
2169 $block = new SystemBlock( [
2171 'systemBlock' => 'global-block'
2175 $this->mGlobalBlock
= $blocked ?
$block : false;
2176 return $this->mGlobalBlock ?
: null;
2180 * Check if user account is locked
2182 * @return bool True if locked, false otherwise
2184 public function isLocked() {
2185 if ( $this->mLocked
!== null ) {
2186 return $this->mLocked
;
2189 $this->mLocked
= false;
2190 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2191 return $this->mLocked
;
2195 * Check if user account is hidden
2197 * @return bool True if hidden, false otherwise
2199 public function isHidden() {
2200 if ( $this->mHideName
!== null ) {
2201 return (bool)$this->mHideName
;
2203 $this->getBlockedStatus();
2204 if ( !$this->mHideName
) {
2206 $this->mHideName
= false;
2207 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2209 return (bool)$this->mHideName
;
2213 * Get the user's ID.
2214 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2216 public function getId() {
2217 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2218 // Special case, we know the user is anonymous
2222 if ( !$this->isItemLoaded( 'id' ) ) {
2223 // Don't load if this was initialized from an ID
2227 return (int)$this->mId
;
2231 * Set the user and reload all fields according to a given ID
2232 * @param int $v User ID to reload
2234 public function setId( $v ) {
2236 $this->clearInstanceCache( 'id' );
2240 * Get the user name, or the IP of an anonymous user
2241 * @return string User's name or IP address
2243 public function getName() {
2244 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2245 // Special case optimisation
2246 return $this->mName
;
2250 if ( $this->mName
=== false ) {
2252 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2255 return $this->mName
;
2259 * Set the user name.
2261 * This does not reload fields from the database according to the given
2262 * name. Rather, it is used to create a temporary "nonexistent user" for
2263 * later addition to the database. It can also be used to set the IP
2264 * address for an anonymous user to something other than the current
2267 * @note User::newFromName() has roughly the same function, when the named user
2269 * @param string $str New user name to set
2271 public function setName( $str ) {
2273 $this->mName
= $str;
2277 * Get the user's actor ID.
2279 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2280 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2282 public function getActorId( IDatabase
$dbw = null ) {
2283 global $wgActorTableSchemaMigrationStage;
2285 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2286 // but it does little harm and might be needed for write callers loading a User.
2287 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2291 if ( !$this->isItemLoaded( 'actor' ) ) {
2295 // Currently $this->mActorId might be null if $this was loaded from a
2296 // cache entry that was written when $wgActorTableSchemaMigrationStage
2297 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2298 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2299 // has been removed), that condition may be removed.
2300 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2302 'actor_user' => $this->getId() ?
: null,
2303 'actor_name' => (string)$this->getName(),
2306 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2307 throw new CannotCreateActorException(
2308 'Cannot create an actor for a usable name that is not an existing user'
2311 if ( $q['actor_name'] === '' ) {
2312 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2314 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2315 if ( $dbw->affectedRows() ) {
2316 $this->mActorId
= (int)$dbw->insertId();
2319 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2320 $this->mActorId
= (int)$dbw->selectField(
2325 [ 'LOCK IN SHARE MODE' ]
2327 if ( !$this->mActorId
) {
2328 throw new CannotCreateActorException(
2329 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2333 $this->invalidateCache();
2335 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2336 $db = wfGetDB( $index );
2337 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2339 $this->setItemLoaded( 'actor' );
2342 return (int)$this->mActorId
;
2346 * Get the user's name escaped by underscores.
2347 * @return string Username escaped by underscores.
2349 public function getTitleKey() {
2350 return str_replace( ' ', '_', $this->getName() );
2354 * Check if the user has new messages.
2355 * @return bool True if the user has new messages
2357 public function getNewtalk() {
2360 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2361 if ( $this->mNewtalk
=== -1 ) {
2362 $this->mNewtalk
= false; # reset talk page status
2364 // Check memcached separately for anons, who have no
2365 // entire User object stored in there.
2366 if ( !$this->mId
) {
2367 global $wgDisableAnonTalk;
2368 if ( $wgDisableAnonTalk ) {
2369 // Anon newtalk disabled by configuration.
2370 $this->mNewtalk
= false;
2372 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2375 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2379 return (bool)$this->mNewtalk
;
2383 * Return the data needed to construct links for new talk page message
2384 * alerts. If there are new messages, this will return an associative array
2385 * with the following data:
2386 * wiki: The database name of the wiki
2387 * link: Root-relative link to the user's talk page
2388 * rev: The last talk page revision that the user has seen or null. This
2389 * is useful for building diff links.
2390 * If there are no new messages, it returns an empty array.
2391 * @note This function was designed to accomodate multiple talk pages, but
2392 * currently only returns a single link and revision.
2395 public function getNewMessageLinks() {
2396 // Avoid PHP 7.1 warning of passing $this by reference
2399 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2403 if ( !$this->getNewtalk() ) {
2406 $utp = $this->getTalkPage();
2407 $dbr = wfGetDB( DB_REPLICA
);
2408 // Get the "last viewed rev" timestamp from the oldest message notification
2409 $timestamp = $dbr->selectField( 'user_newtalk',
2410 'MIN(user_last_timestamp)',
2411 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2413 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2416 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2417 'link' => $utp->getLocalURL(),
2424 * Get the revision ID for the last talk page revision viewed by the talk
2426 * @return int|null Revision ID or null
2428 public function getNewMessageRevisionId() {
2429 $newMessageRevisionId = null;
2430 $newMessageLinks = $this->getNewMessageLinks();
2432 // Note: getNewMessageLinks() never returns more than a single link
2433 // and it is always for the same wiki, but we double-check here in
2434 // case that changes some time in the future.
2435 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2436 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2437 && $newMessageLinks[0]['rev']
2439 /** @var Revision $newMessageRevision */
2440 $newMessageRevision = $newMessageLinks[0]['rev'];
2441 $newMessageRevisionId = $newMessageRevision->getId();
2444 return $newMessageRevisionId;
2448 * Internal uncached check for new messages
2451 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2452 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2453 * @return bool True if the user has new messages
2455 protected function checkNewtalk( $field, $id ) {
2456 $dbr = wfGetDB( DB_REPLICA
);
2458 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2460 return $ok !== false;
2464 * Add or update the new messages flag
2465 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2466 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2467 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2468 * @return bool True if successful, false otherwise
2470 protected function updateNewtalk( $field, $id, $curRev = null ) {
2471 // Get timestamp of the talk page revision prior to the current one
2472 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2473 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2474 // Mark the user as having new messages since this revision
2475 $dbw = wfGetDB( DB_MASTER
);
2476 $dbw->insert( 'user_newtalk',
2477 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2480 if ( $dbw->affectedRows() ) {
2481 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2485 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2490 * Clear the new messages flag for the given user
2491 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2492 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2493 * @return bool True if successful, false otherwise
2495 protected function deleteNewtalk( $field, $id ) {
2496 $dbw = wfGetDB( DB_MASTER
);
2497 $dbw->delete( 'user_newtalk',
2500 if ( $dbw->affectedRows() ) {
2501 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2505 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2510 * Update the 'You have new messages!' status.
2511 * @param bool $val Whether the user has new messages
2512 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2513 * page. Ignored if null or !$val.
2515 public function setNewtalk( $val, $curRev = null ) {
2516 if ( wfReadOnly() ) {
2521 $this->mNewtalk
= $val;
2523 if ( $this->isAnon() ) {
2525 $id = $this->getName();
2528 $id = $this->getId();
2532 $changed = $this->updateNewtalk( $field, $id, $curRev );
2534 $changed = $this->deleteNewtalk( $field, $id );
2538 $this->invalidateCache();
2543 * Generate a current or new-future timestamp to be stored in the
2544 * user_touched field when we update things.
2546 * @return string Timestamp in TS_MW format
2548 private function newTouchedTimestamp() {
2550 if ( $this->mTouched
) {
2551 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2554 return wfTimestamp( TS_MW
, $time );
2558 * Clear user data from memcached
2560 * Use after applying updates to the database; caller's
2561 * responsibility to update user_touched if appropriate.
2563 * Called implicitly from invalidateCache() and saveSettings().
2565 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2567 public function clearSharedCache( $mode = 'refresh' ) {
2568 if ( !$this->getId() ) {
2572 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2573 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2574 $key = $this->getCacheKey( $cache );
2576 if ( $mode === 'refresh' ) {
2577 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2579 $lb->getConnectionRef( DB_MASTER
)->onTransactionPreCommitOrIdle(
2580 function () use ( $cache, $key ) {
2581 $cache->delete( $key );
2589 * Immediately touch the user data cache for this account
2591 * Calls touch() and removes account data from memcached
2593 public function invalidateCache() {
2595 $this->clearSharedCache( 'changed' );
2599 * Update the "touched" timestamp for the user
2601 * This is useful on various login/logout events when making sure that
2602 * a browser or proxy that has multiple tenants does not suffer cache
2603 * pollution where the new user sees the old users content. The value
2604 * of getTouched() is checked when determining 304 vs 200 responses.
2605 * Unlike invalidateCache(), this preserves the User object cache and
2606 * avoids database writes.
2610 public function touch() {
2611 $id = $this->getId();
2613 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2614 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2615 $cache->touchCheckKey( $key );
2616 $this->mQuickTouched
= null;
2621 * Validate the cache for this account.
2622 * @param string $timestamp A timestamp in TS_MW format
2625 public function validateCache( $timestamp ) {
2626 return ( $timestamp >= $this->getTouched() );
2630 * Get the user touched timestamp
2632 * Use this value only to validate caches via inequalities
2633 * such as in the case of HTTP If-Modified-Since response logic
2635 * @return string TS_MW Timestamp
2637 public function getTouched() {
2641 if ( $this->mQuickTouched
=== null ) {
2642 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2643 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2645 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2648 return max( $this->mTouched
, $this->mQuickTouched
);
2651 return $this->mTouched
;
2655 * Get the user_touched timestamp field (time of last DB updates)
2656 * @return string TS_MW Timestamp
2659 public function getDBTouched() {
2662 return $this->mTouched
;
2666 * Set the password and reset the random token.
2667 * Calls through to authentication plugin if necessary;
2668 * will have no effect if the auth plugin refuses to
2669 * pass the change through or if the legal password
2672 * As a special case, setting the password to null
2673 * wipes it, so the account cannot be logged in until
2674 * a new password is set, for instance via e-mail.
2676 * @deprecated since 1.27, use AuthManager instead
2677 * @param string $str New password to set
2678 * @throws PasswordError On failure
2681 public function setPassword( $str ) {
2682 wfDeprecated( __METHOD__
, '1.27' );
2683 return $this->setPasswordInternal( $str );
2687 * Set the password and reset the random token unconditionally.
2689 * @deprecated since 1.27, use AuthManager instead
2690 * @param string|null $str New password to set or null to set an invalid
2691 * password hash meaning that the user will not be able to log in
2692 * through the web interface.
2694 public function setInternalPassword( $str ) {
2695 wfDeprecated( __METHOD__
, '1.27' );
2696 $this->setPasswordInternal( $str );
2700 * Actually set the password and such
2701 * @since 1.27 cannot set a password for a user not in the database
2702 * @param string|null $str New password to set or null to set an invalid
2703 * password hash meaning that the user will not be able to log in
2704 * through the web interface.
2705 * @return bool Success
2707 private function setPasswordInternal( $str ) {
2708 $manager = AuthManager
::singleton();
2710 // If the user doesn't exist yet, fail
2711 if ( !$manager->userExists( $this->getName() ) ) {
2712 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2715 $status = $this->changeAuthenticationData( [
2716 'username' => $this->getName(),
2720 if ( !$status->isGood() ) {
2721 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2722 ->info( __METHOD__
. ': Password change rejected: '
2723 . $status->getWikiText( null, null, 'en' ) );
2727 $this->setOption( 'watchlisttoken', false );
2728 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2734 * Changes credentials of the user.
2736 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2737 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2738 * e.g. when no provider handled the change.
2740 * @param array $data A set of authentication data in fieldname => value format. This is the
2741 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2745 public function changeAuthenticationData( array $data ) {
2746 $manager = AuthManager
::singleton();
2747 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2748 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2750 $status = Status
::newGood( 'ignored' );
2751 foreach ( $reqs as $req ) {
2752 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2754 if ( $status->getValue() === 'ignored' ) {
2755 $status->warning( 'authenticationdatachange-ignored' );
2758 if ( $status->isGood() ) {
2759 foreach ( $reqs as $req ) {
2760 $manager->changeAuthenticationData( $req );
2767 * Get the user's current token.
2768 * @param bool $forceCreation Force the generation of a new token if the
2769 * user doesn't have one (default=true for backwards compatibility).
2770 * @return string|null Token
2772 public function getToken( $forceCreation = true ) {
2773 global $wgAuthenticationTokenVersion;
2776 if ( !$this->mToken
&& $forceCreation ) {
2780 if ( !$this->mToken
) {
2781 // The user doesn't have a token, return null to indicate that.
2785 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2786 // We return a random value here so existing token checks are very
2788 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2791 if ( $wgAuthenticationTokenVersion === null ) {
2792 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2793 return $this->mToken
;
2796 // $wgAuthenticationTokenVersion in use, so hmac it.
2797 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2799 // The raw hash can be overly long. Shorten it up.
2800 $len = max( 32, self
::TOKEN_LENGTH
);
2801 if ( strlen( $ret ) < $len ) {
2802 // Should never happen, even md5 is 128 bits
2803 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2806 return substr( $ret, -$len );
2810 * Set the random token (used for persistent authentication)
2811 * Called from loadDefaults() among other places.
2813 * @param string|bool $token If specified, set the token to this value
2815 public function setToken( $token = false ) {
2817 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2818 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2819 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2820 } elseif ( !$token ) {
2821 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2823 $this->mToken
= $token;
2828 * Set the password for a password reminder or new account email
2830 * @deprecated Removed in 1.27. Use PasswordReset instead.
2831 * @param string $str New password to set or null to set an invalid
2832 * password hash meaning that the user will not be able to use it
2833 * @param bool $throttle If true, reset the throttle timestamp to the present
2835 public function setNewpassword( $str, $throttle = true ) {
2836 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2840 * Get the user's e-mail address
2841 * @return string User's email address
2843 public function getEmail() {
2845 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2846 return $this->mEmail
;
2850 * Get the timestamp of the user's e-mail authentication
2851 * @return string TS_MW timestamp
2853 public function getEmailAuthenticationTimestamp() {
2855 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2856 return $this->mEmailAuthenticated
;
2860 * Set the user's e-mail address
2861 * @param string $str New e-mail address
2863 public function setEmail( $str ) {
2865 if ( $str == $this->mEmail
) {
2868 $this->invalidateEmail();
2869 $this->mEmail
= $str;
2870 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2874 * Set the user's e-mail address and a confirmation mail if needed.
2877 * @param string $str New e-mail address
2880 public function setEmailWithConfirmation( $str ) {
2881 global $wgEnableEmail, $wgEmailAuthentication;
2883 if ( !$wgEnableEmail ) {
2884 return Status
::newFatal( 'emaildisabled' );
2887 $oldaddr = $this->getEmail();
2888 if ( $str === $oldaddr ) {
2889 return Status
::newGood( true );
2892 $type = $oldaddr != '' ?
'changed' : 'set';
2893 $notificationResult = null;
2895 if ( $wgEmailAuthentication && $type === 'changed' ) {
2896 // Send the user an email notifying the user of the change in registered
2897 // email address on their previous email address
2898 $change = $str != '' ?
'changed' : 'removed';
2899 $notificationResult = $this->sendMail(
2900 wfMessage( 'notificationemail_subject_' . $change )->text(),
2901 wfMessage( 'notificationemail_body_' . $change,
2902 $this->getRequest()->getIP(),
2908 $this->setEmail( $str );
2910 if ( $str !== '' && $wgEmailAuthentication ) {
2911 // Send a confirmation request to the new address if needed
2912 $result = $this->sendConfirmationMail( $type );
2914 if ( $notificationResult !== null ) {
2915 $result->merge( $notificationResult );
2918 if ( $result->isGood() ) {
2919 // Say to the caller that a confirmation and notification mail has been sent
2920 $result->value
= 'eauth';
2923 $result = Status
::newGood( true );
2930 * Get the user's real name
2931 * @return string User's real name
2933 public function getRealName() {
2934 if ( !$this->isItemLoaded( 'realname' ) ) {
2938 return $this->mRealName
;
2942 * Set the user's real name
2943 * @param string $str New real name
2945 public function setRealName( $str ) {
2947 $this->mRealName
= $str;
2951 * Get the user's current setting for a given option.
2953 * @param string $oname The option to check
2954 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2955 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2956 * @return string|array|int|null User's current value for the option
2957 * @see getBoolOption()
2958 * @see getIntOption()
2960 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2961 global $wgHiddenPrefs;
2962 $this->loadOptions();
2964 # We want 'disabled' preferences to always behave as the default value for
2965 # users, even if they have set the option explicitly in their settings (ie they
2966 # set it, and then it was disabled removing their ability to change it). But
2967 # we don't want to erase the preferences in the database in case the preference
2968 # is re-enabled again. So don't touch $mOptions, just override the returned value
2969 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2970 return self
::getDefaultOption( $oname );
2973 if ( array_key_exists( $oname, $this->mOptions
) ) {
2974 return $this->mOptions
[$oname];
2977 return $defaultOverride;
2981 * Get all user's options
2983 * @param int $flags Bitwise combination of:
2984 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2985 * to the default value. (Since 1.25)
2988 public function getOptions( $flags = 0 ) {
2989 global $wgHiddenPrefs;
2990 $this->loadOptions();
2991 $options = $this->mOptions
;
2993 # We want 'disabled' preferences to always behave as the default value for
2994 # users, even if they have set the option explicitly in their settings (ie they
2995 # set it, and then it was disabled removing their ability to change it). But
2996 # we don't want to erase the preferences in the database in case the preference
2997 # is re-enabled again. So don't touch $mOptions, just override the returned value
2998 foreach ( $wgHiddenPrefs as $pref ) {
2999 $default = self
::getDefaultOption( $pref );
3000 if ( $default !== null ) {
3001 $options[$pref] = $default;
3005 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3006 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3013 * Get the user's current setting for a given option, as a boolean value.
3015 * @param string $oname The option to check
3016 * @return bool User's current value for the option
3019 public function getBoolOption( $oname ) {
3020 return (bool)$this->getOption( $oname );
3024 * Get the user's current setting for a given option, as an integer value.
3026 * @param string $oname The option to check
3027 * @param int $defaultOverride A default value returned if the option does not exist
3028 * @return int User's current value for the option
3031 public function getIntOption( $oname, $defaultOverride = 0 ) {
3032 $val = $this->getOption( $oname );
3034 $val = $defaultOverride;
3036 return intval( $val );
3040 * Set the given option for a user.
3042 * You need to call saveSettings() to actually write to the database.
3044 * @param string $oname The option to set
3045 * @param mixed $val New value to set
3047 public function setOption( $oname, $val ) {
3048 $this->loadOptions();
3050 // Explicitly NULL values should refer to defaults
3051 if ( is_null( $val ) ) {
3052 $val = self
::getDefaultOption( $oname );
3055 $this->mOptions
[$oname] = $val;
3059 * Get a token stored in the preferences (like the watchlist one),
3060 * resetting it if it's empty (and saving changes).
3062 * @param string $oname The option name to retrieve the token from
3063 * @return string|bool User's current value for the option, or false if this option is disabled.
3064 * @see resetTokenFromOption()
3066 * @deprecated since 1.26 Applications should use the OAuth extension
3068 public function getTokenFromOption( $oname ) {
3069 global $wgHiddenPrefs;
3071 $id = $this->getId();
3072 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3076 $token = $this->getOption( $oname );
3078 // Default to a value based on the user token to avoid space
3079 // wasted on storing tokens for all users. When this option
3080 // is set manually by the user, only then is it stored.
3081 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3088 * Reset a token stored in the preferences (like the watchlist one).
3089 * *Does not* save user's preferences (similarly to setOption()).
3091 * @param string $oname The option name to reset the token in
3092 * @return string|bool New token value, or false if this option is disabled.
3093 * @see getTokenFromOption()
3096 public function resetTokenFromOption( $oname ) {
3097 global $wgHiddenPrefs;
3098 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3102 $token = MWCryptRand
::generateHex( 40 );
3103 $this->setOption( $oname, $token );
3108 * Return a list of the types of user options currently returned by
3109 * User::getOptionKinds().
3111 * Currently, the option kinds are:
3112 * - 'registered' - preferences which are registered in core MediaWiki or
3113 * by extensions using the UserGetDefaultOptions hook.
3114 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3115 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3116 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3117 * be used by user scripts.
3118 * - 'special' - "preferences" that are not accessible via User::getOptions
3119 * or User::setOptions.
3120 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3121 * These are usually legacy options, removed in newer versions.
3123 * The API (and possibly others) use this function to determine the possible
3124 * option types for validation purposes, so make sure to update this when a
3125 * new option kind is added.
3127 * @see User::getOptionKinds
3128 * @return array Option kinds
3130 public static function listOptionKinds() {
3133 'registered-multiselect',
3134 'registered-checkmatrix',
3142 * Return an associative array mapping preferences keys to the kind of a preference they're
3143 * used for. Different kinds are handled differently when setting or reading preferences.
3145 * See User::listOptionKinds for the list of valid option types that can be provided.
3147 * @see User::listOptionKinds
3148 * @param IContextSource $context
3149 * @param array|null $options Assoc. array with options keys to check as keys.
3150 * Defaults to $this->mOptions.
3151 * @return array The key => kind mapping data
3153 public function getOptionKinds( IContextSource
$context, $options = null ) {
3154 $this->loadOptions();
3155 if ( $options === null ) {
3156 $options = $this->mOptions
;
3159 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3160 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3163 // Pull out the "special" options, so they don't get converted as
3164 // multiselect or checkmatrix.
3165 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3166 foreach ( $specialOptions as $name => $value ) {
3167 unset( $prefs[$name] );
3170 // Multiselect and checkmatrix options are stored in the database with
3171 // one key per option, each having a boolean value. Extract those keys.
3172 $multiselectOptions = [];
3173 foreach ( $prefs as $name => $info ) {
3174 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3175 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3176 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3177 $prefix = $info['prefix'] ??
$name;
3179 foreach ( $opts as $value ) {
3180 $multiselectOptions["$prefix$value"] = true;
3183 unset( $prefs[$name] );
3186 $checkmatrixOptions = [];
3187 foreach ( $prefs as $name => $info ) {
3188 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3189 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3190 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3191 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3192 $prefix = $info['prefix'] ??
$name;
3194 foreach ( $columns as $column ) {
3195 foreach ( $rows as $row ) {
3196 $checkmatrixOptions["$prefix$column-$row"] = true;
3200 unset( $prefs[$name] );
3204 // $value is ignored
3205 foreach ( $options as $key => $value ) {
3206 if ( isset( $prefs[$key] ) ) {
3207 $mapping[$key] = 'registered';
3208 } elseif ( isset( $multiselectOptions[$key] ) ) {
3209 $mapping[$key] = 'registered-multiselect';
3210 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3211 $mapping[$key] = 'registered-checkmatrix';
3212 } elseif ( isset( $specialOptions[$key] ) ) {
3213 $mapping[$key] = 'special';
3214 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3215 $mapping[$key] = 'userjs';
3217 $mapping[$key] = 'unused';
3225 * Reset certain (or all) options to the site defaults
3227 * The optional parameter determines which kinds of preferences will be reset.
3228 * Supported values are everything that can be reported by getOptionKinds()
3229 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3231 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3232 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3233 * for backwards-compatibility.
3234 * @param IContextSource|null $context Context source used when $resetKinds
3235 * does not contain 'all', passed to getOptionKinds().
3236 * Defaults to RequestContext::getMain() when null.
3238 public function resetOptions(
3239 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3240 IContextSource
$context = null
3243 $defaultOptions = self
::getDefaultOptions();
3245 if ( !is_array( $resetKinds ) ) {
3246 $resetKinds = [ $resetKinds ];
3249 if ( in_array( 'all', $resetKinds ) ) {
3250 $newOptions = $defaultOptions;
3252 if ( $context === null ) {
3253 $context = RequestContext
::getMain();
3256 $optionKinds = $this->getOptionKinds( $context );
3257 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3260 // Use default values for the options that should be deleted, and
3261 // copy old values for the ones that shouldn't.
3262 foreach ( $this->mOptions
as $key => $value ) {
3263 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3264 if ( array_key_exists( $key, $defaultOptions ) ) {
3265 $newOptions[$key] = $defaultOptions[$key];
3268 $newOptions[$key] = $value;
3273 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3275 $this->mOptions
= $newOptions;
3276 $this->mOptionsLoaded
= true;
3280 * Get the user's preferred date format.
3281 * @return string User's preferred date format
3283 public function getDatePreference() {
3284 // Important migration for old data rows
3285 if ( is_null( $this->mDatePreference
) ) {
3287 $value = $this->getOption( 'date' );
3288 $map = $wgLang->getDatePreferenceMigrationMap();
3289 if ( isset( $map[$value] ) ) {
3290 $value = $map[$value];
3292 $this->mDatePreference
= $value;
3294 return $this->mDatePreference
;
3298 * Determine based on the wiki configuration and the user's options,
3299 * whether this user must be over HTTPS no matter what.
3303 public function requiresHTTPS() {
3304 global $wgSecureLogin;
3305 if ( !$wgSecureLogin ) {
3309 $https = $this->getBoolOption( 'prefershttps' );
3310 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3312 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3319 * Get the user preferred stub threshold
3323 public function getStubThreshold() {
3324 global $wgMaxArticleSize; # Maximum article size, in Kb
3325 $threshold = $this->getIntOption( 'stubthreshold' );
3326 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3327 // If they have set an impossible value, disable the preference
3328 // so we can use the parser cache again.
3335 * Get the permissions this user has.
3336 * @return string[] permission names
3338 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3339 * ->getUserPermissions(..) instead
3342 public function getRights() {
3343 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3347 * Get the list of explicit group memberships this user has.
3348 * The implicit * and user groups are not included.
3350 * @return string[] Array of internal group names (sorted since 1.33)
3352 public function getGroups() {
3354 $this->loadGroups();
3355 return array_keys( $this->mGroupMemberships
);
3359 * Get the list of explicit group memberships this user has, stored as
3360 * UserGroupMembership objects. Implicit groups are not included.
3362 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3365 public function getGroupMemberships() {
3367 $this->loadGroups();
3368 return $this->mGroupMemberships
;
3372 * Get the list of implicit group memberships this user has.
3373 * This includes all explicit groups, plus 'user' if logged in,
3374 * '*' for all accounts, and autopromoted groups
3375 * @param bool $recache Whether to avoid the cache
3376 * @return array Array of String internal group names
3378 public function getEffectiveGroups( $recache = false ) {
3379 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3380 $this->mEffectiveGroups
= array_unique( array_merge(
3381 $this->getGroups(), // explicit groups
3382 $this->getAutomaticGroups( $recache ) // implicit groups
3384 // Avoid PHP 7.1 warning of passing $this by reference
3386 // Hook for additional groups
3387 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3388 // Force reindexation of groups when a hook has unset one of them
3389 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3391 return $this->mEffectiveGroups
;
3395 * Get the list of implicit group memberships this user has.
3396 * This includes 'user' if logged in, '*' for all accounts,
3397 * and autopromoted groups
3398 * @param bool $recache Whether to avoid the cache
3399 * @return array Array of String internal group names
3401 public function getAutomaticGroups( $recache = false ) {
3402 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3403 $this->mImplicitGroups
= [ '*' ];
3404 if ( $this->getId() ) {
3405 $this->mImplicitGroups
[] = 'user';
3407 $this->mImplicitGroups
= array_unique( array_merge(
3408 $this->mImplicitGroups
,
3409 Autopromote
::getAutopromoteGroups( $this )
3413 // Assure data consistency with rights/groups,
3414 // as getEffectiveGroups() depends on this function
3415 $this->mEffectiveGroups
= null;
3418 return $this->mImplicitGroups
;
3422 * Returns the groups the user has belonged to.
3424 * The user may still belong to the returned groups. Compare with getGroups().
3426 * The function will not return groups the user had belonged to before MW 1.17
3428 * @return array Names of the groups the user has belonged to.
3430 public function getFormerGroups() {
3433 if ( is_null( $this->mFormerGroups
) ) {
3434 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3435 ?
wfGetDB( DB_MASTER
)
3436 : wfGetDB( DB_REPLICA
);
3437 $res = $db->select( 'user_former_groups',
3439 [ 'ufg_user' => $this->mId
],
3441 $this->mFormerGroups
= [];
3442 foreach ( $res as $row ) {
3443 $this->mFormerGroups
[] = $row->ufg_group
;
3447 return $this->mFormerGroups
;
3451 * Get the user's edit count.
3452 * @return int|null Null for anonymous users
3454 public function getEditCount() {
3455 if ( !$this->getId() ) {
3459 if ( $this->mEditCount
=== null ) {
3460 /* Populate the count, if it has not been populated yet */
3461 $dbr = wfGetDB( DB_REPLICA
);
3462 // check if the user_editcount field has been initialized
3463 $count = $dbr->selectField(
3464 'user', 'user_editcount',
3465 [ 'user_id' => $this->mId
],
3469 if ( $count === null ) {
3470 // it has not been initialized. do so.
3471 $count = $this->initEditCountInternal( $dbr );
3473 $this->mEditCount
= $count;
3475 return (int)$this->mEditCount
;
3479 * Add the user to the given group. This takes immediate effect.
3480 * If the user is already in the group, the expiry time will be updated to the new
3481 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3484 * @param string $group Name of the group to add
3485 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3486 * wfTimestamp(), or null if the group assignment should not expire
3489 public function addGroup( $group, $expiry = null ) {
3491 $this->loadGroups();
3494 $expiry = wfTimestamp( TS_MW
, $expiry );
3497 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3501 // create the new UserGroupMembership and put it in the DB
3502 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3503 if ( !$ugm->insert( true ) ) {
3507 $this->mGroupMemberships
[$group] = $ugm;
3509 // Refresh the groups caches, and clear the rights cache so it will be
3510 // refreshed on the next call to $this->getRights().
3511 $this->getEffectiveGroups( true );
3512 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3513 $this->invalidateCache();
3519 * Remove the user from the given group.
3520 * This takes immediate effect.
3521 * @param string $group Name of the group to remove
3524 public function removeGroup( $group ) {
3527 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3531 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3532 // delete the membership entry
3533 if ( !$ugm ||
!$ugm->delete() ) {
3537 $this->loadGroups();
3538 unset( $this->mGroupMemberships
[$group] );
3540 // Refresh the groups caches, and clear the rights cache so it will be
3541 // refreshed on the next call to $this->getRights().
3542 $this->getEffectiveGroups( true );
3543 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3544 $this->invalidateCache();
3550 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3551 * only this new name and not the old isLoggedIn() variant.
3553 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3554 * anonymous or has no local account (which can happen when importing). This is equivalent to
3555 * getId() != 0 and is provided for code readability.
3558 public function isRegistered() {
3559 return $this->getId() != 0;
3563 * Get whether the user is logged in
3566 public function isLoggedIn() {
3567 return $this->isRegistered();
3571 * Get whether the user is anonymous
3574 public function isAnon() {
3575 return !$this->isRegistered();
3579 * @return bool Whether this user is flagged as being a bot role account
3582 public function isBot() {
3583 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3588 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3594 * Check if user is allowed to access a feature / make an action
3596 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3597 * ->getPermissionManager()->userHasAnyRights(...) instead
3599 * @param string $permissions,... Permissions to test
3600 * @return bool True if user is allowed to perform *any* of the given actions
3601 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3603 public function isAllowedAny() {
3604 return MediaWikiServices
::getInstance()
3605 ->getPermissionManager()
3606 ->userHasAnyRight( $this, ...func_get_args() );
3610 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3611 * ->getPermissionManager()->userHasAllRights(...) instead
3612 * @param string $permissions,... Permissions to test
3613 * @return bool True if the user is allowed to perform *all* of the given actions
3614 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3616 public function isAllowedAll() {
3617 return MediaWikiServices
::getInstance()
3618 ->getPermissionManager()
3619 ->userHasAllRights( $this, ...func_get_args() );
3623 * Internal mechanics of testing a permission
3625 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3626 * ->getPermissionManager()->userHasRight(...) instead
3628 * @param string $action
3632 public function isAllowed( $action = '' ) {
3633 return MediaWikiServices
::getInstance()->getPermissionManager()
3634 ->userHasRight( $this, $action );
3638 * Check whether to enable recent changes patrol features for this user
3639 * @return bool True or false
3641 public function useRCPatrol() {
3642 global $wgUseRCPatrol;
3643 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3647 * Check whether to enable new pages patrol features for this user
3648 * @return bool True or false
3650 public function useNPPatrol() {
3651 global $wgUseRCPatrol, $wgUseNPPatrol;
3653 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3654 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3659 * Check whether to enable new files patrol features for this user
3660 * @return bool True or false
3662 public function useFilePatrol() {
3663 global $wgUseRCPatrol, $wgUseFilePatrol;
3665 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3666 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3671 * Get the WebRequest object to use with this object
3673 * @return WebRequest
3675 public function getRequest() {
3676 if ( $this->mRequest
) {
3677 return $this->mRequest
;
3685 * Check the watched status of an article.
3686 * @since 1.22 $checkRights parameter added
3687 * @param Title $title Title of the article to look at
3688 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3689 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3692 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3693 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3694 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3701 * @since 1.22 $checkRights parameter added
3702 * @param Title $title Title of the article to look at
3703 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3704 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3706 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3707 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3708 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3710 [ $title->getSubjectPage(), $title->getTalkPage() ]
3713 $this->invalidateCache();
3717 * Stop watching an article.
3718 * @since 1.22 $checkRights parameter added
3719 * @param Title $title Title of the article to look at
3720 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3721 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3723 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3724 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3725 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3726 $store->removeWatch( $this, $title->getSubjectPage() );
3727 $store->removeWatch( $this, $title->getTalkPage() );
3729 $this->invalidateCache();
3733 * Clear the user's notification timestamp for the given title.
3734 * If e-notif e-mails are on, they will receive notification mails on
3735 * the next change of the page if it's watched etc.
3736 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3737 * @param Title &$title Title of the article to look at
3738 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3740 public function clearNotification( &$title, $oldid = 0 ) {
3741 global $wgUseEnotif, $wgShowUpdatedMarker;
3743 // Do nothing if the database is locked to writes
3744 if ( wfReadOnly() ) {
3748 // Do nothing if not allowed to edit the watchlist
3749 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3753 // If we're working on user's talk page, we should update the talk page message indicator
3754 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3755 // Avoid PHP 7.1 warning of passing $this by reference
3757 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3761 // Try to update the DB post-send and only if needed...
3762 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3763 if ( !$this->getNewtalk() ) {
3764 return; // no notifications to clear
3767 // Delete the last notifications (they stack up)
3768 $this->setNewtalk( false );
3770 // If there is a new, unseen, revision, use its timestamp
3772 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3775 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3780 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3784 if ( $this->isAnon() ) {
3785 // Nothing else to do...
3789 // Only update the timestamp if the page is being watched.
3790 // The query to find out if it is watched is cached both in memcached and per-invocation,
3791 // and when it does have to be executed, it can be on a replica DB
3792 // If this is the user's newtalk page, we always update the timestamp
3794 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3798 MediaWikiServices
::getInstance()->getWatchedItemStore()
3799 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3803 * Resets all of the given user's page-change notification timestamps.
3804 * If e-notif e-mails are on, they will receive notification mails on
3805 * the next change of any watched page.
3806 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3808 public function clearAllNotifications() {
3809 global $wgUseEnotif, $wgShowUpdatedMarker;
3810 // Do nothing if not allowed to edit the watchlist
3811 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3815 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3816 $this->setNewtalk( false );
3820 $id = $this->getId();
3825 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3826 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3828 // We also need to clear here the "you have new message" notification for the own
3829 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3833 * Compute experienced level based on edit count and registration date.
3835 * @return string 'newcomer', 'learner', or 'experienced'
3837 public function getExperienceLevel() {
3838 global $wgLearnerEdits,
3839 $wgExperiencedUserEdits,
3840 $wgLearnerMemberSince,
3841 $wgExperiencedUserMemberSince;
3843 if ( $this->isAnon() ) {
3847 $editCount = $this->getEditCount();
3848 $registration = $this->getRegistration();
3850 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3851 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3853 if ( $editCount < $wgLearnerEdits ||
3854 $registration > $learnerRegistration ) {
3858 if ( $editCount > $wgExperiencedUserEdits &&
3859 $registration <= $experiencedRegistration
3861 return 'experienced';
3868 * Persist this user's session (e.g. set cookies)
3870 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3872 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3873 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3875 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3877 if ( $this->mId
== 0 ) {
3881 $session = $this->getRequest()->getSession();
3882 if ( $request && $session->getRequest() !== $request ) {
3883 $session = $session->sessionWithRequest( $request );
3885 $delay = $session->delaySave();
3887 if ( !$session->getUser()->equals( $this ) ) {
3888 if ( !$session->canSetUser() ) {
3889 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3890 ->warning( __METHOD__
.
3891 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3895 $session->setUser( $this );
3898 $session->setRememberUser( $rememberMe );
3899 if ( $secure !== null ) {
3900 $session->setForceHTTPS( $secure );
3903 $session->persist();
3905 ScopedCallback
::consume( $delay );
3909 * Log this user out.
3911 public function logout() {
3912 // Avoid PHP 7.1 warning of passing $this by reference
3914 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3920 * Clear the user's session, and reset the instance cache.
3923 public function doLogout() {
3924 $session = $this->getRequest()->getSession();
3925 if ( !$session->canSetUser() ) {
3926 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3927 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3928 $error = 'immutable';
3929 } elseif ( !$session->getUser()->equals( $this ) ) {
3930 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3931 ->warning( __METHOD__
.
3932 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3934 // But we still may as well make this user object anon
3935 $this->clearInstanceCache( 'defaults' );
3936 $error = 'wronguser';
3938 $this->clearInstanceCache( 'defaults' );
3939 $delay = $session->delaySave();
3940 $session->unpersist(); // Clear cookies (T127436)
3941 $session->setLoggedOutTimestamp( time() );
3942 $session->setUser( new User
);
3943 $session->set( 'wsUserID', 0 ); // Other code expects this
3944 $session->resetAllTokens();
3945 ScopedCallback
::consume( $delay );
3948 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3949 'event' => 'logout',
3950 'successful' => $error === false,
3951 'status' => $error ?
: 'success',
3956 * Save this user's settings into the database.
3957 * @todo Only rarely do all these fields need to be set!
3959 public function saveSettings() {
3960 if ( wfReadOnly() ) {
3961 // @TODO: caller should deal with this instead!
3962 // This should really just be an exception.
3963 MWExceptionHandler
::logException( new DBExpectedError(
3965 "Could not update user with ID '{$this->mId}'; DB is read-only."
3971 if ( $this->mId
== 0 ) {
3975 // Get a new user_touched that is higher than the old one.
3976 // This will be used for a CAS check as a last-resort safety
3977 // check against race conditions and replica DB lag.
3978 $newTouched = $this->newTouchedTimestamp();
3980 $dbw = wfGetDB( DB_MASTER
);
3981 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3982 global $wgActorTableSchemaMigrationStage;
3984 $dbw->update( 'user',
3986 'user_name' => $this->mName
,
3987 'user_real_name' => $this->mRealName
,
3988 'user_email' => $this->mEmail
,
3989 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3990 'user_touched' => $dbw->timestamp( $newTouched ),
3991 'user_token' => strval( $this->mToken
),
3992 'user_email_token' => $this->mEmailToken
,
3993 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3994 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3995 'user_id' => $this->mId
,
3999 if ( !$dbw->affectedRows() ) {
4000 // Maybe the problem was a missed cache update; clear it to be safe
4001 $this->clearSharedCache( 'refresh' );
4002 // User was changed in the meantime or loaded with stale data
4003 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4004 LoggerFactory
::getInstance( 'preferences' )->warning(
4005 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4006 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4008 throw new MWException( "CAS update failed on user_touched. " .
4009 "The version of the user to be saved is older than the current version."
4013 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4016 [ 'actor_name' => $this->mName
],
4017 [ 'actor_user' => $this->mId
],
4023 $this->mTouched
= $newTouched;
4024 $this->saveOptions();
4026 Hooks
::run( 'UserSaveSettings', [ $this ] );
4027 $this->clearSharedCache( 'changed' );
4028 $this->getUserPage()->purgeSquid();
4032 * If only this user's username is known, and it exists, return the user ID.
4034 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4037 public function idForName( $flags = 0 ) {
4038 $s = trim( $this->getName() );
4043 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4044 ?
wfGetDB( DB_MASTER
)
4045 : wfGetDB( DB_REPLICA
);
4047 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4048 ?
[ 'LOCK IN SHARE MODE' ]
4051 $id = $db->selectField( 'user',
4052 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4058 * Add a user to the database, return the user object
4060 * @param string $name Username to add
4061 * @param array $params Array of Strings Non-default parameters to save to
4062 * the database as user_* fields:
4063 * - email: The user's email address.
4064 * - email_authenticated: The email authentication timestamp.
4065 * - real_name: The user's real name.
4066 * - options: An associative array of non-default options.
4067 * - token: Random authentication token. Do not set.
4068 * - registration: Registration timestamp. Do not set.
4070 * @return User|null User object, or null if the username already exists.
4072 public static function createNew( $name, $params = [] ) {
4073 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4074 if ( isset( $params[$field] ) ) {
4075 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4076 unset( $params[$field] );
4082 $user->setToken(); // init token
4083 if ( isset( $params['options'] ) ) {
4084 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4085 unset( $params['options'] );
4087 $dbw = wfGetDB( DB_MASTER
);
4089 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4092 'user_name' => $name,
4093 'user_password' => $noPass,
4094 'user_newpassword' => $noPass,
4095 'user_email' => $user->mEmail
,
4096 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4097 'user_real_name' => $user->mRealName
,
4098 'user_token' => strval( $user->mToken
),
4099 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4100 'user_editcount' => 0,
4101 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4103 foreach ( $params as $name => $value ) {
4104 $fields["user_$name"] = $value;
4107 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4108 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4109 if ( $dbw->affectedRows() ) {
4110 $newUser = self
::newFromId( $dbw->insertId() );
4111 $newUser->mName
= $fields['user_name'];
4112 $newUser->updateActorId( $dbw );
4113 // Load the user from master to avoid replica lag
4114 $newUser->load( self
::READ_LATEST
);
4123 * Add this existing user object to the database. If the user already
4124 * exists, a fatal status object is returned, and the user object is
4125 * initialised with the data from the database.
4127 * Previously, this function generated a DB error due to a key conflict
4128 * if the user already existed. Many extension callers use this function
4129 * in code along the lines of:
4131 * $user = User::newFromName( $name );
4132 * if ( !$user->isLoggedIn() ) {
4133 * $user->addToDatabase();
4135 * // do something with $user...
4137 * However, this was vulnerable to a race condition (T18020). By
4138 * initialising the user object if the user exists, we aim to support this
4139 * calling sequence as far as possible.
4141 * Note that if the user exists, this function will acquire a write lock,
4142 * so it is still advisable to make the call conditional on isLoggedIn(),
4143 * and to commit the transaction after calling.
4145 * @throws MWException
4148 public function addToDatabase() {
4150 if ( !$this->mToken
) {
4151 $this->setToken(); // init token
4154 if ( !is_string( $this->mName
) ) {
4155 throw new RuntimeException( "User name field is not set." );
4158 $this->mTouched
= $this->newTouchedTimestamp();
4160 $dbw = wfGetDB( DB_MASTER
);
4161 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4162 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4163 $dbw->insert( 'user',
4165 'user_name' => $this->mName
,
4166 'user_password' => $noPass,
4167 'user_newpassword' => $noPass,
4168 'user_email' => $this->mEmail
,
4169 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4170 'user_real_name' => $this->mRealName
,
4171 'user_token' => strval( $this->mToken
),
4172 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4173 'user_editcount' => 0,
4174 'user_touched' => $dbw->timestamp( $this->mTouched
),
4178 if ( !$dbw->affectedRows() ) {
4179 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4180 $this->mId
= $dbw->selectField(
4183 [ 'user_name' => $this->mName
],
4185 [ 'LOCK IN SHARE MODE' ]
4188 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4192 throw new MWException( $fname . ": hit a key conflict attempting " .
4193 "to insert user '{$this->mName}' row, but it was not present in select!" );
4195 return Status
::newFatal( 'userexists' );
4197 $this->mId
= $dbw->insertId();
4198 self
::$idCacheByName[$this->mName
] = $this->mId
;
4199 $this->updateActorId( $dbw );
4201 return Status
::newGood();
4203 if ( !$status->isGood() ) {
4207 // Clear instance cache other than user table data and actor, which is already accurate
4208 $this->clearInstanceCache();
4210 $this->saveOptions();
4211 return Status
::newGood();
4215 * Update the actor ID after an insert
4216 * @param IDatabase $dbw Writable database handle
4218 private function updateActorId( IDatabase
$dbw ) {
4219 global $wgActorTableSchemaMigrationStage;
4221 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4224 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4227 $this->mActorId
= (int)$dbw->insertId();
4232 * If this user is logged-in and blocked,
4233 * block any IP address they've successfully logged in from.
4234 * @return bool A block was spread
4236 public function spreadAnyEditBlock() {
4237 if ( $this->isLoggedIn() && $this->getBlock() ) {
4238 return $this->spreadBlock();
4245 * If this (non-anonymous) user is blocked,
4246 * block the IP address they've successfully logged in from.
4247 * @return bool A block was spread
4249 protected function spreadBlock() {
4250 wfDebug( __METHOD__
. "()\n" );
4252 if ( $this->mId
== 0 ) {
4256 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4257 if ( !$userblock ) {
4261 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4265 * Get whether the user is explicitly blocked from account creation.
4266 * @return bool|AbstractBlock
4268 public function isBlockedFromCreateAccount() {
4269 $this->getBlockedStatus();
4270 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4271 return $this->mBlock
;
4274 # T15611: if the IP address the user is trying to create an account from is
4275 # blocked with createaccount disabled, prevent new account creation there even
4276 # when the user is logged in
4277 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4278 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4279 null, $this->getRequest()->getIP()
4282 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4283 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4284 ?
$this->mBlockedFromCreateAccount
4289 * Get whether the user is blocked from using Special:Emailuser.
4292 public function isBlockedFromEmailuser() {
4293 $this->getBlockedStatus();
4294 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4298 * Get whether the user is blocked from using Special:Upload
4303 public function isBlockedFromUpload() {
4304 $this->getBlockedStatus();
4305 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4309 * Get whether the user is allowed to create an account.
4312 public function isAllowedToCreateAccount() {
4313 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4317 * Get this user's personal page title.
4319 * @return Title User's personal page title
4321 public function getUserPage() {
4322 return Title
::makeTitle( NS_USER
, $this->getName() );
4326 * Get this user's talk page title.
4328 * @return Title User's talk page title
4330 public function getTalkPage() {
4331 $title = $this->getUserPage();
4332 return $title->getTalkPage();
4336 * Determine whether the user is a newbie. Newbies are either
4337 * anonymous IPs, or the most recently created accounts.
4340 public function isNewbie() {
4341 return !$this->isAllowed( 'autoconfirmed' );
4345 * Check to see if the given clear-text password is one of the accepted passwords
4346 * @deprecated since 1.27, use AuthManager instead
4347 * @param string $password User password
4348 * @return bool True if the given password is correct, otherwise False
4350 public function checkPassword( $password ) {
4351 wfDeprecated( __METHOD__
, '1.27' );
4353 $manager = AuthManager
::singleton();
4354 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4355 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4357 'username' => $this->getName(),
4358 'password' => $password,
4361 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4362 switch ( $res->status
) {
4363 case AuthenticationResponse
::PASS
:
4365 case AuthenticationResponse
::FAIL
:
4366 // Hope it's not a PreAuthenticationProvider that failed...
4367 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4368 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4371 throw new BadMethodCallException(
4372 'AuthManager returned a response unsupported by ' . __METHOD__
4378 * Check if the given clear-text password matches the temporary password
4379 * sent by e-mail for password reset operations.
4381 * @deprecated since 1.27, use AuthManager instead
4382 * @param string $plaintext
4383 * @return bool True if matches, false otherwise
4385 public function checkTemporaryPassword( $plaintext ) {
4386 wfDeprecated( __METHOD__
, '1.27' );
4387 // Can't check the temporary password individually.
4388 return $this->checkPassword( $plaintext );
4392 * Initialize (if necessary) and return a session token value
4393 * which can be used in edit forms to show that the user's
4394 * login credentials aren't being hijacked with a foreign form
4398 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4399 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4400 * @return MediaWiki\Session\Token The new edit token
4402 public function getEditTokenObject( $salt = '', $request = null ) {
4403 if ( $this->isAnon() ) {
4404 return new LoggedOutEditToken();
4408 $request = $this->getRequest();
4410 return $request->getSession()->getToken( $salt );
4414 * Initialize (if necessary) and return a session token value
4415 * which can be used in edit forms to show that the user's
4416 * login credentials aren't being hijacked with a foreign form
4419 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4422 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4423 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4424 * @return string The new edit token
4426 public function getEditToken( $salt = '', $request = null ) {
4427 return $this->getEditTokenObject( $salt, $request )->toString();
4431 * Check given value against the token value stored in the session.
4432 * A match should confirm that the form was submitted from the
4433 * user's own login session, not a form submission from a third-party
4436 * @param string $val Input value to compare
4437 * @param string|array $salt Optional function-specific data for hashing
4438 * @param WebRequest|null $request Object to use or null to use $wgRequest
4439 * @param int|null $maxage Fail tokens older than this, in seconds
4440 * @return bool Whether the token matches
4442 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4443 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4447 * Check given value against the token value stored in the session,
4448 * ignoring the suffix.
4450 * @param string $val Input value to compare
4451 * @param string|array $salt Optional function-specific data for hashing
4452 * @param WebRequest|null $request Object to use or null to use $wgRequest
4453 * @param int|null $maxage Fail tokens older than this, in seconds
4454 * @return bool Whether the token matches
4456 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4457 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4458 return $this->matchEditToken( $val, $salt, $request, $maxage );
4462 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4463 * mail to the user's given address.
4465 * @param string $type Message to send, either "created", "changed" or "set"
4468 public function sendConfirmationMail( $type = 'created' ) {
4470 $expiration = null; // gets passed-by-ref and defined in next line.
4471 $token = $this->confirmationToken( $expiration );
4472 $url = $this->confirmationTokenUrl( $token );
4473 $invalidateURL = $this->invalidationTokenUrl( $token );
4474 $this->saveSettings();
4476 if ( $type == 'created' ||
$type === false ) {
4477 $message = 'confirmemail_body';
4479 } elseif ( $type === true ) {
4480 $message = 'confirmemail_body_changed';
4483 // Messages: confirmemail_body_changed, confirmemail_body_set
4484 $message = 'confirmemail_body_' . $type;
4488 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4489 'body' => wfMessage( $message,
4490 $this->getRequest()->getIP(),
4493 $wgLang->userTimeAndDate( $expiration, $this ),
4495 $wgLang->userDate( $expiration, $this ),
4496 $wgLang->userTime( $expiration, $this ) )->text(),
4502 'ip' => $this->getRequest()->getIP(),
4503 'confirmURL' => $url,
4504 'invalidateURL' => $invalidateURL,
4505 'expiration' => $expiration
4508 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4509 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4513 * Send an e-mail to this user's account. Does not check for
4514 * confirmed status or validity.
4516 * @param string $subject Message subject
4517 * @param string $body Message body
4518 * @param User|null $from Optional sending user; if unspecified, default
4519 * $wgPasswordSender will be used.
4520 * @param MailAddress|null $replyto Reply-To address
4523 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4524 global $wgPasswordSender;
4526 if ( $from instanceof User
) {
4527 $sender = MailAddress
::newFromUser( $from );
4529 $sender = new MailAddress( $wgPasswordSender,
4530 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4532 $to = MailAddress
::newFromUser( $this );
4534 return UserMailer
::send( $to, $sender, $subject, $body, [
4535 'replyTo' => $replyto,
4540 * Generate, store, and return a new e-mail confirmation code.
4541 * A hash (unsalted, since it's used as a key) is stored.
4543 * @note Call saveSettings() after calling this function to commit
4544 * this change to the database.
4546 * @param string &$expiration Accepts the expiration time
4547 * @return string New token
4549 protected function confirmationToken( &$expiration ) {
4550 global $wgUserEmailConfirmationTokenExpiry;
4552 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4553 $expiration = wfTimestamp( TS_MW
, $expires );
4555 $token = MWCryptRand
::generateHex( 32 );
4556 $hash = md5( $token );
4557 $this->mEmailToken
= $hash;
4558 $this->mEmailTokenExpires
= $expiration;
4563 * Return a URL the user can use to confirm their email address.
4564 * @param string $token Accepts the email confirmation token
4565 * @return string New token URL
4567 protected function confirmationTokenUrl( $token ) {
4568 return $this->getTokenUrl( 'ConfirmEmail', $token );
4572 * Return a URL the user can use to invalidate their email address.
4573 * @param string $token Accepts the email confirmation token
4574 * @return string New token URL
4576 protected function invalidationTokenUrl( $token ) {
4577 return $this->getTokenUrl( 'InvalidateEmail', $token );
4581 * Internal function to format the e-mail validation/invalidation URLs.
4582 * This uses a quickie hack to use the
4583 * hardcoded English names of the Special: pages, for ASCII safety.
4585 * @note Since these URLs get dropped directly into emails, using the
4586 * short English names avoids insanely long URL-encoded links, which
4587 * also sometimes can get corrupted in some browsers/mailers
4588 * (T8957 with Gmail and Internet Explorer).
4590 * @param string $page Special page
4591 * @param string $token
4592 * @return string Formatted URL
4594 protected function getTokenUrl( $page, $token ) {
4595 // Hack to bypass localization of 'Special:'
4596 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4597 return $title->getCanonicalURL();
4601 * Mark the e-mail address confirmed.
4603 * @note Call saveSettings() after calling this function to commit the change.
4607 public function confirmEmail() {
4608 // Check if it's already confirmed, so we don't touch the database
4609 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4610 if ( !$this->isEmailConfirmed() ) {
4611 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4612 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4618 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4619 * address if it was already confirmed.
4621 * @note Call saveSettings() after calling this function to commit the change.
4622 * @return bool Returns true
4624 public function invalidateEmail() {
4626 $this->mEmailToken
= null;
4627 $this->mEmailTokenExpires
= null;
4628 $this->setEmailAuthenticationTimestamp( null );
4630 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4635 * Set the e-mail authentication timestamp.
4636 * @param string $timestamp TS_MW timestamp
4638 public function setEmailAuthenticationTimestamp( $timestamp ) {
4640 $this->mEmailAuthenticated
= $timestamp;
4641 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4645 * Is this user allowed to send e-mails within limits of current
4646 * site configuration?
4649 public function canSendEmail() {
4650 global $wgEnableEmail, $wgEnableUserEmail;
4651 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4654 $canSend = $this->isEmailConfirmed();
4655 // Avoid PHP 7.1 warning of passing $this by reference
4657 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4662 * Is this user allowed to receive e-mails within limits of current
4663 * site configuration?
4666 public function canReceiveEmail() {
4667 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4671 * Is this user's e-mail address valid-looking and confirmed within
4672 * limits of the current site configuration?
4674 * @note If $wgEmailAuthentication is on, this may require the user to have
4675 * confirmed their address by returning a code or using a password
4676 * sent to the address from the wiki.
4680 public function isEmailConfirmed() {
4681 global $wgEmailAuthentication;
4683 // Avoid PHP 7.1 warning of passing $this by reference
4686 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4687 if ( $this->isAnon() ) {
4690 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4693 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4703 * Check whether there is an outstanding request for e-mail confirmation.
4706 public function isEmailConfirmationPending() {
4707 global $wgEmailAuthentication;
4708 return $wgEmailAuthentication &&
4709 !$this->isEmailConfirmed() &&
4710 $this->mEmailToken
&&
4711 $this->mEmailTokenExpires
> wfTimestamp();
4715 * Get the timestamp of account creation.
4717 * @return string|bool|null Timestamp of account creation, false for
4718 * non-existent/anonymous user accounts, or null if existing account
4719 * but information is not in database.
4721 public function getRegistration() {
4722 if ( $this->isAnon() ) {
4726 return $this->mRegistration
;
4730 * Get the timestamp of the first edit
4732 * @return string|bool Timestamp of first edit, or false for
4733 * non-existent/anonymous user accounts.
4735 public function getFirstEditTimestamp() {
4736 return $this->getEditTimestamp( true );
4740 * Get the timestamp of the latest edit
4743 * @return string|bool Timestamp of first edit, or false for
4744 * non-existent/anonymous user accounts.
4746 public function getLatestEditTimestamp() {
4747 return $this->getEditTimestamp( false );
4751 * Get the timestamp of the first or latest edit
4753 * @param bool $first True for the first edit, false for the latest one
4754 * @return string|bool Timestamp of first or latest edit, or false for
4755 * non-existent/anonymous user accounts.
4757 private function getEditTimestamp( $first ) {
4758 if ( $this->getId() == 0 ) {
4759 return false; // anons
4761 $dbr = wfGetDB( DB_REPLICA
);
4762 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4763 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4764 ?
'revactor_timestamp' : 'rev_timestamp';
4765 $sortOrder = $first ?
'ASC' : 'DESC';
4766 $time = $dbr->selectField(
4767 [ 'revision' ] +
$actorWhere['tables'],
4769 [ $actorWhere['conds'] ],
4771 [ 'ORDER BY' => "$tsField $sortOrder" ],
4772 $actorWhere['joins']
4775 return false; // no edits
4777 return wfTimestamp( TS_MW
, $time );
4781 * Get the permissions associated with a given list of groups
4783 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4784 * ->getGroupPermissions() instead
4786 * @param array $groups Array of Strings List of internal group names
4787 * @return array Array of Strings List of permission key names for given groups combined
4789 public static function getGroupPermissions( $groups ) {
4790 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4794 * Get all the groups who have a given permission
4796 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4797 * ->getGroupsWithPermission() instead
4799 * @param string $role Role to check
4800 * @return array Array of Strings List of internal group names with the given permission
4802 public static function getGroupsWithPermission( $role ) {
4803 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4807 * Check, if the given group has the given permission
4809 * If you're wanting to check whether all users have a permission, use
4810 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4813 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4814 * ->groupHasPermission(..) instead
4817 * @param string $group Group to check
4818 * @param string $role Role to check
4821 public static function groupHasPermission( $group, $role ) {
4822 return MediaWikiServices
::getInstance()->getPermissionManager()
4823 ->groupHasPermission( $group, $role );
4827 * Check if all users may be assumed to have the given permission
4829 * We generally assume so if the right is granted to '*' and isn't revoked
4830 * on any group. It doesn't attempt to take grants or other extension
4831 * limitations on rights into account in the general case, though, as that
4832 * would require it to always return false and defeat the purpose.
4833 * Specifically, session-based rights restrictions (such as OAuth or bot
4834 * passwords) are applied based on the current session.
4836 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4837 * ->isEveryoneAllowed() instead
4839 * @param string $right Right to check
4844 public static function isEveryoneAllowed( $right ) {
4845 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4849 * Return the set of defined explicit groups.
4850 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4851 * are not included, as they are defined automatically, not in the database.
4852 * @return array Array of internal group names
4854 public static function getAllGroups() {
4855 global $wgGroupPermissions, $wgRevokePermissions;
4856 return array_values( array_diff(
4857 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4858 self
::getImplicitGroups()
4863 * Get a list of all available permissions.
4865 * @deprecated since 1.34, use PermissionManager::getAllPermissions() instead
4867 * @return string[] Array of permission names
4869 public static function getAllRights() {
4870 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4874 * Get a list of implicit groups
4875 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4877 * @return array Array of Strings Array of internal group names
4879 public static function getImplicitGroups() {
4880 global $wgImplicitGroups;
4881 return $wgImplicitGroups;
4885 * Returns an array of the groups that a particular group can add/remove.
4887 * @param string $group The group to check for whether it can add/remove
4888 * @return array [ 'add' => [ addablegroups ],
4889 * 'remove' => [ removablegroups ],
4890 * 'add-self' => [ addablegroups to self ],
4891 * 'remove-self' => [ removable groups from self ] ]
4893 public static function changeableByGroup( $group ) {
4894 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4903 if ( empty( $wgAddGroups[$group] ) ) {
4904 // Don't add anything to $groups
4905 } elseif ( $wgAddGroups[$group] === true ) {
4906 // You get everything
4907 $groups['add'] = self
::getAllGroups();
4908 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4909 $groups['add'] = $wgAddGroups[$group];
4912 // Same thing for remove
4913 if ( empty( $wgRemoveGroups[$group] ) ) {
4915 } elseif ( $wgRemoveGroups[$group] === true ) {
4916 $groups['remove'] = self
::getAllGroups();
4917 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4918 $groups['remove'] = $wgRemoveGroups[$group];
4921 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4922 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4923 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4924 if ( is_int( $key ) ) {
4925 $wgGroupsAddToSelf['user'][] = $value;
4930 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4931 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4932 if ( is_int( $key ) ) {
4933 $wgGroupsRemoveFromSelf['user'][] = $value;
4938 // Now figure out what groups the user can add to him/herself
4939 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4941 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4942 // No idea WHY this would be used, but it's there
4943 $groups['add-self'] = self
::getAllGroups();
4944 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4945 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4948 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4950 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4951 $groups['remove-self'] = self
::getAllGroups();
4952 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4953 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4960 * Returns an array of groups that this user can add and remove
4961 * @return array [ 'add' => [ addablegroups ],
4962 * 'remove' => [ removablegroups ],
4963 * 'add-self' => [ addablegroups to self ],
4964 * 'remove-self' => [ removable groups from self ] ]
4966 public function changeableGroups() {
4967 if ( $this->isAllowed( 'userrights' ) ) {
4968 // This group gives the right to modify everything (reverse-
4969 // compatibility with old "userrights lets you change
4971 // Using array_merge to make the groups reindexed
4972 $all = array_merge( self
::getAllGroups() );
4981 // Okay, it's not so simple, we will have to go through the arrays
4988 $addergroups = $this->getEffectiveGroups();
4990 foreach ( $addergroups as $addergroup ) {
4991 $groups = array_merge_recursive(
4992 $groups, $this->changeableByGroup( $addergroup )
4994 $groups['add'] = array_unique( $groups['add'] );
4995 $groups['remove'] = array_unique( $groups['remove'] );
4996 $groups['add-self'] = array_unique( $groups['add-self'] );
4997 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5003 * Schedule a deferred update to update the user's edit count
5005 public function incEditCount() {
5006 if ( $this->isAnon() ) {
5010 DeferredUpdates
::addUpdate(
5011 new UserEditCountUpdate( $this, 1 ),
5012 DeferredUpdates
::POSTSEND
5017 * This method should not be called outside User/UserEditCountUpdate
5021 public function setEditCountInternal( $count ) {
5022 $this->mEditCount
= $count;
5026 * Initialize user_editcount from data out of the revision table
5028 * @internal This method should not be called outside User/UserEditCountUpdate
5029 * @param IDatabase $dbr Replica database
5030 * @return int Number of edits
5032 public function initEditCountInternal( IDatabase
$dbr ) {
5033 // Pull from a replica DB to be less cruel to servers
5034 // Accuracy isn't the point anyway here
5035 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5036 $count = (int)$dbr->selectField(
5037 [ 'revision' ] +
$actorWhere['tables'],
5039 [ $actorWhere['conds'] ],
5042 $actorWhere['joins']
5045 $dbw = wfGetDB( DB_MASTER
);
5048 [ 'user_editcount' => $count ],
5050 'user_id' => $this->getId(),
5051 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5060 * Get the description of a given right
5063 * @param string $right Right to query
5064 * @return string Localized description of the right
5066 public static function getRightDescription( $right ) {
5067 $key = "right-$right";
5068 $msg = wfMessage( $key );
5069 return $msg->isDisabled() ?
$right : $msg->text();
5073 * Get the name of a given grant
5076 * @param string $grant Grant to query
5077 * @return string Localized name of the grant
5079 public static function getGrantName( $grant ) {
5080 $key = "grant-$grant";
5081 $msg = wfMessage( $key );
5082 return $msg->isDisabled() ?
$grant : $msg->text();
5086 * Add a newuser log entry for this user.
5087 * Before 1.19 the return value was always true.
5089 * @deprecated since 1.27, AuthManager handles logging
5090 * @param string|bool $action Account creation type.
5091 * - String, one of the following values:
5092 * - 'create' for an anonymous user creating an account for himself.
5093 * This will force the action's performer to be the created user itself,
5094 * no matter the value of $wgUser
5095 * - 'create2' for a logged in user creating an account for someone else
5096 * - 'byemail' when the created user will receive its password by e-mail
5097 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5098 * - Boolean means whether the account was created by e-mail (deprecated):
5099 * - true will be converted to 'byemail'
5100 * - false will be converted to 'create' if this object is the same as
5101 * $wgUser and to 'create2' otherwise
5102 * @param string $reason User supplied reason
5105 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5106 return true; // disabled
5110 * Add an autocreate newuser log entry for this user
5111 * Used by things like CentralAuth and perhaps other authplugins.
5112 * Consider calling addNewUserLogEntry() directly instead.
5114 * @deprecated since 1.27, AuthManager handles logging
5117 public function addNewUserLogEntryAutoCreate() {
5118 wfDeprecated( __METHOD__
, '1.27' );
5119 $this->addNewUserLogEntry( 'autocreate' );
5125 * Load the user options either from cache, the database or an array
5127 * @param array|null $data Rows for the current user out of the user_properties table
5129 protected function loadOptions( $data = null ) {
5132 if ( $this->mOptionsLoaded
) {
5136 $this->mOptions
= self
::getDefaultOptions();
5138 if ( !$this->getId() ) {
5139 // For unlogged-in users, load language/variant options from request.
5140 // There's no need to do it for logged-in users: they can set preferences,
5141 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5142 // so don't override user's choice (especially when the user chooses site default).
5143 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5144 $this->mOptions
['variant'] = $variant;
5145 $this->mOptions
['language'] = $variant;
5146 $this->mOptionsLoaded
= true;
5150 // Maybe load from the object
5151 if ( !is_null( $this->mOptionOverrides
) ) {
5152 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5153 foreach ( $this->mOptionOverrides
as $key => $value ) {
5154 $this->mOptions
[$key] = $value;
5157 if ( !is_array( $data ) ) {
5158 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5159 // Load from database
5160 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5161 ?
wfGetDB( DB_MASTER
)
5162 : wfGetDB( DB_REPLICA
);
5164 $res = $dbr->select(
5166 [ 'up_property', 'up_value' ],
5167 [ 'up_user' => $this->getId() ],
5171 $this->mOptionOverrides
= [];
5173 foreach ( $res as $row ) {
5174 // Convert '0' to 0. PHP's boolean conversion considers them both
5175 // false, but e.g. JavaScript considers the former as true.
5176 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5177 // and convert all values here.
5178 if ( $row->up_value
=== '0' ) {
5181 $data[$row->up_property
] = $row->up_value
;
5185 foreach ( $data as $property => $value ) {
5186 $this->mOptionOverrides
[$property] = $value;
5187 $this->mOptions
[$property] = $value;
5191 // Replace deprecated language codes
5192 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5193 $this->mOptions
['language']
5196 $this->mOptionsLoaded
= true;
5198 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5202 * Saves the non-default options for this user, as previously set e.g. via
5203 * setOption(), in the database's "user_properties" (preferences) table.
5204 * Usually used via saveSettings().
5206 protected function saveOptions() {
5207 $this->loadOptions();
5209 // Not using getOptions(), to keep hidden preferences in database
5210 $saveOptions = $this->mOptions
;
5212 // Allow hooks to abort, for instance to save to a global profile.
5213 // Reset options to default state before saving.
5214 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5218 $userId = $this->getId();
5220 $insert_rows = []; // all the new preference rows
5221 foreach ( $saveOptions as $key => $value ) {
5222 // Don't bother storing default values
5223 $defaultOption = self
::getDefaultOption( $key );
5224 if ( ( $defaultOption === null && $value !== false && $value !== null )
5225 ||
$value != $defaultOption
5228 'up_user' => $userId,
5229 'up_property' => $key,
5230 'up_value' => $value,
5235 $dbw = wfGetDB( DB_MASTER
);
5237 $res = $dbw->select( 'user_properties',
5238 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5240 // Find prior rows that need to be removed or updated. These rows will
5241 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5243 foreach ( $res as $row ) {
5244 if ( !isset( $saveOptions[$row->up_property
] )
5245 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5247 $keysDelete[] = $row->up_property
;
5251 if ( count( $keysDelete ) ) {
5252 // Do the DELETE by PRIMARY KEY for prior rows.
5253 // In the past a very large portion of calls to this function are for setting
5254 // 'rememberpassword' for new accounts (a preference that has since been removed).
5255 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5256 // caused gap locks on [max user ID,+infinity) which caused high contention since
5257 // updates would pile up on each other as they are for higher (newer) user IDs.
5258 // It might not be necessary these days, but it shouldn't hurt either.
5259 $dbw->delete( 'user_properties',
5260 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5262 // Insert the new preference rows
5263 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5267 * Return the list of user fields that should be selected to create
5268 * a new user object.
5269 * @deprecated since 1.31, use self::getQueryInfo() instead.
5272 public static function selectFields() {
5273 wfDeprecated( __METHOD__
, '1.31' );
5281 'user_email_authenticated',
5283 'user_email_token_expires',
5284 'user_registration',
5290 * Return the tables, fields, and join conditions to be selected to create
5291 * a new user object.
5293 * @return array With three keys:
5294 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5295 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5296 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5298 public static function getQueryInfo() {
5299 global $wgActorTableSchemaMigrationStage;
5302 'tables' => [ 'user' ],
5310 'user_email_authenticated',
5312 'user_email_token_expires',
5313 'user_registration',
5319 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5320 // but it does little harm and might be needed for write callers loading a User.
5321 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5322 $ret['tables']['user_actor'] = 'actor';
5323 $ret['fields'][] = 'user_actor.actor_id';
5324 $ret['joins']['user_actor'] = [
5325 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5326 [ 'user_actor.actor_user = user_id' ]
5334 * Factory function for fatal permission-denied errors
5337 * @param string $permission User right required
5340 static function newFatalPermissionDeniedStatus( $permission ) {
5344 foreach ( MediaWikiServices
::getInstance()
5345 ->getPermissionManager()
5346 ->getGroupsWithPermission( $permission ) as $group ) {
5347 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5351 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5354 return Status
::newFatal( 'badaccess-group0' );
5358 * Get a new instance of this user that was loaded from the master via a locking read
5360 * Use this instead of the main context User when updating that user. This avoids races
5361 * where that user was loaded from a replica DB or even the master but without proper locks.
5363 * @return User|null Returns null if the user was not found in the DB
5366 public function getInstanceForUpdate() {
5367 if ( !$this->getId() ) {
5368 return null; // anon
5371 $user = self
::newFromId( $this->getId() );
5372 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5380 * Checks if two user objects point to the same user.
5382 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5383 * @param UserIdentity $user
5386 public function equals( UserIdentity
$user ) {
5387 // XXX it's not clear whether central ID providers are supposed to obey this
5388 return $this->getName() === $user->getName();
5392 * Checks if usertalk is allowed
5396 public function isAllowUsertalk() {
5397 return $this->mAllowUsertalk
;