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, if the ID isn't 0
332 if ( $this->mId
!= 0 ) {
333 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
334 if ( $lb->hasOrMadeRecentMasterChanges() ) {
335 $flags |
= self
::READ_LATEST
;
336 $this->queryFlagsUsed
= $flags;
340 $this->loadFromId( $flags );
344 // Make sure this thread sees its own changes
345 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
346 if ( $lb->hasOrMadeRecentMasterChanges() ) {
347 $flags |
= self
::READ_LATEST
;
348 $this->queryFlagsUsed
= $flags;
351 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
352 $row = wfGetDB( $index )->selectRow(
354 [ 'actor_id', 'actor_user', 'actor_name' ],
355 $this->mFrom
=== 'name' ?
[ 'actor_name' => $this->mName
] : [ 'actor_id' => $this->mActorId
],
362 $this->loadDefaults( $this->mFrom
=== 'name' ?
$this->mName
: false );
363 } elseif ( $row->actor_user
) {
364 $this->mId
= $row->actor_user
;
365 $this->loadFromId( $flags );
367 $this->loadDefaults( $row->actor_name
, $row->actor_id
);
371 if ( !$this->loadFromSession() ) {
372 // Loading from session failed. Load defaults.
373 $this->loadDefaults();
375 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
378 throw new UnexpectedValueException(
379 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
384 * Load user table data, given mId has already been set.
385 * @param int $flags User::READ_* constant bitfield
386 * @return bool False if the ID does not exist, true otherwise
388 public function loadFromId( $flags = self
::READ_NORMAL
) {
389 if ( $this->mId
== 0 ) {
390 // Anonymous users are not in the database (don't need cache)
391 $this->loadDefaults();
395 // Try cache (unless this needs data from the master DB).
396 // NOTE: if this thread called saveSettings(), the cache was cleared.
397 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
399 if ( !$this->loadFromDatabase( $flags ) ) {
400 // Can't load from ID
404 $this->loadFromCache();
407 $this->mLoadedItems
= true;
408 $this->queryFlagsUsed
= $flags;
415 * @param string $dbDomain
418 public static function purge( $dbDomain, $userId ) {
419 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
420 $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
421 $cache->delete( $key );
426 * @param WANObjectCache $cache
429 protected function getCacheKey( WANObjectCache
$cache ) {
430 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
432 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
436 * @param WANObjectCache $cache
440 public function getMutableCacheKeys( WANObjectCache
$cache ) {
441 $id = $this->getId();
443 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
447 * Load user data from shared cache, given mId has already been set.
452 protected function loadFromCache() {
453 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
454 $data = $cache->getWithSetCallback(
455 $this->getCacheKey( $cache ),
457 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
458 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
459 wfDebug( "User: cache miss for user {$this->mId}\n" );
461 $this->loadFromDatabase( self
::READ_NORMAL
);
463 $this->loadOptions();
466 foreach ( self
::$mCacheVars as $name ) {
467 $data[$name] = $this->$name;
470 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
472 // if a user group membership is about to expire, the cache needs to
473 // expire at that time (T163691)
474 foreach ( $this->mGroupMemberships
as $ugm ) {
475 if ( $ugm->getExpiry() ) {
476 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
477 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
478 $ttl = $secondsUntilExpiry;
485 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
488 // Restore from cache
489 foreach ( self
::$mCacheVars as $name ) {
490 $this->$name = $data[$name];
496 /** @name newFrom*() static factory methods */
500 * Static factory method for creation from username.
502 * This is slightly less efficient than newFromId(), so use newFromId() if
503 * you have both an ID and a name handy.
505 * @param string $name Username, validated by Title::newFromText()
506 * @param string|bool $validate Validate username. Takes the same parameters as
507 * User::getCanonicalName(), except that true is accepted as an alias
508 * for 'valid', for BC.
510 * @return User|bool User object, or false if the username is invalid
511 * (e.g. if it contains illegal characters or is an IP address). If the
512 * username is not present in the database, the result will be a user object
513 * with a name, zero user ID and default settings.
515 public static function newFromName( $name, $validate = 'valid' ) {
516 if ( $validate === true ) {
519 $name = self
::getCanonicalName( $name, $validate );
520 if ( $name === false ) {
524 // Create unloaded user object
528 $u->setItemLoaded( 'name' );
534 * Static factory method for creation from a given user ID.
536 * @param int $id Valid user ID
537 * @return User The corresponding User object
539 public static function newFromId( $id ) {
543 $u->setItemLoaded( 'id' );
548 * Static factory method for creation from a given actor ID.
551 * @param int $id Valid actor ID
552 * @return User The corresponding User object
554 public static function newFromActorId( $id ) {
558 $u->setItemLoaded( 'actor' );
563 * Returns a User object corresponding to the given UserIdentity.
567 * @param UserIdentity $identity
571 public static function newFromIdentity( UserIdentity
$identity ) {
572 if ( $identity instanceof User
) {
576 return self
::newFromAnyId(
577 $identity->getId() === 0 ?
null : $identity->getId(),
578 $identity->getName() === '' ?
null : $identity->getName(),
579 $identity->getActorId() === 0 ?
null : $identity->getActorId()
584 * Static factory method for creation from an ID, name, and/or actor ID
586 * This does not check that the ID, name, and actor ID all correspond to
590 * @param int|null $userId User ID, if known
591 * @param string|null $userName User name, if known
592 * @param int|null $actorId Actor ID, if known
593 * @param bool|string $dbDomain remote wiki to which the User/Actor ID applies, or false if none
596 public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
597 // Stop-gap solution for the problem described in T222212.
598 // Force the User ID and Actor ID to zero for users loaded from the database
599 // of another wiki, to prevent subtle data corruption and confusing failure modes.
600 if ( $dbDomain !== false ) {
606 $user->mFrom
= 'defaults';
608 if ( $actorId !== null ) {
609 $user->mActorId
= (int)$actorId;
610 if ( $user->mActorId
!== 0 ) {
611 $user->mFrom
= 'actor';
613 $user->setItemLoaded( 'actor' );
616 if ( $userName !== null && $userName !== '' ) {
617 $user->mName
= $userName;
618 $user->mFrom
= 'name';
619 $user->setItemLoaded( 'name' );
622 if ( $userId !== null ) {
623 $user->mId
= (int)$userId;
624 if ( $user->mId
!== 0 ) {
627 $user->setItemLoaded( 'id' );
630 if ( $user->mFrom
=== 'defaults' ) {
631 throw new InvalidArgumentException(
632 'Cannot create a user with no name, no ID, and no actor ID'
640 * Factory method to fetch whichever user has a given email confirmation code.
641 * This code is generated when an account is created or its e-mail address
644 * If the code is invalid or has expired, returns NULL.
646 * @param string $code Confirmation code
647 * @param int $flags User::READ_* bitfield
650 public static function newFromConfirmationCode( $code, $flags = 0 ) {
651 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
652 ?
wfGetDB( DB_MASTER
)
653 : wfGetDB( DB_REPLICA
);
655 $id = $db->selectField(
659 'user_email_token' => md5( $code ),
660 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
664 return $id ? self
::newFromId( $id ) : null;
668 * Create a new user object using data from session. If the login
669 * credentials are invalid, the result is an anonymous user.
671 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
674 public static function newFromSession( WebRequest
$request = null ) {
676 $user->mFrom
= 'session';
677 $user->mRequest
= $request;
682 * Create a new user object from a user row.
683 * The row should have the following fields from the user table in it:
684 * - either user_name or user_id to load further data if needed (or both)
686 * - all other fields (email, etc.)
687 * It is useless to provide the remaining fields if either user_id,
688 * user_name and user_real_name are not provided because the whole row
689 * will be loaded once more from the database when accessing them.
691 * @param stdClass $row A row from the user table
692 * @param array|null $data Further data to load into the object
693 * (see User::loadFromRow for valid keys)
696 public static function newFromRow( $row, $data = null ) {
698 $user->loadFromRow( $row, $data );
703 * Static factory method for creation of a "system" user from username.
705 * A "system" user is an account that's used to attribute logged actions
706 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
707 * might include the 'Maintenance script' or 'Conversion script' accounts
708 * used by various scripts in the maintenance/ directory or accounts such
709 * as 'MediaWiki message delivery' used by the MassMessage extension.
711 * This can optionally create the user if it doesn't exist, and "steal" the
712 * account if it does exist.
714 * "Stealing" an existing user is intended to make it impossible for normal
715 * authentication processes to use the account, effectively disabling the
716 * account for normal use:
717 * - Email is invalidated, to prevent account recovery by emailing a
718 * temporary password and to disassociate the account from the existing
720 * - The token is set to a magic invalid value, to kill existing sessions
721 * and to prevent $this->setToken() calls from resetting the token to a
723 * - SessionManager is instructed to prevent new sessions for the user, to
724 * do things like deauthorizing OAuth consumers.
725 * - AuthManager is instructed to revoke access, to invalidate or remove
726 * passwords and other credentials.
728 * @param string $name Username
729 * @param array $options Options are:
730 * - validate: As for User::getCanonicalName(), default 'valid'
731 * - create: Whether to create the user if it doesn't already exist, default true
732 * - steal: Whether to "disable" the account for normal use if it already
733 * exists, default false
737 public static function newSystemUser( $name, $options = [] ) {
739 'validate' => 'valid',
744 $name = self
::getCanonicalName( $name, $options['validate'] );
745 if ( $name === false ) {
749 $dbr = wfGetDB( DB_REPLICA
);
750 $userQuery = self
::getQueryInfo();
751 $row = $dbr->selectRow(
752 $userQuery['tables'],
753 $userQuery['fields'],
754 [ 'user_name' => $name ],
760 // Try the master database...
761 $dbw = wfGetDB( DB_MASTER
);
762 $row = $dbw->selectRow(
763 $userQuery['tables'],
764 $userQuery['fields'],
765 [ 'user_name' => $name ],
773 // No user. Create it?
774 return $options['create']
775 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
779 $user = self
::newFromRow( $row );
781 // A user is considered to exist as a non-system user if it can
782 // authenticate, or has an email set, or has a non-invalid token.
783 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
784 AuthManager
::singleton()->userCanAuthenticate( $name )
786 // User exists. Steal it?
787 if ( !$options['steal'] ) {
791 AuthManager
::singleton()->revokeAccessForUser( $name );
793 $user->invalidateEmail();
794 $user->mToken
= self
::INVALID_TOKEN
;
795 $user->saveSettings();
796 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
805 * Get the username corresponding to a given user ID
806 * @param int $id User ID
807 * @return string|bool The corresponding username
809 public static function whoIs( $id ) {
810 return UserCache
::singleton()->getProp( $id, 'name' );
814 * Get the real name of a user given their user ID
816 * @param int $id User ID
817 * @return string|bool The corresponding user's real name
819 public static function whoIsReal( $id ) {
820 return UserCache
::singleton()->getProp( $id, 'real_name' );
824 * Get database id given a user name
825 * @param string $name Username
826 * @param int $flags User::READ_* constant bitfield
827 * @return int|null The corresponding user's ID, or null if user is nonexistent
829 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
830 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
831 $name = (string)$name;
832 $nt = Title
::makeTitleSafe( NS_USER
, $name );
833 if ( is_null( $nt ) ) {
838 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
839 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
842 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
843 $db = wfGetDB( $index );
848 [ 'user_name' => $nt->getText() ],
853 if ( $s === false ) {
856 $result = (int)$s->user_id
;
859 if ( count( self
::$idCacheByName ) >= 1000 ) {
860 self
::$idCacheByName = [];
863 self
::$idCacheByName[$name] = $result;
869 * Reset the cache used in idFromName(). For use in tests.
871 public static function resetIdByNameCache() {
872 self
::$idCacheByName = [];
876 * Does the string match an anonymous IP address?
878 * This function exists for username validation, in order to reject
879 * usernames which are similar in form to IP addresses. Strings such
880 * as 300.300.300.300 will return true because it looks like an IP
881 * address, despite not being strictly valid.
883 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
884 * address because the usemod software would "cloak" anonymous IP
885 * addresses like this, if we allowed accounts like this to be created
886 * new users could get the old edits of these anonymous users.
888 * @param string $name Name to match
891 public static function isIP( $name ) {
892 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
893 || IP
::isIPv6( $name );
897 * Is the user an IP range?
902 public function isIPRange() {
903 return IP
::isValidRange( $this->mName
);
907 * Is the input a valid username?
909 * Checks if the input is a valid username, we don't want an empty string,
910 * an IP address, anything that contains slashes (would mess up subpages),
911 * is longer than the maximum allowed username size or doesn't begin with
914 * @param string $name Name to match
917 public static function isValidUserName( $name ) {
918 global $wgMaxNameChars;
921 || self
::isIP( $name )
922 ||
strpos( $name, '/' ) !== false
923 ||
strlen( $name ) > $wgMaxNameChars
924 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
929 // Ensure that the name can't be misresolved as a different title,
930 // such as with extra namespace keys at the start.
931 $parsed = Title
::newFromText( $name );
932 if ( is_null( $parsed )
933 ||
$parsed->getNamespace()
934 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
938 // Check an additional blacklist of troublemaker characters.
939 // Should these be merged into the title char list?
940 $unicodeBlacklist = '/[' .
941 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
942 '\x{00a0}' . # non-breaking space
943 '\x{2000}-\x{200f}' . # various whitespace
944 '\x{2028}-\x{202f}' . # breaks and control chars
945 '\x{3000}' . # ideographic space
946 '\x{e000}-\x{f8ff}' . # private use
948 if ( preg_match( $unicodeBlacklist, $name ) ) {
956 * Usernames which fail to pass this function will be blocked
957 * from user login and new account registrations, but may be used
958 * internally by batch processes.
960 * If an account already exists in this form, login will be blocked
961 * by a failure to pass this function.
963 * @param string $name Name to match
966 public static function isUsableName( $name ) {
967 global $wgReservedUsernames;
968 // Must be a valid username, obviously ;)
969 if ( !self
::isValidUserName( $name ) ) {
973 static $reservedUsernames = false;
974 if ( !$reservedUsernames ) {
975 $reservedUsernames = $wgReservedUsernames;
976 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
979 // Certain names may be reserved for batch processes.
980 foreach ( $reservedUsernames as $reserved ) {
981 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
982 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
984 if ( $reserved == $name ) {
992 * Return the users who are members of the given group(s). In case of multiple groups,
993 * users who are members of at least one of them are returned.
995 * @param string|array $groups A single group name or an array of group names
996 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
997 * records; larger values are ignored.
998 * @param int|null $after ID the user to start after
999 * @return UserArrayFromResult
1001 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1002 if ( $groups === [] ) {
1003 return UserArrayFromResult
::newFromIDs( [] );
1006 $groups = array_unique( (array)$groups );
1007 $limit = min( 5000, $limit );
1009 $conds = [ 'ug_group' => $groups ];
1010 if ( $after !== null ) {
1011 $conds[] = 'ug_user > ' . (int)$after;
1014 $dbr = wfGetDB( DB_REPLICA
);
1015 $ids = $dbr->selectFieldValues(
1022 'ORDER BY' => 'ug_user',
1026 return UserArray
::newFromIDs( $ids );
1030 * Usernames which fail to pass this function will be blocked
1031 * from new account registrations, but may be used internally
1032 * either by batch processes or by user accounts which have
1033 * already been created.
1035 * Additional blacklisting may be added here rather than in
1036 * isValidUserName() to avoid disrupting existing accounts.
1038 * @param string $name String to match
1041 public static function isCreatableName( $name ) {
1042 global $wgInvalidUsernameCharacters;
1044 // Ensure that the username isn't longer than 235 bytes, so that
1045 // (at least for the builtin skins) user javascript and css files
1046 // will work. (T25080)
1047 if ( strlen( $name ) > 235 ) {
1048 wfDebugLog( 'username', __METHOD__
.
1049 ": '$name' invalid due to length" );
1053 // Preg yells if you try to give it an empty string
1054 if ( $wgInvalidUsernameCharacters !== '' &&
1055 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1057 wfDebugLog( 'username', __METHOD__
.
1058 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1062 return self
::isUsableName( $name );
1066 * Is the input a valid password for this user?
1068 * @param string $password Desired password
1071 public function isValidPassword( $password ) {
1072 // simple boolean wrapper for checkPasswordValidity
1073 return $this->checkPasswordValidity( $password )->isGood();
1077 * Check if this is a valid password for this user
1079 * Returns a Status object with a set of messages describing
1080 * problems with the password. If the return status is fatal,
1081 * the action should be refused and the password should not be
1082 * checked at all (this is mainly meant for DoS mitigation).
1083 * If the return value is OK but not good, the password can be checked,
1084 * but the user should not be able to set their password to this.
1085 * The value of the returned Status object will be an array which
1086 * can have the following fields:
1087 * - forceChange (bool): if set to true, the user should not be
1088 * allowed to log with this password unless they change it during
1089 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1090 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1091 * a password change on login.
1093 * @param string $password Desired password
1097 public function checkPasswordValidity( $password ) {
1098 global $wgPasswordPolicy;
1100 $upp = new UserPasswordPolicy(
1101 $wgPasswordPolicy['policies'],
1102 $wgPasswordPolicy['checks']
1105 $status = Status
::newGood( [] );
1106 $result = false; // init $result to false for the internal checks
1108 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1109 $status->error( $result );
1113 if ( $result === false ) {
1114 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1118 if ( $result === true ) {
1122 $status->error( $result );
1123 return $status; // the isValidPassword hook set a string $result and returned true
1127 * Given unvalidated user input, return a canonical username, or false if
1128 * the username is invalid.
1129 * @param string $name User input
1130 * @param string|bool $validate Type of validation to use:
1131 * - false No validation
1132 * - 'valid' Valid for batch processes
1133 * - 'usable' Valid for batch processes and login
1134 * - 'creatable' Valid for batch processes, login and account creation
1136 * @throws InvalidArgumentException
1137 * @return bool|string
1139 public static function getCanonicalName( $name, $validate = 'valid' ) {
1140 // Force usernames to capital
1141 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1143 # Reject names containing '#'; these will be cleaned up
1144 # with title normalisation, but then it's too late to
1146 if ( strpos( $name, '#' ) !== false ) {
1150 // Clean up name according to title rules,
1151 // but only when validation is requested (T14654)
1152 $t = ( $validate !== false ) ?
1153 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1154 // Check for invalid titles
1155 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1159 $name = $t->getText();
1161 switch ( $validate ) {
1165 if ( !self
::isValidUserName( $name ) ) {
1170 if ( !self
::isUsableName( $name ) ) {
1175 if ( !self
::isCreatableName( $name ) ) {
1180 throw new InvalidArgumentException(
1181 'Invalid parameter value for $validate in ' . __METHOD__
);
1187 * Set cached properties to default.
1189 * @note This no longer clears uncached lazy-initialised properties;
1190 * the constructor does that instead.
1192 * @param string|bool $name
1193 * @param int|null $actorId
1195 public function loadDefaults( $name = false, $actorId = null ) {
1197 $this->mName
= $name;
1198 $this->mActorId
= $actorId;
1199 $this->mRealName
= '';
1201 $this->mOptionOverrides
= null;
1202 $this->mOptionsLoaded
= false;
1204 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1205 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1206 if ( $loggedOut !== 0 ) {
1207 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1209 $this->mTouched
= '1'; # Allow any pages to be cached
1212 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1213 $this->mEmailAuthenticated
= null;
1214 $this->mEmailToken
= '';
1215 $this->mEmailTokenExpires
= null;
1216 $this->mRegistration
= wfTimestamp( TS_MW
);
1217 $this->mGroupMemberships
= [];
1219 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1223 * Return whether an item has been loaded.
1225 * @param string $item Item to check. Current possibilities:
1229 * @param string $all 'all' to check if the whole object has been loaded
1230 * or any other string to check if only the item is available (e.g.
1234 public function isItemLoaded( $item, $all = 'all' ) {
1235 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1236 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1240 * Set that an item has been loaded
1242 * @param string $item
1244 protected function setItemLoaded( $item ) {
1245 if ( is_array( $this->mLoadedItems
) ) {
1246 $this->mLoadedItems
[$item] = true;
1251 * Load user data from the session.
1253 * @return bool True if the user is logged in, false otherwise.
1255 private function loadFromSession() {
1256 // MediaWiki\Session\Session already did the necessary authentication of the user
1257 // returned here, so just use it if applicable.
1258 $session = $this->getRequest()->getSession();
1259 $user = $session->getUser();
1260 if ( $user->isLoggedIn() ) {
1261 $this->loadFromUserObject( $user );
1263 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1264 // every session load, because an autoblocked editor might not edit again from the same
1265 // IP address after being blocked.
1266 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1268 // Other code expects these to be set in the session, so set them.
1269 $session->set( 'wsUserID', $this->getId() );
1270 $session->set( 'wsUserName', $this->getName() );
1271 $session->set( 'wsToken', $this->getToken() );
1280 * Set the 'BlockID' cookie depending on block type and user authentication status.
1282 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1284 public function trackBlockWithCookie() {
1285 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1289 * Load user and user_group data from the database.
1290 * $this->mId must be set, this is how the user is identified.
1292 * @param int $flags User::READ_* constant bitfield
1293 * @return bool True if the user exists, false if the user is anonymous
1295 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1297 $this->mId
= intval( $this->mId
);
1299 if ( !$this->mId
) {
1300 // Anonymous users are not in the database
1301 $this->loadDefaults();
1305 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1306 $db = wfGetDB( $index );
1308 $userQuery = self
::getQueryInfo();
1309 $s = $db->selectRow(
1310 $userQuery['tables'],
1311 $userQuery['fields'],
1312 [ 'user_id' => $this->mId
],
1318 $this->queryFlagsUsed
= $flags;
1319 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1321 if ( $s !== false ) {
1322 // Initialise user table data
1323 $this->loadFromRow( $s );
1324 $this->mGroupMemberships
= null; // deferred
1325 $this->getEditCount(); // revalidation for nulls
1331 $this->loadDefaults();
1337 * Initialize this object from a row from the user table.
1339 * @param stdClass $row Row from the user table to load.
1340 * @param array|null $data Further user data to load into the object
1342 * user_groups Array of arrays or stdClass result rows out of the user_groups
1343 * table. Previously you were supposed to pass an array of strings
1344 * here, but we also need expiry info nowadays, so an array of
1345 * strings is ignored.
1346 * user_properties Array with properties out of the user_properties table
1348 protected function loadFromRow( $row, $data = null ) {
1349 if ( !is_object( $row ) ) {
1350 throw new InvalidArgumentException( '$row must be an object' );
1355 $this->mGroupMemberships
= null; // deferred
1357 if ( isset( $row->actor_id
) ) {
1358 $this->mActorId
= (int)$row->actor_id
;
1359 if ( $this->mActorId
!== 0 ) {
1360 $this->mFrom
= 'actor';
1362 $this->setItemLoaded( 'actor' );
1367 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1368 $this->mName
= $row->user_name
;
1369 $this->mFrom
= 'name';
1370 $this->setItemLoaded( 'name' );
1375 if ( isset( $row->user_real_name
) ) {
1376 $this->mRealName
= $row->user_real_name
;
1377 $this->setItemLoaded( 'realname' );
1382 if ( isset( $row->user_id
) ) {
1383 $this->mId
= intval( $row->user_id
);
1384 if ( $this->mId
!== 0 ) {
1385 $this->mFrom
= 'id';
1387 $this->setItemLoaded( 'id' );
1392 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1393 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1396 if ( isset( $row->user_editcount
) ) {
1397 $this->mEditCount
= $row->user_editcount
;
1402 if ( isset( $row->user_touched
) ) {
1403 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1408 if ( isset( $row->user_token
) ) {
1409 // The definition for the column is binary(32), so trim the NULs
1410 // that appends. The previous definition was char(32), so trim
1412 $this->mToken
= rtrim( $row->user_token
, " \0" );
1413 if ( $this->mToken
=== '' ) {
1414 $this->mToken
= null;
1420 if ( isset( $row->user_email
) ) {
1421 $this->mEmail
= $row->user_email
;
1422 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1423 $this->mEmailToken
= $row->user_email_token
;
1424 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1425 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1431 $this->mLoadedItems
= true;
1434 if ( is_array( $data ) ) {
1435 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1436 if ( $data['user_groups'] === [] ) {
1437 $this->mGroupMemberships
= [];
1439 $firstGroup = reset( $data['user_groups'] );
1440 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1441 $this->mGroupMemberships
= [];
1442 foreach ( $data['user_groups'] as $row ) {
1443 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1444 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1449 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1450 $this->loadOptions( $data['user_properties'] );
1456 * Load the data for this user object from another user object.
1460 protected function loadFromUserObject( $user ) {
1462 foreach ( self
::$mCacheVars as $var ) {
1463 $this->$var = $user->$var;
1468 * Load the groups from the database if they aren't already loaded.
1470 private function loadGroups() {
1471 if ( is_null( $this->mGroupMemberships
) ) {
1472 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1473 ?
wfGetDB( DB_MASTER
)
1474 : wfGetDB( DB_REPLICA
);
1475 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1481 * Add the user to the group if he/she meets given criteria.
1483 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1484 * possible to remove manually via Special:UserRights. In such case it
1485 * will not be re-added automatically. The user will also not lose the
1486 * group if they no longer meet the criteria.
1488 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1490 * @return array Array of groups the user has been promoted to.
1492 * @see $wgAutopromoteOnce
1494 public function addAutopromoteOnceGroups( $event ) {
1495 global $wgAutopromoteOnceLogInRC;
1497 if ( wfReadOnly() ||
!$this->getId() ) {
1501 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1502 if ( $toPromote === [] ) {
1506 if ( !$this->checkAndSetTouched() ) {
1507 return []; // raced out (bug T48834)
1510 $oldGroups = $this->getGroups(); // previous groups
1511 $oldUGMs = $this->getGroupMemberships();
1512 foreach ( $toPromote as $group ) {
1513 $this->addGroup( $group );
1515 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1516 $newUGMs = $this->getGroupMemberships();
1518 // update groups in external authentication database
1519 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1521 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1522 $logEntry->setPerformer( $this );
1523 $logEntry->setTarget( $this->getUserPage() );
1524 $logEntry->setParameters( [
1525 '4::oldgroups' => $oldGroups,
1526 '5::newgroups' => $newGroups,
1528 $logid = $logEntry->insert();
1529 if ( $wgAutopromoteOnceLogInRC ) {
1530 $logEntry->publish( $logid );
1537 * Builds update conditions. Additional conditions may be added to $conditions to
1538 * protected against race conditions using a compare-and-set (CAS) mechanism
1539 * based on comparing $this->mTouched with the user_touched field.
1541 * @param IDatabase $db
1542 * @param array $conditions WHERE conditions for use with Database::update
1543 * @return array WHERE conditions for use with Database::update
1545 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1546 if ( $this->mTouched
) {
1547 // CAS check: only update if the row wasn't changed sicne it was loaded.
1548 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1555 * Bump user_touched if it didn't change since this object was loaded
1557 * On success, the mTouched field is updated.
1558 * The user serialization cache is always cleared.
1560 * @return bool Whether user_touched was actually updated
1563 protected function checkAndSetTouched() {
1566 if ( !$this->mId
) {
1567 return false; // anon
1570 // Get a new user_touched that is higher than the old one
1571 $newTouched = $this->newTouchedTimestamp();
1573 $dbw = wfGetDB( DB_MASTER
);
1574 $dbw->update( 'user',
1575 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1576 $this->makeUpdateConditions( $dbw, [
1577 'user_id' => $this->mId
,
1581 $success = ( $dbw->affectedRows() > 0 );
1584 $this->mTouched
= $newTouched;
1585 $this->clearSharedCache( 'changed' );
1587 // Clears on failure too since that is desired if the cache is stale
1588 $this->clearSharedCache( 'refresh' );
1595 * Clear various cached data stored in this object. The cache of the user table
1596 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1598 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1599 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1601 public function clearInstanceCache( $reloadFrom = false ) {
1602 global $wgFullyInitialised;
1604 $this->mNewtalk
= -1;
1605 $this->mDatePreference
= null;
1606 $this->mBlockedby
= -1; # Unset
1607 $this->mHash
= false;
1608 $this->mEffectiveGroups
= null;
1609 $this->mImplicitGroups
= null;
1610 $this->mGroupMemberships
= null;
1611 $this->mOptions
= null;
1612 $this->mOptionsLoaded
= false;
1613 $this->mEditCount
= null;
1615 // Replacement of former `$this->mRights = null` line
1616 if ( $wgFullyInitialised && $this->mFrom
) {
1617 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1622 if ( $reloadFrom ) {
1623 $this->mLoadedItems
= [];
1624 $this->mFrom
= $reloadFrom;
1628 /** @var array|null */
1629 private static $defOpt = null;
1630 /** @var string|null */
1631 private static $defOptLang = null;
1634 * Reset the process cache of default user options. This is only necessary
1635 * if the wiki configuration has changed since defaults were calculated,
1636 * and as such should only be performed inside the testing suite that
1637 * regularly changes wiki configuration.
1639 public static function resetGetDefaultOptionsForTestsOnly() {
1640 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1641 self
::$defOpt = null;
1642 self
::$defOptLang = null;
1646 * Combine the language default options with any site-specific options
1647 * and add the default language variants.
1649 * @return array Array of String options
1651 public static function getDefaultOptions() {
1652 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1654 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1655 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1656 // The content language does not change (and should not change) mid-request, but the
1657 // unit tests change it anyway, and expect this method to return values relevant to the
1658 // current content language.
1659 return self
::$defOpt;
1662 self
::$defOpt = $wgDefaultUserOptions;
1663 // Default language setting
1664 self
::$defOptLang = $contLang->getCode();
1665 self
::$defOpt['language'] = self
::$defOptLang;
1666 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1667 if ( $langCode === $contLang->getCode() ) {
1668 self
::$defOpt['variant'] = $langCode;
1670 self
::$defOpt["variant-$langCode"] = $langCode;
1674 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1675 // since extensions may change the set of searchable namespaces depending
1676 // on user groups/permissions.
1677 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1678 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1680 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1682 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1684 return self
::$defOpt;
1688 * Get a given default option value.
1690 * @param string $opt Name of option to retrieve
1691 * @return string Default option value
1693 public static function getDefaultOption( $opt ) {
1694 $defOpts = self
::getDefaultOptions();
1695 return $defOpts[$opt] ??
null;
1699 * Get blocking information
1701 * TODO: Move this into the BlockManager, along with block-related properties.
1703 * @param bool $fromReplica Whether to check the replica DB first.
1704 * To improve performance, non-critical checks are done against replica DBs.
1705 * Check when actually saving should be done against master.
1707 private function getBlockedStatus( $fromReplica = true ) {
1708 if ( $this->mBlockedby
!= -1 ) {
1712 wfDebug( __METHOD__
. ": checking...\n" );
1714 // Initialize data...
1715 // Otherwise something ends up stomping on $this->mBlockedby when
1716 // things get lazy-loaded later, causing false positive block hits
1717 // due to -1 !== 0. Probably session-related... Nothing should be
1718 // overwriting mBlockedby, surely?
1721 // @phan-suppress-next-line PhanAccessMethodInternal It's the only allowed use
1722 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1728 $this->mBlock
= $block;
1729 $this->mBlockedby
= $block->getByName();
1730 $this->mBlockreason
= $block->getReason();
1731 $this->mHideName
= $block->getHideName();
1732 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1734 $this->mBlock
= null;
1735 $this->mBlockedby
= '';
1736 $this->mBlockreason
= '';
1737 $this->mHideName
= 0;
1738 $this->mAllowUsertalk
= false;
1741 // Avoid PHP 7.1 warning of passing $this by reference
1744 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1748 * Whether the given IP is in a DNS blacklist.
1750 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1751 * @param string $ip IP to check
1752 * @param bool $checkWhitelist Whether to check the whitelist first
1753 * @return bool True if blacklisted.
1755 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1756 return MediaWikiServices
::getInstance()->getBlockManager()
1757 ->isDnsBlacklisted( $ip, $checkWhitelist );
1761 * Whether the given IP is in a given DNS blacklist.
1763 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1764 * @param string $ip IP to check
1765 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1766 * @return bool True if blacklisted.
1768 public function inDnsBlacklist( $ip, $bases ) {
1769 wfDeprecated( __METHOD__
, '1.34' );
1772 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1773 if ( IP
::isIPv4( $ip ) ) {
1774 // Reverse IP, T23255
1775 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1777 foreach ( (array)$bases as $base ) {
1779 // If we have an access key, use that too (ProjectHoneypot, etc.)
1781 if ( is_array( $base ) ) {
1782 if ( count( $base ) >= 2 ) {
1783 // Access key is 1, base URL is 0
1784 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1786 $host = "$ipReversed.{$base[0]}";
1788 $basename = $base[0];
1790 $host = "$ipReversed.$base";
1794 $ipList = gethostbynamel( $host );
1797 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1802 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1810 * Check if an IP address is in the local proxy list
1812 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1816 public static function isLocallyBlockedProxy( $ip ) {
1817 wfDeprecated( __METHOD__
, '1.34' );
1819 global $wgProxyList;
1821 if ( !$wgProxyList ) {
1825 if ( !is_array( $wgProxyList ) ) {
1826 // Load values from the specified file
1827 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1830 $resultProxyList = [];
1831 $deprecatedIPEntries = [];
1833 // backward compatibility: move all ip addresses in keys to values
1834 foreach ( $wgProxyList as $key => $value ) {
1835 $keyIsIP = IP
::isIPAddress( $key );
1836 $valueIsIP = IP
::isIPAddress( $value );
1837 if ( $keyIsIP && !$valueIsIP ) {
1838 $deprecatedIPEntries[] = $key;
1839 $resultProxyList[] = $key;
1840 } elseif ( $keyIsIP && $valueIsIP ) {
1841 $deprecatedIPEntries[] = $key;
1842 $resultProxyList[] = $key;
1843 $resultProxyList[] = $value;
1845 $resultProxyList[] = $value;
1849 if ( $deprecatedIPEntries ) {
1851 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1852 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1855 $proxyListIPSet = new IPSet( $resultProxyList );
1856 return $proxyListIPSet->match( $ip );
1860 * Is this user subject to rate limiting?
1862 * @return bool True if rate limited
1864 public function isPingLimitable() {
1865 global $wgRateLimitsExcludedIPs;
1866 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1867 // No other good way currently to disable rate limits
1868 // for specific IPs. :P
1869 // But this is a crappy hack and should die.
1872 return !$this->isAllowed( 'noratelimit' );
1876 * Primitive rate limits: enforce maximum actions per time period
1877 * to put a brake on flooding.
1879 * The method generates both a generic profiling point and a per action one
1880 * (suffix being "-$action".
1882 * @note When using a shared cache like memcached, IP-address
1883 * last-hit counters will be shared across wikis.
1885 * @param string $action Action to enforce; 'edit' if unspecified
1886 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1887 * @return bool True if a rate limiter was tripped
1889 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1890 // Avoid PHP 7.1 warning of passing $this by reference
1892 // Call the 'PingLimiter' hook
1894 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1898 global $wgRateLimits;
1899 if ( !isset( $wgRateLimits[$action] ) ) {
1903 $limits = array_merge(
1904 [ '&can-bypass' => true ],
1905 $wgRateLimits[$action]
1908 // Some groups shouldn't trigger the ping limiter, ever
1909 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1914 $id = $this->getId();
1916 $isNewbie = $this->isNewbie();
1917 $cache = ObjectCache
::getLocalClusterInstance();
1921 if ( isset( $limits['anon'] ) ) {
1922 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1924 } elseif ( isset( $limits['user'] ) ) {
1925 // limits for logged-in users
1926 $userLimit = $limits['user'];
1929 // limits for anons and for newbie logged-in users
1932 if ( isset( $limits['ip'] ) ) {
1933 $ip = $this->getRequest()->getIP();
1934 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1936 // subnet-based limits
1937 if ( isset( $limits['subnet'] ) ) {
1938 $ip = $this->getRequest()->getIP();
1939 $subnet = IP
::getSubnet( $ip );
1940 if ( $subnet !== false ) {
1941 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1946 // Check for group-specific permissions
1947 // If more than one group applies, use the group with the highest limit ratio (max/period)
1948 foreach ( $this->getGroups() as $group ) {
1949 if ( isset( $limits[$group] ) ) {
1950 if ( $userLimit === false
1951 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1953 $userLimit = $limits[$group];
1958 // limits for newbie logged-in users (override all the normal user limits)
1959 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1960 $userLimit = $limits['newbie'];
1963 // Set the user limit key
1964 if ( $userLimit !== false ) {
1965 // phan is confused because &can-bypass's value is a bool, so it assumes
1966 // that $userLimit is also a bool here.
1967 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
1968 list( $max, $period ) = $userLimit;
1969 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1970 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
1973 // ip-based limits for all ping-limitable users
1974 if ( isset( $limits['ip-all'] ) ) {
1975 $ip = $this->getRequest()->getIP();
1976 // ignore if user limit is more permissive
1977 if ( $isNewbie ||
$userLimit === false
1978 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1979 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1983 // subnet-based limits for all ping-limitable users
1984 if ( isset( $limits['subnet-all'] ) ) {
1985 $ip = $this->getRequest()->getIP();
1986 $subnet = IP
::getSubnet( $ip );
1987 if ( $subnet !== false ) {
1988 // ignore if user limit is more permissive
1989 if ( $isNewbie ||
$userLimit === false
1990 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1991 > $userLimit[0] / $userLimit[1] ) {
1992 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1998 foreach ( $keys as $key => $limit ) {
1999 // phan is confused because &can-bypass's value is a bool, so it assumes
2000 // that $userLimit is also a bool here.
2001 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2002 list( $max, $period ) = $limit;
2003 $summary = "(limit $max in {$period}s)";
2004 $count = $cache->get( $key );
2006 if ( $count && $count >= $max ) {
2007 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2008 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2011 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2012 if ( $incrBy > 0 ) {
2013 $cache->add( $key, 0, intval( $period ) ); // first ping
2016 if ( $incrBy > 0 ) {
2017 $cache->incrWithInit( $key, (int)$period, $incrBy, $incrBy );
2025 * Check if user is blocked
2027 * @deprecated since 1.34, use User::getBlock() or
2028 * PermissionManager::isBlockedFrom() or
2029 * PermissionManager::userCan() instead.
2031 * @param bool $fromReplica Whether to check the replica DB instead of
2032 * the master. Hacked from false due to horrible probs on site.
2033 * @return bool True if blocked, false otherwise
2035 public function isBlocked( $fromReplica = true ) {
2036 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2037 $this->getBlock()->appliesToRight( 'edit' );
2041 * Get the block affecting the user, or null if the user is not blocked
2043 * @param bool $fromReplica Whether to check the replica DB instead of the master
2044 * @return AbstractBlock|null
2046 public function getBlock( $fromReplica = true ) {
2047 $this->getBlockedStatus( $fromReplica );
2048 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2052 * Check if user is blocked from editing a particular article
2054 * @param Title $title Title to check
2055 * @param bool $fromReplica Whether to check the replica DB instead of the master
2058 * @deprecated since 1.33,
2059 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2062 public function isBlockedFrom( $title, $fromReplica = false ) {
2063 return MediaWikiServices
::getInstance()->getPermissionManager()
2064 ->isBlockedFrom( $this, $title, $fromReplica );
2068 * If user is blocked, return the name of the user who placed the block
2069 * @return string Name of blocker
2071 public function blockedBy() {
2072 $this->getBlockedStatus();
2073 return $this->mBlockedby
;
2077 * If user is blocked, return the specified reason for the block
2078 * @return string Blocking reason
2080 public function blockedFor() {
2081 $this->getBlockedStatus();
2082 return $this->mBlockreason
;
2086 * If user is blocked, return the ID for the block
2087 * @return int Block ID
2089 public function getBlockId() {
2090 $this->getBlockedStatus();
2091 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2095 * Check if user is blocked on all wikis.
2096 * Do not use for actual edit permission checks!
2097 * This is intended for quick UI checks.
2099 * @param string $ip IP address, uses current client if none given
2100 * @return bool True if blocked, false otherwise
2102 public function isBlockedGlobally( $ip = '' ) {
2103 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2107 * Check if user is blocked on all wikis.
2108 * Do not use for actual edit permission checks!
2109 * This is intended for quick UI checks.
2111 * @param string $ip IP address, uses current client if none given
2112 * @return AbstractBlock|null Block object if blocked, null otherwise
2113 * @throws FatalError
2114 * @throws MWException
2116 public function getGlobalBlock( $ip = '' ) {
2117 if ( $this->mGlobalBlock
!== null ) {
2118 return $this->mGlobalBlock ?
: null;
2120 // User is already an IP?
2121 if ( IP
::isIPAddress( $this->getName() ) ) {
2122 $ip = $this->getName();
2124 $ip = $this->getRequest()->getIP();
2126 // Avoid PHP 7.1 warning of passing $this by reference
2130 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2132 if ( $blocked && $block === null ) {
2133 // back-compat: UserIsBlockedGlobally didn't have $block param first
2134 $block = new SystemBlock( [
2136 'systemBlock' => 'global-block'
2140 $this->mGlobalBlock
= $blocked ?
$block : false;
2141 return $this->mGlobalBlock ?
: null;
2145 * Check if user account is locked
2147 * @return bool True if locked, false otherwise
2149 public function isLocked() {
2150 if ( $this->mLocked
!== null ) {
2151 return $this->mLocked
;
2154 $this->mLocked
= false;
2155 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2156 return $this->mLocked
;
2160 * Check if user account is hidden
2162 * @return bool True if hidden, false otherwise
2164 public function isHidden() {
2165 if ( $this->mHideName
!== null ) {
2166 return (bool)$this->mHideName
;
2168 $this->getBlockedStatus();
2169 if ( !$this->mHideName
) {
2171 $this->mHideName
= false;
2172 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
], '1.34' );
2174 return (bool)$this->mHideName
;
2178 * Get the user's ID.
2179 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2181 public function getId() {
2182 if ( $this->mId
=== null && $this->mName
!== null &&
2183 ( self
::isIP( $this->mName
) || ExternalUserNames
::isExternal( $this->mName
) )
2185 // Special case, we know the user is anonymous
2189 if ( !$this->isItemLoaded( 'id' ) ) {
2190 // Don't load if this was initialized from an ID
2194 return (int)$this->mId
;
2198 * Set the user and reload all fields according to a given ID
2199 * @param int $v User ID to reload
2201 public function setId( $v ) {
2203 $this->clearInstanceCache( 'id' );
2207 * Get the user name, or the IP of an anonymous user
2208 * @return string User's name or IP address
2210 public function getName() {
2211 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2212 // Special case optimisation
2213 return $this->mName
;
2217 if ( $this->mName
=== false ) {
2219 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2222 return $this->mName
;
2226 * Set the user name.
2228 * This does not reload fields from the database according to the given
2229 * name. Rather, it is used to create a temporary "nonexistent user" for
2230 * later addition to the database. It can also be used to set the IP
2231 * address for an anonymous user to something other than the current
2234 * @note User::newFromName() has roughly the same function, when the named user
2236 * @param string $str New user name to set
2238 public function setName( $str ) {
2240 $this->mName
= $str;
2244 * Get the user's actor ID.
2246 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2247 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2249 public function getActorId( IDatabase
$dbw = null ) {
2250 if ( !$this->isItemLoaded( 'actor' ) ) {
2254 if ( !$this->mActorId
&& $dbw ) {
2256 'actor_user' => $this->getId() ?
: null,
2257 'actor_name' => (string)$this->getName(),
2259 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2260 throw new CannotCreateActorException(
2261 'Cannot create an actor for a usable name that is not an existing user'
2264 if ( $q['actor_name'] === '' ) {
2265 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2267 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2268 if ( $dbw->affectedRows() ) {
2269 $this->mActorId
= (int)$dbw->insertId();
2272 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2273 $this->mActorId
= (int)$dbw->selectField(
2278 [ 'LOCK IN SHARE MODE' ]
2280 if ( !$this->mActorId
) {
2281 throw new CannotCreateActorException(
2282 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2286 $this->invalidateCache();
2287 $this->setItemLoaded( 'actor' );
2290 return (int)$this->mActorId
;
2294 * Get the user's name escaped by underscores.
2295 * @return string Username escaped by underscores.
2297 public function getTitleKey() {
2298 return str_replace( ' ', '_', $this->getName() );
2302 * Check if the user has new messages.
2303 * @return bool True if the user has new messages
2305 public function getNewtalk() {
2308 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2309 if ( $this->mNewtalk
=== -1 ) {
2310 $this->mNewtalk
= false; # reset talk page status
2312 // Check memcached separately for anons, who have no
2313 // entire User object stored in there.
2314 if ( !$this->mId
) {
2315 global $wgDisableAnonTalk;
2316 if ( $wgDisableAnonTalk ) {
2317 // Anon newtalk disabled by configuration.
2318 $this->mNewtalk
= false;
2320 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2323 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2327 return (bool)$this->mNewtalk
;
2331 * Return the data needed to construct links for new talk page message
2332 * alerts. If there are new messages, this will return an associative array
2333 * with the following data:
2334 * wiki: The database name of the wiki
2335 * link: Root-relative link to the user's talk page
2336 * rev: The last talk page revision that the user has seen or null. This
2337 * is useful for building diff links.
2338 * If there are no new messages, it returns an empty array.
2339 * @note This function was designed to accomodate multiple talk pages, but
2340 * currently only returns a single link and revision.
2343 public function getNewMessageLinks() {
2344 // Avoid PHP 7.1 warning of passing $this by reference
2347 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2351 if ( !$this->getNewtalk() ) {
2354 $utp = $this->getTalkPage();
2355 $dbr = wfGetDB( DB_REPLICA
);
2356 // Get the "last viewed rev" timestamp from the oldest message notification
2357 $timestamp = $dbr->selectField( 'user_newtalk',
2358 'MIN(user_last_timestamp)',
2359 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2361 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2364 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2365 'link' => $utp->getLocalURL(),
2372 * Get the revision ID for the last talk page revision viewed by the talk
2374 * @return int|null Revision ID or null
2376 public function getNewMessageRevisionId() {
2377 $newMessageRevisionId = null;
2378 $newMessageLinks = $this->getNewMessageLinks();
2380 // Note: getNewMessageLinks() never returns more than a single link
2381 // and it is always for the same wiki, but we double-check here in
2382 // case that changes some time in the future.
2383 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2384 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2385 && $newMessageLinks[0]['rev']
2387 /** @var Revision $newMessageRevision */
2388 $newMessageRevision = $newMessageLinks[0]['rev'];
2389 $newMessageRevisionId = $newMessageRevision->getId();
2392 return $newMessageRevisionId;
2396 * Internal uncached check for new messages
2399 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2400 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2401 * @return bool True if the user has new messages
2403 protected function checkNewtalk( $field, $id ) {
2404 $dbr = wfGetDB( DB_REPLICA
);
2406 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2408 return $ok !== false;
2412 * Add or update the new messages flag
2413 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2414 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2415 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2416 * @return bool True if successful, false otherwise
2418 protected function updateNewtalk( $field, $id, $curRev = null ) {
2419 // Get timestamp of the talk page revision prior to the current one
2420 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2421 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2422 // Mark the user as having new messages since this revision
2423 $dbw = wfGetDB( DB_MASTER
);
2424 $dbw->insert( 'user_newtalk',
2425 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2428 if ( $dbw->affectedRows() ) {
2429 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2433 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2438 * Clear the new messages flag for the given user
2439 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2440 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2441 * @return bool True if successful, false otherwise
2443 protected function deleteNewtalk( $field, $id ) {
2444 $dbw = wfGetDB( DB_MASTER
);
2445 $dbw->delete( 'user_newtalk',
2448 if ( $dbw->affectedRows() ) {
2449 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2453 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2458 * Update the 'You have new messages!' status.
2459 * @param bool $val Whether the user has new messages
2460 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2461 * page. Ignored if null or !$val.
2463 public function setNewtalk( $val, $curRev = null ) {
2464 if ( wfReadOnly() ) {
2469 $this->mNewtalk
= $val;
2471 if ( $this->isAnon() ) {
2473 $id = $this->getName();
2476 $id = $this->getId();
2480 $changed = $this->updateNewtalk( $field, $id, $curRev );
2482 $changed = $this->deleteNewtalk( $field, $id );
2486 $this->invalidateCache();
2491 * Generate a current or new-future timestamp to be stored in the
2492 * user_touched field when we update things.
2494 * @return string Timestamp in TS_MW format
2496 private function newTouchedTimestamp() {
2498 if ( $this->mTouched
) {
2499 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2502 return wfTimestamp( TS_MW
, $time );
2506 * Clear user data from memcached
2508 * Use after applying updates to the database; caller's
2509 * responsibility to update user_touched if appropriate.
2511 * Called implicitly from invalidateCache() and saveSettings().
2513 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2515 public function clearSharedCache( $mode = 'refresh' ) {
2516 if ( !$this->getId() ) {
2520 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2521 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2522 $key = $this->getCacheKey( $cache );
2524 if ( $mode === 'refresh' ) {
2525 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2527 $lb->getConnectionRef( DB_MASTER
)->onTransactionPreCommitOrIdle(
2528 function () use ( $cache, $key ) {
2529 $cache->delete( $key );
2537 * Immediately touch the user data cache for this account
2539 * Calls touch() and removes account data from memcached
2541 public function invalidateCache() {
2543 $this->clearSharedCache( 'changed' );
2547 * Update the "touched" timestamp for the user
2549 * This is useful on various login/logout events when making sure that
2550 * a browser or proxy that has multiple tenants does not suffer cache
2551 * pollution where the new user sees the old users content. The value
2552 * of getTouched() is checked when determining 304 vs 200 responses.
2553 * Unlike invalidateCache(), this preserves the User object cache and
2554 * avoids database writes.
2558 public function touch() {
2559 $id = $this->getId();
2561 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2562 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2563 $cache->touchCheckKey( $key );
2564 $this->mQuickTouched
= null;
2569 * Validate the cache for this account.
2570 * @param string $timestamp A timestamp in TS_MW format
2573 public function validateCache( $timestamp ) {
2574 return ( $timestamp >= $this->getTouched() );
2578 * Get the user touched timestamp
2580 * Use this value only to validate caches via inequalities
2581 * such as in the case of HTTP If-Modified-Since response logic
2583 * @return string TS_MW Timestamp
2585 public function getTouched() {
2589 if ( $this->mQuickTouched
=== null ) {
2590 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2591 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2593 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2596 return max( $this->mTouched
, $this->mQuickTouched
);
2599 return $this->mTouched
;
2603 * Get the user_touched timestamp field (time of last DB updates)
2604 * @return string TS_MW Timestamp
2607 public function getDBTouched() {
2610 return $this->mTouched
;
2614 * Set the password and reset the random token.
2615 * Calls through to authentication plugin if necessary;
2616 * will have no effect if the auth plugin refuses to
2617 * pass the change through or if the legal password
2620 * As a special case, setting the password to null
2621 * wipes it, so the account cannot be logged in until
2622 * a new password is set, for instance via e-mail.
2624 * @deprecated since 1.27, use AuthManager instead
2625 * @param string $str New password to set
2626 * @throws PasswordError On failure
2629 public function setPassword( $str ) {
2630 wfDeprecated( __METHOD__
, '1.27' );
2631 return $this->setPasswordInternal( $str );
2635 * Set the password and reset the random token unconditionally.
2637 * @deprecated since 1.27, use AuthManager instead
2638 * @param string|null $str New password to set or null to set an invalid
2639 * password hash meaning that the user will not be able to log in
2640 * through the web interface.
2642 public function setInternalPassword( $str ) {
2643 wfDeprecated( __METHOD__
, '1.27' );
2644 $this->setPasswordInternal( $str );
2648 * Actually set the password and such
2649 * @since 1.27 cannot set a password for a user not in the database
2650 * @param string|null $str New password to set or null to set an invalid
2651 * password hash meaning that the user will not be able to log in
2652 * through the web interface.
2653 * @return bool Success
2655 private function setPasswordInternal( $str ) {
2656 $manager = AuthManager
::singleton();
2658 // If the user doesn't exist yet, fail
2659 if ( !$manager->userExists( $this->getName() ) ) {
2660 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2663 $status = $this->changeAuthenticationData( [
2664 'username' => $this->getName(),
2668 if ( !$status->isGood() ) {
2669 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2670 ->info( __METHOD__
. ': Password change rejected: '
2671 . $status->getWikiText( null, null, 'en' ) );
2675 $this->setOption( 'watchlisttoken', false );
2676 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2682 * Changes credentials of the user.
2684 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2685 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2686 * e.g. when no provider handled the change.
2688 * @param array $data A set of authentication data in fieldname => value format. This is the
2689 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2693 public function changeAuthenticationData( array $data ) {
2694 $manager = AuthManager
::singleton();
2695 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2696 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2698 $status = Status
::newGood( 'ignored' );
2699 foreach ( $reqs as $req ) {
2700 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2702 if ( $status->getValue() === 'ignored' ) {
2703 $status->warning( 'authenticationdatachange-ignored' );
2706 if ( $status->isGood() ) {
2707 foreach ( $reqs as $req ) {
2708 $manager->changeAuthenticationData( $req );
2715 * Get the user's current token.
2716 * @param bool $forceCreation Force the generation of a new token if the
2717 * user doesn't have one (default=true for backwards compatibility).
2718 * @return string|null Token
2720 public function getToken( $forceCreation = true ) {
2721 global $wgAuthenticationTokenVersion;
2724 if ( !$this->mToken
&& $forceCreation ) {
2728 if ( !$this->mToken
) {
2729 // The user doesn't have a token, return null to indicate that.
2733 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2734 // We return a random value here so existing token checks are very
2736 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2739 if ( $wgAuthenticationTokenVersion === null ) {
2740 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2741 return $this->mToken
;
2744 // $wgAuthenticationTokenVersion in use, so hmac it.
2745 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2747 // The raw hash can be overly long. Shorten it up.
2748 $len = max( 32, self
::TOKEN_LENGTH
);
2749 if ( strlen( $ret ) < $len ) {
2750 // Should never happen, even md5 is 128 bits
2751 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2754 return substr( $ret, -$len );
2758 * Set the random token (used for persistent authentication)
2759 * Called from loadDefaults() among other places.
2761 * @param string|bool $token If specified, set the token to this value
2763 public function setToken( $token = false ) {
2765 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2766 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2767 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2768 } elseif ( !$token ) {
2769 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2771 $this->mToken
= $token;
2776 * Set the password for a password reminder or new account email
2778 * @deprecated Removed in 1.27. Use PasswordReset instead.
2779 * @param string $str New password to set or null to set an invalid
2780 * password hash meaning that the user will not be able to use it
2781 * @param bool $throttle If true, reset the throttle timestamp to the present
2783 public function setNewpassword( $str, $throttle = true ) {
2784 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2788 * Get the user's e-mail address
2789 * @return string User's email address
2791 public function getEmail() {
2793 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2794 return $this->mEmail
;
2798 * Get the timestamp of the user's e-mail authentication
2799 * @return string TS_MW timestamp
2801 public function getEmailAuthenticationTimestamp() {
2803 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2804 return $this->mEmailAuthenticated
;
2808 * Set the user's e-mail address
2809 * @param string $str New e-mail address
2811 public function setEmail( $str ) {
2813 if ( $str == $this->mEmail
) {
2816 $this->invalidateEmail();
2817 $this->mEmail
= $str;
2818 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2822 * Set the user's e-mail address and a confirmation mail if needed.
2825 * @param string $str New e-mail address
2828 public function setEmailWithConfirmation( $str ) {
2829 global $wgEnableEmail, $wgEmailAuthentication;
2831 if ( !$wgEnableEmail ) {
2832 return Status
::newFatal( 'emaildisabled' );
2835 $oldaddr = $this->getEmail();
2836 if ( $str === $oldaddr ) {
2837 return Status
::newGood( true );
2840 $type = $oldaddr != '' ?
'changed' : 'set';
2841 $notificationResult = null;
2843 if ( $wgEmailAuthentication && $type === 'changed' ) {
2844 // Send the user an email notifying the user of the change in registered
2845 // email address on their previous email address
2846 $change = $str != '' ?
'changed' : 'removed';
2847 $notificationResult = $this->sendMail(
2848 wfMessage( 'notificationemail_subject_' . $change )->text(),
2849 wfMessage( 'notificationemail_body_' . $change,
2850 $this->getRequest()->getIP(),
2856 $this->setEmail( $str );
2858 if ( $str !== '' && $wgEmailAuthentication ) {
2859 // Send a confirmation request to the new address if needed
2860 $result = $this->sendConfirmationMail( $type );
2862 if ( $notificationResult !== null ) {
2863 $result->merge( $notificationResult );
2866 if ( $result->isGood() ) {
2867 // Say to the caller that a confirmation and notification mail has been sent
2868 $result->value
= 'eauth';
2871 $result = Status
::newGood( true );
2878 * Get the user's real name
2879 * @return string User's real name
2881 public function getRealName() {
2882 if ( !$this->isItemLoaded( 'realname' ) ) {
2886 return $this->mRealName
;
2890 * Set the user's real name
2891 * @param string $str New real name
2893 public function setRealName( $str ) {
2895 $this->mRealName
= $str;
2899 * Get the user's current setting for a given option.
2901 * @param string $oname The option to check
2902 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2903 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2904 * @return string|array|int|null User's current value for the option
2905 * @see getBoolOption()
2906 * @see getIntOption()
2908 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2909 global $wgHiddenPrefs;
2910 $this->loadOptions();
2912 # We want 'disabled' preferences to always behave as the default value for
2913 # users, even if they have set the option explicitly in their settings (ie they
2914 # set it, and then it was disabled removing their ability to change it). But
2915 # we don't want to erase the preferences in the database in case the preference
2916 # is re-enabled again. So don't touch $mOptions, just override the returned value
2917 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2918 return self
::getDefaultOption( $oname );
2921 if ( array_key_exists( $oname, $this->mOptions
) ) {
2922 return $this->mOptions
[$oname];
2925 return $defaultOverride;
2929 * Get all user's options
2931 * @param int $flags Bitwise combination of:
2932 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2933 * to the default value. (Since 1.25)
2936 public function getOptions( $flags = 0 ) {
2937 global $wgHiddenPrefs;
2938 $this->loadOptions();
2939 $options = $this->mOptions
;
2941 # We want 'disabled' preferences to always behave as the default value for
2942 # users, even if they have set the option explicitly in their settings (ie they
2943 # set it, and then it was disabled removing their ability to change it). But
2944 # we don't want to erase the preferences in the database in case the preference
2945 # is re-enabled again. So don't touch $mOptions, just override the returned value
2946 foreach ( $wgHiddenPrefs as $pref ) {
2947 $default = self
::getDefaultOption( $pref );
2948 if ( $default !== null ) {
2949 $options[$pref] = $default;
2953 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2954 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2961 * Get the user's current setting for a given option, as a boolean value.
2963 * @param string $oname The option to check
2964 * @return bool User's current value for the option
2967 public function getBoolOption( $oname ) {
2968 return (bool)$this->getOption( $oname );
2972 * Get the user's current setting for a given option, as an integer value.
2974 * @param string $oname The option to check
2975 * @param int $defaultOverride A default value returned if the option does not exist
2976 * @return int User's current value for the option
2979 public function getIntOption( $oname, $defaultOverride = 0 ) {
2980 $val = $this->getOption( $oname );
2982 $val = $defaultOverride;
2984 return intval( $val );
2988 * Set the given option for a user.
2990 * You need to call saveSettings() to actually write to the database.
2992 * @param string $oname The option to set
2993 * @param mixed $val New value to set
2995 public function setOption( $oname, $val ) {
2996 $this->loadOptions();
2998 // Explicitly NULL values should refer to defaults
2999 if ( is_null( $val ) ) {
3000 $val = self
::getDefaultOption( $oname );
3003 $this->mOptions
[$oname] = $val;
3007 * Get a token stored in the preferences (like the watchlist one),
3008 * resetting it if it's empty (and saving changes).
3010 * @param string $oname The option name to retrieve the token from
3011 * @return string|bool User's current value for the option, or false if this option is disabled.
3012 * @see resetTokenFromOption()
3014 * @deprecated since 1.26 Applications should use the OAuth extension
3016 public function getTokenFromOption( $oname ) {
3017 global $wgHiddenPrefs;
3019 $id = $this->getId();
3020 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3024 $token = $this->getOption( $oname );
3026 // Default to a value based on the user token to avoid space
3027 // wasted on storing tokens for all users. When this option
3028 // is set manually by the user, only then is it stored.
3029 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3036 * Reset a token stored in the preferences (like the watchlist one).
3037 * *Does not* save user's preferences (similarly to setOption()).
3039 * @param string $oname The option name to reset the token in
3040 * @return string|bool New token value, or false if this option is disabled.
3041 * @see getTokenFromOption()
3044 public function resetTokenFromOption( $oname ) {
3045 global $wgHiddenPrefs;
3046 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3050 $token = MWCryptRand
::generateHex( 40 );
3051 $this->setOption( $oname, $token );
3056 * Return a list of the types of user options currently returned by
3057 * User::getOptionKinds().
3059 * Currently, the option kinds are:
3060 * - 'registered' - preferences which are registered in core MediaWiki or
3061 * by extensions using the UserGetDefaultOptions hook.
3062 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3063 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3064 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3065 * be used by user scripts.
3066 * - 'special' - "preferences" that are not accessible via User::getOptions
3067 * or User::setOptions.
3068 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3069 * These are usually legacy options, removed in newer versions.
3071 * The API (and possibly others) use this function to determine the possible
3072 * option types for validation purposes, so make sure to update this when a
3073 * new option kind is added.
3075 * @see User::getOptionKinds
3076 * @return array Option kinds
3078 public static function listOptionKinds() {
3081 'registered-multiselect',
3082 'registered-checkmatrix',
3090 * Return an associative array mapping preferences keys to the kind of a preference they're
3091 * used for. Different kinds are handled differently when setting or reading preferences.
3093 * See User::listOptionKinds for the list of valid option types that can be provided.
3095 * @see User::listOptionKinds
3096 * @param IContextSource $context
3097 * @param array|null $options Assoc. array with options keys to check as keys.
3098 * Defaults to $this->mOptions.
3099 * @return array The key => kind mapping data
3101 public function getOptionKinds( IContextSource
$context, $options = null ) {
3102 $this->loadOptions();
3103 if ( $options === null ) {
3104 $options = $this->mOptions
;
3107 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3108 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3111 // Pull out the "special" options, so they don't get converted as
3112 // multiselect or checkmatrix.
3113 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3114 foreach ( $specialOptions as $name => $value ) {
3115 unset( $prefs[$name] );
3118 // Multiselect and checkmatrix options are stored in the database with
3119 // one key per option, each having a boolean value. Extract those keys.
3120 $multiselectOptions = [];
3121 foreach ( $prefs as $name => $info ) {
3122 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3123 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3124 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3125 $prefix = $info['prefix'] ??
$name;
3127 foreach ( $opts as $value ) {
3128 $multiselectOptions["$prefix$value"] = true;
3131 unset( $prefs[$name] );
3134 $checkmatrixOptions = [];
3135 foreach ( $prefs as $name => $info ) {
3136 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3137 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3138 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3139 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3140 $prefix = $info['prefix'] ??
$name;
3142 foreach ( $columns as $column ) {
3143 foreach ( $rows as $row ) {
3144 $checkmatrixOptions["$prefix$column-$row"] = true;
3148 unset( $prefs[$name] );
3152 // $value is ignored
3153 foreach ( $options as $key => $value ) {
3154 if ( isset( $prefs[$key] ) ) {
3155 $mapping[$key] = 'registered';
3156 } elseif ( isset( $multiselectOptions[$key] ) ) {
3157 $mapping[$key] = 'registered-multiselect';
3158 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3159 $mapping[$key] = 'registered-checkmatrix';
3160 } elseif ( isset( $specialOptions[$key] ) ) {
3161 $mapping[$key] = 'special';
3162 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3163 $mapping[$key] = 'userjs';
3165 $mapping[$key] = 'unused';
3173 * Reset certain (or all) options to the site defaults
3175 * The optional parameter determines which kinds of preferences will be reset.
3176 * Supported values are everything that can be reported by getOptionKinds()
3177 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3179 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3180 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3181 * for backwards-compatibility.
3182 * @param IContextSource|null $context Context source used when $resetKinds
3183 * does not contain 'all', passed to getOptionKinds().
3184 * Defaults to RequestContext::getMain() when null.
3186 public function resetOptions(
3187 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3188 IContextSource
$context = null
3191 $defaultOptions = self
::getDefaultOptions();
3193 if ( !is_array( $resetKinds ) ) {
3194 $resetKinds = [ $resetKinds ];
3197 if ( in_array( 'all', $resetKinds ) ) {
3198 $newOptions = $defaultOptions;
3200 if ( $context === null ) {
3201 $context = RequestContext
::getMain();
3204 $optionKinds = $this->getOptionKinds( $context );
3205 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3208 // Use default values for the options that should be deleted, and
3209 // copy old values for the ones that shouldn't.
3210 foreach ( $this->mOptions
as $key => $value ) {
3211 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3212 if ( array_key_exists( $key, $defaultOptions ) ) {
3213 $newOptions[$key] = $defaultOptions[$key];
3216 $newOptions[$key] = $value;
3221 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3223 $this->mOptions
= $newOptions;
3224 $this->mOptionsLoaded
= true;
3228 * Get the user's preferred date format.
3229 * @return string User's preferred date format
3231 public function getDatePreference() {
3232 // Important migration for old data rows
3233 if ( is_null( $this->mDatePreference
) ) {
3235 $value = $this->getOption( 'date' );
3236 $map = $wgLang->getDatePreferenceMigrationMap();
3237 if ( isset( $map[$value] ) ) {
3238 $value = $map[$value];
3240 $this->mDatePreference
= $value;
3242 return $this->mDatePreference
;
3246 * Determine based on the wiki configuration and the user's options,
3247 * whether this user must be over HTTPS no matter what.
3251 public function requiresHTTPS() {
3252 global $wgSecureLogin;
3253 if ( !$wgSecureLogin ) {
3257 $https = $this->getBoolOption( 'prefershttps' );
3258 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3260 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3267 * Get the user preferred stub threshold
3271 public function getStubThreshold() {
3272 global $wgMaxArticleSize; # Maximum article size, in Kb
3273 $threshold = $this->getIntOption( 'stubthreshold' );
3274 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3275 // If they have set an impossible value, disable the preference
3276 // so we can use the parser cache again.
3283 * Get the permissions this user has.
3284 * @return string[] permission names
3286 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3287 * ->getUserPermissions(..) instead
3290 public function getRights() {
3291 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3295 * Get the list of explicit group memberships this user has.
3296 * The implicit * and user groups are not included.
3298 * @return string[] Array of internal group names (sorted since 1.33)
3300 public function getGroups() {
3302 $this->loadGroups();
3303 return array_keys( $this->mGroupMemberships
);
3307 * Get the list of explicit group memberships this user has, stored as
3308 * UserGroupMembership objects. Implicit groups are not included.
3310 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3313 public function getGroupMemberships() {
3315 $this->loadGroups();
3316 return $this->mGroupMemberships
;
3320 * Get the list of implicit group memberships this user has.
3321 * This includes all explicit groups, plus 'user' if logged in,
3322 * '*' for all accounts, and autopromoted groups
3323 * @param bool $recache Whether to avoid the cache
3324 * @return array Array of String internal group names
3326 public function getEffectiveGroups( $recache = false ) {
3327 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3328 $this->mEffectiveGroups
= array_unique( array_merge(
3329 $this->getGroups(), // explicit groups
3330 $this->getAutomaticGroups( $recache ) // implicit groups
3332 // Avoid PHP 7.1 warning of passing $this by reference
3334 // Hook for additional groups
3335 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3336 // Force reindexation of groups when a hook has unset one of them
3337 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3339 return $this->mEffectiveGroups
;
3343 * Get the list of implicit group memberships this user has.
3344 * This includes 'user' if logged in, '*' for all accounts,
3345 * and autopromoted groups
3346 * @param bool $recache Whether to avoid the cache
3347 * @return array Array of String internal group names
3349 public function getAutomaticGroups( $recache = false ) {
3350 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3351 $this->mImplicitGroups
= [ '*' ];
3352 if ( $this->getId() ) {
3353 $this->mImplicitGroups
[] = 'user';
3355 $this->mImplicitGroups
= array_unique( array_merge(
3356 $this->mImplicitGroups
,
3357 Autopromote
::getAutopromoteGroups( $this )
3361 // Assure data consistency with rights/groups,
3362 // as getEffectiveGroups() depends on this function
3363 $this->mEffectiveGroups
= null;
3366 return $this->mImplicitGroups
;
3370 * Returns the groups the user has belonged to.
3372 * The user may still belong to the returned groups. Compare with getGroups().
3374 * The function will not return groups the user had belonged to before MW 1.17
3376 * @return array Names of the groups the user has belonged to.
3378 public function getFormerGroups() {
3381 if ( is_null( $this->mFormerGroups
) ) {
3382 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3383 ?
wfGetDB( DB_MASTER
)
3384 : wfGetDB( DB_REPLICA
);
3385 $res = $db->select( 'user_former_groups',
3387 [ 'ufg_user' => $this->mId
],
3389 $this->mFormerGroups
= [];
3390 foreach ( $res as $row ) {
3391 $this->mFormerGroups
[] = $row->ufg_group
;
3395 return $this->mFormerGroups
;
3399 * Get the user's edit count.
3400 * @return int|null Null for anonymous users
3402 public function getEditCount() {
3403 if ( !$this->getId() ) {
3407 if ( $this->mEditCount
=== null ) {
3408 /* Populate the count, if it has not been populated yet */
3409 $dbr = wfGetDB( DB_REPLICA
);
3410 // check if the user_editcount field has been initialized
3411 $count = $dbr->selectField(
3412 'user', 'user_editcount',
3413 [ 'user_id' => $this->mId
],
3417 if ( $count === null ) {
3418 // it has not been initialized. do so.
3419 $count = $this->initEditCountInternal( $dbr );
3421 $this->mEditCount
= $count;
3423 return (int)$this->mEditCount
;
3427 * Add the user to the given group. This takes immediate effect.
3428 * If the user is already in the group, the expiry time will be updated to the new
3429 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3432 * @param string $group Name of the group to add
3433 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3434 * wfTimestamp(), or null if the group assignment should not expire
3437 public function addGroup( $group, $expiry = null ) {
3439 $this->loadGroups();
3442 $expiry = wfTimestamp( TS_MW
, $expiry );
3445 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3449 // create the new UserGroupMembership and put it in the DB
3450 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3451 if ( !$ugm->insert( true ) ) {
3455 $this->mGroupMemberships
[$group] = $ugm;
3457 // Refresh the groups caches, and clear the rights cache so it will be
3458 // refreshed on the next call to $this->getRights().
3459 $this->getEffectiveGroups( true );
3460 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3461 $this->invalidateCache();
3467 * Remove the user from the given group.
3468 * This takes immediate effect.
3469 * @param string $group Name of the group to remove
3472 public function removeGroup( $group ) {
3475 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3479 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3480 // delete the membership entry
3481 if ( !$ugm ||
!$ugm->delete() ) {
3485 $this->loadGroups();
3486 unset( $this->mGroupMemberships
[$group] );
3488 // Refresh the groups caches, and clear the rights cache so it will be
3489 // refreshed on the next call to $this->getRights().
3490 $this->getEffectiveGroups( true );
3491 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3492 $this->invalidateCache();
3498 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3499 * only this new name and not the old isLoggedIn() variant.
3501 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3502 * anonymous or has no local account (which can happen when importing). This is equivalent to
3503 * getId() != 0 and is provided for code readability.
3506 public function isRegistered() {
3507 return $this->getId() != 0;
3511 * Get whether the user is logged in
3514 public function isLoggedIn() {
3515 return $this->isRegistered();
3519 * Get whether the user is anonymous
3522 public function isAnon() {
3523 return !$this->isRegistered();
3527 * @return bool Whether this user is flagged as being a bot role account
3530 public function isBot() {
3531 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3536 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3542 * Check if user is allowed to access a feature / make an action
3544 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3545 * ->getPermissionManager()->userHasAnyRights(...) instead
3547 * @param string $permissions,... Permissions to test
3548 * @return bool True if user is allowed to perform *any* of the given actions
3549 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3551 public function isAllowedAny() {
3552 return MediaWikiServices
::getInstance()
3553 ->getPermissionManager()
3554 ->userHasAnyRight( $this, ...func_get_args() );
3558 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3559 * ->getPermissionManager()->userHasAllRights(...) instead
3560 * @param string $permissions,... Permissions to test
3561 * @return bool True if the user is allowed to perform *all* of the given actions
3562 * @suppress PhanCommentParamOnEmptyParamList Cannot make variadic due to HHVM bug, T191668#5263929
3564 public function isAllowedAll() {
3565 return MediaWikiServices
::getInstance()
3566 ->getPermissionManager()
3567 ->userHasAllRights( $this, ...func_get_args() );
3571 * Internal mechanics of testing a permission
3573 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3574 * ->getPermissionManager()->userHasRight(...) instead
3576 * @param string $action
3580 public function isAllowed( $action = '' ) {
3581 return MediaWikiServices
::getInstance()->getPermissionManager()
3582 ->userHasRight( $this, $action );
3586 * Check whether to enable recent changes patrol features for this user
3587 * @return bool True or false
3589 public function useRCPatrol() {
3590 global $wgUseRCPatrol;
3591 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3595 * Check whether to enable new pages patrol features for this user
3596 * @return bool True or false
3598 public function useNPPatrol() {
3599 global $wgUseRCPatrol, $wgUseNPPatrol;
3601 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3602 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3607 * Check whether to enable new files patrol features for this user
3608 * @return bool True or false
3610 public function useFilePatrol() {
3611 global $wgUseRCPatrol, $wgUseFilePatrol;
3613 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3614 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3619 * Get the WebRequest object to use with this object
3621 * @return WebRequest
3623 public function getRequest() {
3624 if ( $this->mRequest
) {
3625 return $this->mRequest
;
3633 * Check the watched status of an article.
3634 * @since 1.22 $checkRights parameter added
3635 * @param Title $title Title of the article to look at
3636 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3637 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3640 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3641 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3642 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3649 * @since 1.22 $checkRights parameter added
3650 * @param Title $title Title of the article to look at
3651 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3652 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3654 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3655 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3656 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3658 [ $title->getSubjectPage(), $title->getTalkPage() ]
3661 $this->invalidateCache();
3665 * Stop watching an article.
3666 * @since 1.22 $checkRights parameter added
3667 * @param Title $title Title of the article to look at
3668 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3669 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3671 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3672 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3673 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3674 $store->removeWatch( $this, $title->getSubjectPage() );
3675 $store->removeWatch( $this, $title->getTalkPage() );
3677 $this->invalidateCache();
3681 * Clear the user's notification timestamp for the given title.
3682 * If e-notif e-mails are on, they will receive notification mails on
3683 * the next change of the page if it's watched etc.
3684 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3685 * @param Title &$title Title of the article to look at
3686 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3688 public function clearNotification( &$title, $oldid = 0 ) {
3689 global $wgUseEnotif, $wgShowUpdatedMarker;
3691 // Do nothing if the database is locked to writes
3692 if ( wfReadOnly() ) {
3696 // Do nothing if not allowed to edit the watchlist
3697 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3701 // If we're working on user's talk page, we should update the talk page message indicator
3702 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3703 // Avoid PHP 7.1 warning of passing $this by reference
3705 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3709 // Try to update the DB post-send and only if needed...
3710 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3711 if ( !$this->getNewtalk() ) {
3712 return; // no notifications to clear
3715 // Delete the last notifications (they stack up)
3716 $this->setNewtalk( false );
3718 // If there is a new, unseen, revision, use its timestamp
3720 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3723 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3728 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3732 if ( $this->isAnon() ) {
3733 // Nothing else to do...
3737 // Only update the timestamp if the page is being watched.
3738 // The query to find out if it is watched is cached both in memcached and per-invocation,
3739 // and when it does have to be executed, it can be on a replica DB
3740 // If this is the user's newtalk page, we always update the timestamp
3742 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3746 MediaWikiServices
::getInstance()->getWatchedItemStore()
3747 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3751 * Resets all of the given user's page-change notification timestamps.
3752 * If e-notif e-mails are on, they will receive notification mails on
3753 * the next change of any watched page.
3754 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3756 public function clearAllNotifications() {
3757 global $wgUseEnotif, $wgShowUpdatedMarker;
3758 // Do nothing if not allowed to edit the watchlist
3759 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3763 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3764 $this->setNewtalk( false );
3768 $id = $this->getId();
3773 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3774 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3776 // We also need to clear here the "you have new message" notification for the own
3777 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3781 * Compute experienced level based on edit count and registration date.
3783 * @return string 'newcomer', 'learner', or 'experienced'
3785 public function getExperienceLevel() {
3786 global $wgLearnerEdits,
3787 $wgExperiencedUserEdits,
3788 $wgLearnerMemberSince,
3789 $wgExperiencedUserMemberSince;
3791 if ( $this->isAnon() ) {
3795 $editCount = $this->getEditCount();
3796 $registration = $this->getRegistration();
3798 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3799 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3801 if ( $editCount < $wgLearnerEdits ||
3802 $registration > $learnerRegistration ) {
3806 if ( $editCount > $wgExperiencedUserEdits &&
3807 $registration <= $experiencedRegistration
3809 return 'experienced';
3816 * Persist this user's session (e.g. set cookies)
3818 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3820 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3821 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3823 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3825 if ( $this->mId
== 0 ) {
3829 $session = $this->getRequest()->getSession();
3830 if ( $request && $session->getRequest() !== $request ) {
3831 $session = $session->sessionWithRequest( $request );
3833 $delay = $session->delaySave();
3835 if ( !$session->getUser()->equals( $this ) ) {
3836 if ( !$session->canSetUser() ) {
3837 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3838 ->warning( __METHOD__
.
3839 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3843 $session->setUser( $this );
3846 $session->setRememberUser( $rememberMe );
3847 if ( $secure !== null ) {
3848 $session->setForceHTTPS( $secure );
3851 $session->persist();
3853 ScopedCallback
::consume( $delay );
3857 * Log this user out.
3859 public function logout() {
3860 // Avoid PHP 7.1 warning of passing $this by reference
3862 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3868 * Clear the user's session, and reset the instance cache.
3871 public function doLogout() {
3872 $session = $this->getRequest()->getSession();
3873 if ( !$session->canSetUser() ) {
3874 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3875 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3876 $error = 'immutable';
3877 } elseif ( !$session->getUser()->equals( $this ) ) {
3878 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3879 ->warning( __METHOD__
.
3880 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3882 // But we still may as well make this user object anon
3883 $this->clearInstanceCache( 'defaults' );
3884 $error = 'wronguser';
3886 $this->clearInstanceCache( 'defaults' );
3887 $delay = $session->delaySave();
3888 $session->unpersist(); // Clear cookies (T127436)
3889 $session->setLoggedOutTimestamp( time() );
3890 $session->setUser( new User
);
3891 $session->set( 'wsUserID', 0 ); // Other code expects this
3892 $session->resetAllTokens();
3893 ScopedCallback
::consume( $delay );
3896 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3897 'event' => 'logout',
3898 'successful' => $error === false,
3899 'status' => $error ?
: 'success',
3904 * Save this user's settings into the database.
3905 * @todo Only rarely do all these fields need to be set!
3907 public function saveSettings() {
3908 if ( wfReadOnly() ) {
3909 // @TODO: caller should deal with this instead!
3910 // This should really just be an exception.
3911 MWExceptionHandler
::logException( new DBExpectedError(
3913 "Could not update user with ID '{$this->mId}'; DB is read-only."
3919 if ( $this->mId
== 0 ) {
3923 // Get a new user_touched that is higher than the old one.
3924 // This will be used for a CAS check as a last-resort safety
3925 // check against race conditions and replica DB lag.
3926 $newTouched = $this->newTouchedTimestamp();
3928 $dbw = wfGetDB( DB_MASTER
);
3929 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3930 $dbw->update( 'user',
3932 'user_name' => $this->mName
,
3933 'user_real_name' => $this->mRealName
,
3934 'user_email' => $this->mEmail
,
3935 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3936 'user_touched' => $dbw->timestamp( $newTouched ),
3937 'user_token' => strval( $this->mToken
),
3938 'user_email_token' => $this->mEmailToken
,
3939 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3940 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3941 'user_id' => $this->mId
,
3945 if ( !$dbw->affectedRows() ) {
3946 // Maybe the problem was a missed cache update; clear it to be safe
3947 $this->clearSharedCache( 'refresh' );
3948 // User was changed in the meantime or loaded with stale data
3949 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3950 LoggerFactory
::getInstance( 'preferences' )->warning(
3951 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
3952 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
3954 throw new MWException( "CAS update failed on user_touched. " .
3955 "The version of the user to be saved is older than the current version."
3961 [ 'actor_name' => $this->mName
],
3962 [ 'actor_user' => $this->mId
],
3967 $this->mTouched
= $newTouched;
3968 $this->saveOptions();
3970 Hooks
::run( 'UserSaveSettings', [ $this ] );
3971 $this->clearSharedCache( 'changed' );
3972 $this->getUserPage()->purgeSquid();
3976 * If only this user's username is known, and it exists, return the user ID.
3978 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3981 public function idForName( $flags = 0 ) {
3982 $s = trim( $this->getName() );
3987 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3988 ?
wfGetDB( DB_MASTER
)
3989 : wfGetDB( DB_REPLICA
);
3991 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3992 ?
[ 'LOCK IN SHARE MODE' ]
3995 $id = $db->selectField( 'user',
3996 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4002 * Add a user to the database, return the user object
4004 * @param string $name Username to add
4005 * @param array $params Array of Strings Non-default parameters to save to
4006 * the database as user_* fields:
4007 * - email: The user's email address.
4008 * - email_authenticated: The email authentication timestamp.
4009 * - real_name: The user's real name.
4010 * - options: An associative array of non-default options.
4011 * - token: Random authentication token. Do not set.
4012 * - registration: Registration timestamp. Do not set.
4014 * @return User|null User object, or null if the username already exists.
4016 public static function createNew( $name, $params = [] ) {
4017 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4018 if ( isset( $params[$field] ) ) {
4019 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4020 unset( $params[$field] );
4026 $user->setToken(); // init token
4027 if ( isset( $params['options'] ) ) {
4028 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4029 unset( $params['options'] );
4031 $dbw = wfGetDB( DB_MASTER
);
4033 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4036 'user_name' => $name,
4037 'user_password' => $noPass,
4038 'user_newpassword' => $noPass,
4039 'user_email' => $user->mEmail
,
4040 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4041 'user_real_name' => $user->mRealName
,
4042 'user_token' => strval( $user->mToken
),
4043 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4044 'user_editcount' => 0,
4045 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4047 foreach ( $params as $name => $value ) {
4048 $fields["user_$name"] = $value;
4051 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4052 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4053 if ( $dbw->affectedRows() ) {
4054 $newUser = self
::newFromId( $dbw->insertId() );
4055 $newUser->mName
= $fields['user_name'];
4056 $newUser->updateActorId( $dbw );
4057 // Load the user from master to avoid replica lag
4058 $newUser->load( self
::READ_LATEST
);
4067 * Add this existing user object to the database. If the user already
4068 * exists, a fatal status object is returned, and the user object is
4069 * initialised with the data from the database.
4071 * Previously, this function generated a DB error due to a key conflict
4072 * if the user already existed. Many extension callers use this function
4073 * in code along the lines of:
4075 * $user = User::newFromName( $name );
4076 * if ( !$user->isLoggedIn() ) {
4077 * $user->addToDatabase();
4079 * // do something with $user...
4081 * However, this was vulnerable to a race condition (T18020). By
4082 * initialising the user object if the user exists, we aim to support this
4083 * calling sequence as far as possible.
4085 * Note that if the user exists, this function will acquire a write lock,
4086 * so it is still advisable to make the call conditional on isLoggedIn(),
4087 * and to commit the transaction after calling.
4089 * @throws MWException
4092 public function addToDatabase() {
4094 if ( !$this->mToken
) {
4095 $this->setToken(); // init token
4098 if ( !is_string( $this->mName
) ) {
4099 throw new RuntimeException( "User name field is not set." );
4102 $this->mTouched
= $this->newTouchedTimestamp();
4104 $dbw = wfGetDB( DB_MASTER
);
4105 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4106 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4107 $dbw->insert( 'user',
4109 'user_name' => $this->mName
,
4110 'user_password' => $noPass,
4111 'user_newpassword' => $noPass,
4112 'user_email' => $this->mEmail
,
4113 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4114 'user_real_name' => $this->mRealName
,
4115 'user_token' => strval( $this->mToken
),
4116 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4117 'user_editcount' => 0,
4118 'user_touched' => $dbw->timestamp( $this->mTouched
),
4122 if ( !$dbw->affectedRows() ) {
4123 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4124 $this->mId
= $dbw->selectField(
4127 [ 'user_name' => $this->mName
],
4129 [ 'LOCK IN SHARE MODE' ]
4132 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4136 throw new MWException( $fname . ": hit a key conflict attempting " .
4137 "to insert user '{$this->mName}' row, but it was not present in select!" );
4139 return Status
::newFatal( 'userexists' );
4141 $this->mId
= $dbw->insertId();
4142 self
::$idCacheByName[$this->mName
] = $this->mId
;
4143 $this->updateActorId( $dbw );
4145 return Status
::newGood();
4147 if ( !$status->isGood() ) {
4151 // Clear instance cache other than user table data and actor, which is already accurate
4152 $this->clearInstanceCache();
4154 $this->saveOptions();
4155 return Status
::newGood();
4159 * Update the actor ID after an insert
4160 * @param IDatabase $dbw Writable database handle
4162 private function updateActorId( IDatabase
$dbw ) {
4165 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4168 $this->mActorId
= (int)$dbw->insertId();
4172 * If this user is logged-in and blocked,
4173 * block any IP address they've successfully logged in from.
4174 * @return bool A block was spread
4176 public function spreadAnyEditBlock() {
4177 if ( $this->isLoggedIn() && $this->getBlock() ) {
4178 return $this->spreadBlock();
4185 * If this (non-anonymous) user is blocked,
4186 * block the IP address they've successfully logged in from.
4187 * @return bool A block was spread
4189 protected function spreadBlock() {
4190 wfDebug( __METHOD__
. "()\n" );
4192 if ( $this->mId
== 0 ) {
4196 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4197 if ( !$userblock ) {
4201 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4205 * Get whether the user is explicitly blocked from account creation.
4206 * @return bool|AbstractBlock
4208 public function isBlockedFromCreateAccount() {
4209 $this->getBlockedStatus();
4210 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4211 return $this->mBlock
;
4214 # T15611: if the IP address the user is trying to create an account from is
4215 # blocked with createaccount disabled, prevent new account creation there even
4216 # when the user is logged in
4217 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4218 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4219 null, $this->getRequest()->getIP()
4222 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4223 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4224 ?
$this->mBlockedFromCreateAccount
4229 * Get whether the user is blocked from using Special:Emailuser.
4232 public function isBlockedFromEmailuser() {
4233 $this->getBlockedStatus();
4234 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4238 * Get whether the user is blocked from using Special:Upload
4243 public function isBlockedFromUpload() {
4244 $this->getBlockedStatus();
4245 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4249 * Get whether the user is allowed to create an account.
4252 public function isAllowedToCreateAccount() {
4253 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4257 * Get this user's personal page title.
4259 * @return Title User's personal page title
4261 public function getUserPage() {
4262 return Title
::makeTitle( NS_USER
, $this->getName() );
4266 * Get this user's talk page title.
4268 * @return Title User's talk page title
4270 public function getTalkPage() {
4271 $title = $this->getUserPage();
4272 return $title->getTalkPage();
4276 * Determine whether the user is a newbie. Newbies are either
4277 * anonymous IPs, or the most recently created accounts.
4280 public function isNewbie() {
4281 return !$this->isAllowed( 'autoconfirmed' );
4285 * Check to see if the given clear-text password is one of the accepted passwords
4286 * @deprecated since 1.27, use AuthManager instead
4287 * @param string $password User password
4288 * @return bool True if the given password is correct, otherwise False
4290 public function checkPassword( $password ) {
4291 wfDeprecated( __METHOD__
, '1.27' );
4293 $manager = AuthManager
::singleton();
4294 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4295 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4297 'username' => $this->getName(),
4298 'password' => $password,
4301 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4302 switch ( $res->status
) {
4303 case AuthenticationResponse
::PASS
:
4305 case AuthenticationResponse
::FAIL
:
4306 // Hope it's not a PreAuthenticationProvider that failed...
4307 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4308 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4311 throw new BadMethodCallException(
4312 'AuthManager returned a response unsupported by ' . __METHOD__
4318 * Check if the given clear-text password matches the temporary password
4319 * sent by e-mail for password reset operations.
4321 * @deprecated since 1.27, use AuthManager instead
4322 * @param string $plaintext
4323 * @return bool True if matches, false otherwise
4325 public function checkTemporaryPassword( $plaintext ) {
4326 wfDeprecated( __METHOD__
, '1.27' );
4327 // Can't check the temporary password individually.
4328 return $this->checkPassword( $plaintext );
4332 * Initialize (if necessary) and return a session token value
4333 * which can be used in edit forms to show that the user's
4334 * login credentials aren't being hijacked with a foreign form
4338 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4339 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4340 * @return MediaWiki\Session\Token The new edit token
4342 public function getEditTokenObject( $salt = '', $request = null ) {
4343 if ( $this->isAnon() ) {
4344 return new LoggedOutEditToken();
4348 $request = $this->getRequest();
4350 return $request->getSession()->getToken( $salt );
4354 * Initialize (if necessary) and return a session token value
4355 * which can be used in edit forms to show that the user's
4356 * login credentials aren't being hijacked with a foreign form
4359 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4362 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4363 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4364 * @return string The new edit token
4366 public function getEditToken( $salt = '', $request = null ) {
4367 return $this->getEditTokenObject( $salt, $request )->toString();
4371 * Check given value against the token value stored in the session.
4372 * A match should confirm that the form was submitted from the
4373 * user's own login session, not a form submission from a third-party
4376 * @param string $val Input value to compare
4377 * @param string|array $salt Optional function-specific data for hashing
4378 * @param WebRequest|null $request Object to use or null to use $wgRequest
4379 * @param int|null $maxage Fail tokens older than this, in seconds
4380 * @return bool Whether the token matches
4382 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4383 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4387 * Check given value against the token value stored in the session,
4388 * ignoring the suffix.
4390 * @param string $val Input value to compare
4391 * @param string|array $salt Optional function-specific data for hashing
4392 * @param WebRequest|null $request Object to use or null to use $wgRequest
4393 * @param int|null $maxage Fail tokens older than this, in seconds
4394 * @return bool Whether the token matches
4396 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4397 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4398 return $this->matchEditToken( $val, $salt, $request, $maxage );
4402 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4403 * mail to the user's given address.
4405 * @param string $type Message to send, either "created", "changed" or "set"
4408 public function sendConfirmationMail( $type = 'created' ) {
4410 $expiration = null; // gets passed-by-ref and defined in next line.
4411 $token = $this->confirmationToken( $expiration );
4412 $url = $this->confirmationTokenUrl( $token );
4413 $invalidateURL = $this->invalidationTokenUrl( $token );
4414 $this->saveSettings();
4416 if ( $type == 'created' ||
$type === false ) {
4417 $message = 'confirmemail_body';
4419 } elseif ( $type === true ) {
4420 $message = 'confirmemail_body_changed';
4423 // Messages: confirmemail_body_changed, confirmemail_body_set
4424 $message = 'confirmemail_body_' . $type;
4428 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4429 'body' => wfMessage( $message,
4430 $this->getRequest()->getIP(),
4433 $wgLang->userTimeAndDate( $expiration, $this ),
4435 $wgLang->userDate( $expiration, $this ),
4436 $wgLang->userTime( $expiration, $this ) )->text(),
4442 'ip' => $this->getRequest()->getIP(),
4443 'confirmURL' => $url,
4444 'invalidateURL' => $invalidateURL,
4445 'expiration' => $expiration
4448 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4449 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4453 * Send an e-mail to this user's account. Does not check for
4454 * confirmed status or validity.
4456 * @param string $subject Message subject
4457 * @param string $body Message body
4458 * @param User|null $from Optional sending user; if unspecified, default
4459 * $wgPasswordSender will be used.
4460 * @param MailAddress|null $replyto Reply-To address
4463 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4464 global $wgPasswordSender;
4466 if ( $from instanceof User
) {
4467 $sender = MailAddress
::newFromUser( $from );
4469 $sender = new MailAddress( $wgPasswordSender,
4470 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4472 $to = MailAddress
::newFromUser( $this );
4474 return UserMailer
::send( $to, $sender, $subject, $body, [
4475 'replyTo' => $replyto,
4480 * Generate, store, and return a new e-mail confirmation code.
4481 * A hash (unsalted, since it's used as a key) is stored.
4483 * @note Call saveSettings() after calling this function to commit
4484 * this change to the database.
4486 * @param string &$expiration Accepts the expiration time
4487 * @return string New token
4489 protected function confirmationToken( &$expiration ) {
4490 global $wgUserEmailConfirmationTokenExpiry;
4492 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4493 $expiration = wfTimestamp( TS_MW
, $expires );
4495 $token = MWCryptRand
::generateHex( 32 );
4496 $hash = md5( $token );
4497 $this->mEmailToken
= $hash;
4498 $this->mEmailTokenExpires
= $expiration;
4503 * Return a URL the user can use to confirm their email address.
4504 * @param string $token Accepts the email confirmation token
4505 * @return string New token URL
4507 protected function confirmationTokenUrl( $token ) {
4508 return $this->getTokenUrl( 'ConfirmEmail', $token );
4512 * Return a URL the user can use to invalidate their email address.
4513 * @param string $token Accepts the email confirmation token
4514 * @return string New token URL
4516 protected function invalidationTokenUrl( $token ) {
4517 return $this->getTokenUrl( 'InvalidateEmail', $token );
4521 * Internal function to format the e-mail validation/invalidation URLs.
4522 * This uses a quickie hack to use the
4523 * hardcoded English names of the Special: pages, for ASCII safety.
4525 * @note Since these URLs get dropped directly into emails, using the
4526 * short English names avoids insanely long URL-encoded links, which
4527 * also sometimes can get corrupted in some browsers/mailers
4528 * (T8957 with Gmail and Internet Explorer).
4530 * @param string $page Special page
4531 * @param string $token
4532 * @return string Formatted URL
4534 protected function getTokenUrl( $page, $token ) {
4535 // Hack to bypass localization of 'Special:'
4536 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4537 return $title->getCanonicalURL();
4541 * Mark the e-mail address confirmed.
4543 * @note Call saveSettings() after calling this function to commit the change.
4547 public function confirmEmail() {
4548 // Check if it's already confirmed, so we don't touch the database
4549 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4550 if ( !$this->isEmailConfirmed() ) {
4551 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4552 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4558 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4559 * address if it was already confirmed.
4561 * @note Call saveSettings() after calling this function to commit the change.
4562 * @return bool Returns true
4564 public function invalidateEmail() {
4566 $this->mEmailToken
= null;
4567 $this->mEmailTokenExpires
= null;
4568 $this->setEmailAuthenticationTimestamp( null );
4570 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4575 * Set the e-mail authentication timestamp.
4576 * @param string $timestamp TS_MW timestamp
4578 public function setEmailAuthenticationTimestamp( $timestamp ) {
4580 $this->mEmailAuthenticated
= $timestamp;
4581 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4585 * Is this user allowed to send e-mails within limits of current
4586 * site configuration?
4589 public function canSendEmail() {
4590 global $wgEnableEmail, $wgEnableUserEmail;
4591 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4594 $canSend = $this->isEmailConfirmed();
4595 // Avoid PHP 7.1 warning of passing $this by reference
4597 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4602 * Is this user allowed to receive e-mails within limits of current
4603 * site configuration?
4606 public function canReceiveEmail() {
4607 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4611 * Is this user's e-mail address valid-looking and confirmed within
4612 * limits of the current site configuration?
4614 * @note If $wgEmailAuthentication is on, this may require the user to have
4615 * confirmed their address by returning a code or using a password
4616 * sent to the address from the wiki.
4620 public function isEmailConfirmed() {
4621 global $wgEmailAuthentication;
4623 // Avoid PHP 7.1 warning of passing $this by reference
4626 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4627 if ( $this->isAnon() ) {
4630 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4633 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4643 * Check whether there is an outstanding request for e-mail confirmation.
4646 public function isEmailConfirmationPending() {
4647 global $wgEmailAuthentication;
4648 return $wgEmailAuthentication &&
4649 !$this->isEmailConfirmed() &&
4650 $this->mEmailToken
&&
4651 $this->mEmailTokenExpires
> wfTimestamp();
4655 * Get the timestamp of account creation.
4657 * @return string|bool|null Timestamp of account creation, false for
4658 * non-existent/anonymous user accounts, or null if existing account
4659 * but information is not in database.
4661 public function getRegistration() {
4662 if ( $this->isAnon() ) {
4666 return $this->mRegistration
;
4670 * Get the timestamp of the first edit
4672 * @return string|bool Timestamp of first edit, or false for
4673 * non-existent/anonymous user accounts.
4675 public function getFirstEditTimestamp() {
4676 return $this->getEditTimestamp( true );
4680 * Get the timestamp of the latest edit
4683 * @return string|bool Timestamp of first edit, or false for
4684 * non-existent/anonymous user accounts.
4686 public function getLatestEditTimestamp() {
4687 return $this->getEditTimestamp( false );
4691 * Get the timestamp of the first or latest edit
4693 * @param bool $first True for the first edit, false for the latest one
4694 * @return string|bool Timestamp of first or latest edit, or false for
4695 * non-existent/anonymous user accounts.
4697 private function getEditTimestamp( $first ) {
4698 if ( $this->getId() == 0 ) {
4699 return false; // anons
4701 $dbr = wfGetDB( DB_REPLICA
);
4702 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4703 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4704 ?
'revactor_timestamp' : 'rev_timestamp';
4705 $sortOrder = $first ?
'ASC' : 'DESC';
4706 $time = $dbr->selectField(
4707 [ 'revision' ] +
$actorWhere['tables'],
4709 [ $actorWhere['conds'] ],
4711 [ 'ORDER BY' => "$tsField $sortOrder" ],
4712 $actorWhere['joins']
4715 return false; // no edits
4717 return wfTimestamp( TS_MW
, $time );
4721 * Get the permissions associated with a given list of groups
4723 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4724 * ->getGroupPermissions() instead
4726 * @param array $groups Array of Strings List of internal group names
4727 * @return array Array of Strings List of permission key names for given groups combined
4729 public static function getGroupPermissions( $groups ) {
4730 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4734 * Get all the groups who have a given permission
4736 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4737 * ->getGroupsWithPermission() instead
4739 * @param string $role Role to check
4740 * @return array Array of Strings List of internal group names with the given permission
4742 public static function getGroupsWithPermission( $role ) {
4743 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4747 * Check, if the given group has the given permission
4749 * If you're wanting to check whether all users have a permission, use
4750 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4753 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4754 * ->groupHasPermission(..) instead
4757 * @param string $group Group to check
4758 * @param string $role Role to check
4761 public static function groupHasPermission( $group, $role ) {
4762 return MediaWikiServices
::getInstance()->getPermissionManager()
4763 ->groupHasPermission( $group, $role );
4767 * Check if all users may be assumed to have the given permission
4769 * We generally assume so if the right is granted to '*' and isn't revoked
4770 * on any group. It doesn't attempt to take grants or other extension
4771 * limitations on rights into account in the general case, though, as that
4772 * would require it to always return false and defeat the purpose.
4773 * Specifically, session-based rights restrictions (such as OAuth or bot
4774 * passwords) are applied based on the current session.
4776 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4777 * ->isEveryoneAllowed() instead
4779 * @param string $right Right to check
4784 public static function isEveryoneAllowed( $right ) {
4785 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4789 * Return the set of defined explicit groups.
4790 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4791 * are not included, as they are defined automatically, not in the database.
4792 * @return array Array of internal group names
4794 public static function getAllGroups() {
4795 global $wgGroupPermissions, $wgRevokePermissions;
4796 return array_values( array_diff(
4797 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4798 self
::getImplicitGroups()
4803 * Get a list of all available permissions.
4805 * @deprecated since 1.34, use PermissionManager::getAllPermissions() instead
4807 * @return string[] Array of permission names
4809 public static function getAllRights() {
4810 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4814 * Get a list of implicit groups
4815 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4817 * @return array Array of Strings Array of internal group names
4819 public static function getImplicitGroups() {
4820 global $wgImplicitGroups;
4821 return $wgImplicitGroups;
4825 * Returns an array of the groups that a particular group can add/remove.
4827 * @param string $group The group to check for whether it can add/remove
4828 * @return array [ 'add' => [ addablegroups ],
4829 * 'remove' => [ removablegroups ],
4830 * 'add-self' => [ addablegroups to self ],
4831 * 'remove-self' => [ removable groups from self ] ]
4833 public static function changeableByGroup( $group ) {
4834 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4843 if ( empty( $wgAddGroups[$group] ) ) {
4844 // Don't add anything to $groups
4845 } elseif ( $wgAddGroups[$group] === true ) {
4846 // You get everything
4847 $groups['add'] = self
::getAllGroups();
4848 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4849 $groups['add'] = $wgAddGroups[$group];
4852 // Same thing for remove
4853 if ( empty( $wgRemoveGroups[$group] ) ) {
4855 } elseif ( $wgRemoveGroups[$group] === true ) {
4856 $groups['remove'] = self
::getAllGroups();
4857 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4858 $groups['remove'] = $wgRemoveGroups[$group];
4861 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4862 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4863 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4864 if ( is_int( $key ) ) {
4865 $wgGroupsAddToSelf['user'][] = $value;
4870 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4871 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4872 if ( is_int( $key ) ) {
4873 $wgGroupsRemoveFromSelf['user'][] = $value;
4878 // Now figure out what groups the user can add to him/herself
4879 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4881 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4882 // No idea WHY this would be used, but it's there
4883 $groups['add-self'] = self
::getAllGroups();
4884 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4885 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4888 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4890 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4891 $groups['remove-self'] = self
::getAllGroups();
4892 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4893 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4900 * Returns an array of groups that this user can add and remove
4901 * @return array [ 'add' => [ addablegroups ],
4902 * 'remove' => [ removablegroups ],
4903 * 'add-self' => [ addablegroups to self ],
4904 * 'remove-self' => [ removable groups from self ] ]
4906 public function changeableGroups() {
4907 if ( $this->isAllowed( 'userrights' ) ) {
4908 // This group gives the right to modify everything (reverse-
4909 // compatibility with old "userrights lets you change
4911 // Using array_merge to make the groups reindexed
4912 $all = array_merge( self
::getAllGroups() );
4921 // Okay, it's not so simple, we will have to go through the arrays
4928 $addergroups = $this->getEffectiveGroups();
4930 foreach ( $addergroups as $addergroup ) {
4931 $groups = array_merge_recursive(
4932 $groups, $this->changeableByGroup( $addergroup )
4934 $groups['add'] = array_unique( $groups['add'] );
4935 $groups['remove'] = array_unique( $groups['remove'] );
4936 $groups['add-self'] = array_unique( $groups['add-self'] );
4937 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4943 * Schedule a deferred update to update the user's edit count
4945 public function incEditCount() {
4946 if ( $this->isAnon() ) {
4950 DeferredUpdates
::addUpdate(
4951 new UserEditCountUpdate( $this, 1 ),
4952 DeferredUpdates
::POSTSEND
4957 * This method should not be called outside User/UserEditCountUpdate
4961 public function setEditCountInternal( $count ) {
4962 $this->mEditCount
= $count;
4966 * Initialize user_editcount from data out of the revision table
4968 * @internal This method should not be called outside User/UserEditCountUpdate
4969 * @param IDatabase $dbr Replica database
4970 * @return int Number of edits
4972 public function initEditCountInternal( IDatabase
$dbr ) {
4973 // Pull from a replica DB to be less cruel to servers
4974 // Accuracy isn't the point anyway here
4975 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4976 $count = (int)$dbr->selectField(
4977 [ 'revision' ] +
$actorWhere['tables'],
4979 [ $actorWhere['conds'] ],
4982 $actorWhere['joins']
4985 $dbw = wfGetDB( DB_MASTER
);
4988 [ 'user_editcount' => $count ],
4990 'user_id' => $this->getId(),
4991 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5000 * Get the description of a given right
5003 * @param string $right Right to query
5004 * @return string Localized description of the right
5006 public static function getRightDescription( $right ) {
5007 $key = "right-$right";
5008 $msg = wfMessage( $key );
5009 return $msg->isDisabled() ?
$right : $msg->text();
5013 * Get the name of a given grant
5016 * @param string $grant Grant to query
5017 * @return string Localized name of the grant
5019 public static function getGrantName( $grant ) {
5020 $key = "grant-$grant";
5021 $msg = wfMessage( $key );
5022 return $msg->isDisabled() ?
$grant : $msg->text();
5026 * Add a newuser log entry for this user.
5027 * Before 1.19 the return value was always true.
5029 * @deprecated since 1.27, AuthManager handles logging
5030 * @param string|bool $action Account creation type.
5031 * - String, one of the following values:
5032 * - 'create' for an anonymous user creating an account for himself.
5033 * This will force the action's performer to be the created user itself,
5034 * no matter the value of $wgUser
5035 * - 'create2' for a logged in user creating an account for someone else
5036 * - 'byemail' when the created user will receive its password by e-mail
5037 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5038 * - Boolean means whether the account was created by e-mail (deprecated):
5039 * - true will be converted to 'byemail'
5040 * - false will be converted to 'create' if this object is the same as
5041 * $wgUser and to 'create2' otherwise
5042 * @param string $reason User supplied reason
5045 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5046 return true; // disabled
5050 * Add an autocreate newuser log entry for this user
5051 * Used by things like CentralAuth and perhaps other authplugins.
5052 * Consider calling addNewUserLogEntry() directly instead.
5054 * @deprecated since 1.27, AuthManager handles logging
5057 public function addNewUserLogEntryAutoCreate() {
5058 wfDeprecated( __METHOD__
, '1.27' );
5059 $this->addNewUserLogEntry( 'autocreate' );
5065 * Load the user options either from cache, the database or an array
5067 * @param array|null $data Rows for the current user out of the user_properties table
5069 protected function loadOptions( $data = null ) {
5072 if ( $this->mOptionsLoaded
) {
5076 $this->mOptions
= self
::getDefaultOptions();
5078 if ( !$this->getId() ) {
5079 // For unlogged-in users, load language/variant options from request.
5080 // There's no need to do it for logged-in users: they can set preferences,
5081 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5082 // so don't override user's choice (especially when the user chooses site default).
5083 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5084 $this->mOptions
['variant'] = $variant;
5085 $this->mOptions
['language'] = $variant;
5086 $this->mOptionsLoaded
= true;
5090 // Maybe load from the object
5091 if ( !is_null( $this->mOptionOverrides
) ) {
5092 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5093 foreach ( $this->mOptionOverrides
as $key => $value ) {
5094 $this->mOptions
[$key] = $value;
5097 if ( !is_array( $data ) ) {
5098 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5099 // Load from database
5100 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5101 ?
wfGetDB( DB_MASTER
)
5102 : wfGetDB( DB_REPLICA
);
5104 $res = $dbr->select(
5106 [ 'up_property', 'up_value' ],
5107 [ 'up_user' => $this->getId() ],
5111 $this->mOptionOverrides
= [];
5113 foreach ( $res as $row ) {
5114 // Convert '0' to 0. PHP's boolean conversion considers them both
5115 // false, but e.g. JavaScript considers the former as true.
5116 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5117 // and convert all values here.
5118 if ( $row->up_value
=== '0' ) {
5121 $data[$row->up_property
] = $row->up_value
;
5125 foreach ( $data as $property => $value ) {
5126 $this->mOptionOverrides
[$property] = $value;
5127 $this->mOptions
[$property] = $value;
5131 // Replace deprecated language codes
5132 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5133 $this->mOptions
['language']
5136 $this->mOptionsLoaded
= true;
5138 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5142 * Saves the non-default options for this user, as previously set e.g. via
5143 * setOption(), in the database's "user_properties" (preferences) table.
5144 * Usually used via saveSettings().
5146 protected function saveOptions() {
5147 $this->loadOptions();
5149 // Not using getOptions(), to keep hidden preferences in database
5150 $saveOptions = $this->mOptions
;
5152 // Allow hooks to abort, for instance to save to a global profile.
5153 // Reset options to default state before saving.
5154 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5158 $userId = $this->getId();
5160 $insert_rows = []; // all the new preference rows
5161 foreach ( $saveOptions as $key => $value ) {
5162 // Don't bother storing default values
5163 $defaultOption = self
::getDefaultOption( $key );
5164 if ( ( $defaultOption === null && $value !== false && $value !== null )
5165 ||
$value != $defaultOption
5168 'up_user' => $userId,
5169 'up_property' => $key,
5170 'up_value' => $value,
5175 $dbw = wfGetDB( DB_MASTER
);
5177 $res = $dbw->select( 'user_properties',
5178 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5180 // Find prior rows that need to be removed or updated. These rows will
5181 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5183 foreach ( $res as $row ) {
5184 if ( !isset( $saveOptions[$row->up_property
] )
5185 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5187 $keysDelete[] = $row->up_property
;
5191 if ( count( $keysDelete ) ) {
5192 // Do the DELETE by PRIMARY KEY for prior rows.
5193 // In the past a very large portion of calls to this function are for setting
5194 // 'rememberpassword' for new accounts (a preference that has since been removed).
5195 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5196 // caused gap locks on [max user ID,+infinity) which caused high contention since
5197 // updates would pile up on each other as they are for higher (newer) user IDs.
5198 // It might not be necessary these days, but it shouldn't hurt either.
5199 $dbw->delete( 'user_properties',
5200 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5202 // Insert the new preference rows
5203 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5207 * Return the list of user fields that should be selected to create
5208 * a new user object.
5209 * @deprecated since 1.31, use self::getQueryInfo() instead.
5212 public static function selectFields() {
5213 wfDeprecated( __METHOD__
, '1.31' );
5221 'user_email_authenticated',
5223 'user_email_token_expires',
5224 'user_registration',
5230 * Return the tables, fields, and join conditions to be selected to create
5231 * a new user object.
5233 * @return array With three keys:
5234 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5235 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5236 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5238 public static function getQueryInfo() {
5240 'tables' => [ 'user', 'user_actor' => 'actor' ],
5248 'user_email_authenticated',
5250 'user_email_token_expires',
5251 'user_registration',
5253 'user_actor.actor_id',
5256 'user_actor' => [ 'JOIN', 'user_actor.actor_user = user_id' ],
5264 * Factory function for fatal permission-denied errors
5267 * @param string $permission User right required
5270 static function newFatalPermissionDeniedStatus( $permission ) {
5274 foreach ( MediaWikiServices
::getInstance()
5275 ->getPermissionManager()
5276 ->getGroupsWithPermission( $permission ) as $group ) {
5277 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5281 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5284 return Status
::newFatal( 'badaccess-group0' );
5288 * Get a new instance of this user that was loaded from the master via a locking read
5290 * Use this instead of the main context User when updating that user. This avoids races
5291 * where that user was loaded from a replica DB or even the master but without proper locks.
5293 * @return User|null Returns null if the user was not found in the DB
5296 public function getInstanceForUpdate() {
5297 if ( !$this->getId() ) {
5298 return null; // anon
5301 $user = self
::newFromId( $this->getId() );
5302 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5310 * Checks if two user objects point to the same user.
5312 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5313 * @param UserIdentity $user
5316 public function equals( UserIdentity
$user ) {
5317 // XXX it's not clear whether central ID providers are supposed to obey this
5318 return $this->getName() === $user->getName();
5322 * Checks if usertalk is allowed
5326 public function isAllowUsertalk() {
5327 return $this->mAllowUsertalk
;