3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\Block\DatabaseBlock
;
25 use MediaWiki\Block\SystemBlock
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Session\SessionManager
;
28 use MediaWiki\Session\Token
;
29 use MediaWiki\Auth\AuthManager
;
30 use MediaWiki\Auth\AuthenticationResponse
;
31 use MediaWiki\Auth\AuthenticationRequest
;
32 use MediaWiki\User\UserIdentity
;
33 use MediaWiki\Logger\LoggerFactory
;
34 use Wikimedia\Assert\Assert
;
36 use Wikimedia\ScopedCallback
;
37 use Wikimedia\Rdbms\Database
;
38 use Wikimedia\Rdbms\DBExpectedError
;
39 use Wikimedia\Rdbms\IDatabase
;
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
, UserIdentity
{
54 * Number of characters required for the user_token field.
56 const TOKEN_LENGTH
= 32;
59 * An invalid string value for the user_token field.
61 const INVALID_TOKEN
= '*** INVALID ***';
64 * Version number to tag cached versions of serialized User objects. Should be increased when
65 * {@link $mCacheVars} or one of it's members changes.
70 * Exclude user options that are set to their default value.
73 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
78 const CHECK_USER_RIGHTS
= true;
83 const IGNORE_USER_RIGHTS
= false;
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
115 * @var string[] Cached results of getAllRights()
117 protected static $mAllRights = false;
119 /** Cache variables */
132 /** @var string TS_MW timestamp from the DB */
134 /** @var string TS_MW timestamp from cache */
135 protected $mQuickTouched;
139 public $mEmailAuthenticated;
141 protected $mEmailToken;
143 protected $mEmailTokenExpires;
145 protected $mRegistration;
147 protected $mEditCount;
148 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
149 protected $mGroupMemberships;
151 protected $mOptionOverrides;
156 * @var bool Whether the cache variables have been loaded.
158 public $mOptionsLoaded;
161 * @var array|bool Array with already loaded items or true if all items have been loaded.
163 protected $mLoadedItems = [];
167 * @var string Initialization data source if mLoadedItems!==true. May be one of:
168 * - 'defaults' anonymous user initialised from class defaults
169 * - 'name' initialise from mName
170 * - 'id' initialise from mId
171 * - 'actor' initialise from mActorId
172 * - 'session' log in from session if possible
174 * Use the User::newFrom*() family of functions to set this.
179 * Lazy-initialized variables, invalidated with clearInstanceCache
184 protected $mDatePreference;
190 protected $mBlockreason;
192 protected $mEffectiveGroups;
194 protected $mImplicitGroups;
196 protected $mFormerGroups;
197 /** @var AbstractBlock */
198 protected $mGlobalBlock;
206 /** @var WebRequest */
209 /** @var AbstractBlock */
213 protected $mAllowUsertalk;
215 /** @var AbstractBlock|bool */
216 private $mBlockedFromCreateAccount = false;
218 /** @var int User::READ_* constant bitfield used to load data */
219 protected $queryFlagsUsed = self
::READ_NORMAL
;
222 public static $idCacheByName = [];
225 * Lightweight constructor for an anonymous user.
226 * Use the User::newFrom* factory functions for other kinds of users.
230 * @see newFromActorId()
231 * @see newFromConfirmationCode()
232 * @see newFromSession()
235 public function __construct() {
236 $this->clearInstanceCache( 'defaults' );
242 public function __toString() {
243 return (string)$this->getName();
246 public function __get( $name ) {
247 // A shortcut for $mRights deprecation phase
248 if ( $name === 'mRights' ) {
249 return $this->getRights();
253 public function __set( $name, $value ) {
254 // A shortcut for $mRights deprecation phase, only known legitimate use was for
255 // testing purposes, other uses seem bad in principle
256 if ( $name === 'mRights' ) {
257 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
259 is_null( $value ) ?
[] : $value
265 * Test if it's safe to load this User object.
267 * You should typically check this before using $wgUser or
268 * RequestContext::getUser in a method that might be called before the
269 * system has been fully initialized. If the object is unsafe, you should
270 * use an anonymous user:
272 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
278 public function isSafeToLoad() {
279 global $wgFullyInitialised;
281 // The user is safe to load if:
282 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
283 // * mLoadedItems === true (already loaded)
284 // * mFrom !== 'session' (sessions not involved at all)
286 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
287 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
291 * Load the user table data for this object from the source given by mFrom.
293 * @param int $flags User::READ_* constant bitfield
295 public function load( $flags = self
::READ_NORMAL
) {
296 global $wgFullyInitialised;
298 if ( $this->mLoadedItems
=== true ) {
302 // Set it now to avoid infinite recursion in accessors
303 $oldLoadedItems = $this->mLoadedItems
;
304 $this->mLoadedItems
= true;
305 $this->queryFlagsUsed
= $flags;
307 // If this is called too early, things are likely to break.
308 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
309 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
310 ->warning( 'User::loadFromSession called before the end of Setup.php', [
311 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
313 $this->loadDefaults();
314 $this->mLoadedItems
= $oldLoadedItems;
318 switch ( $this->mFrom
) {
320 $this->loadDefaults();
323 // Make sure this thread sees its own changes
324 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
325 if ( $lb->hasOrMadeRecentMasterChanges() ) {
326 $flags |
= self
::READ_LATEST
;
327 $this->queryFlagsUsed
= $flags;
330 $this->mId
= self
::idFromName( $this->mName
, $flags );
332 // Nonexistent user placeholder object
333 $this->loadDefaults( $this->mName
);
335 $this->loadFromId( $flags );
339 // Make sure this thread sees its own changes, if the ID isn't 0
340 if ( $this->mId
!= 0 ) {
341 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
342 if ( $lb->hasOrMadeRecentMasterChanges() ) {
343 $flags |
= self
::READ_LATEST
;
344 $this->queryFlagsUsed
= $flags;
348 $this->loadFromId( $flags );
351 // Make sure this thread sees its own changes
352 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
353 if ( $lb->hasOrMadeRecentMasterChanges() ) {
354 $flags |
= self
::READ_LATEST
;
355 $this->queryFlagsUsed
= $flags;
358 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
359 $row = wfGetDB( $index )->selectRow(
361 [ 'actor_user', 'actor_name' ],
362 [ 'actor_id' => $this->mActorId
],
369 $this->loadDefaults();
370 } elseif ( $row->actor_user
) {
371 $this->mId
= $row->actor_user
;
372 $this->loadFromId( $flags );
374 $this->loadDefaults( $row->actor_name
);
378 if ( !$this->loadFromSession() ) {
379 // Loading from session failed. Load defaults.
380 $this->loadDefaults();
382 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
385 throw new UnexpectedValueException(
386 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
391 * Load user table data, given mId has already been set.
392 * @param int $flags User::READ_* constant bitfield
393 * @return bool False if the ID does not exist, true otherwise
395 public function loadFromId( $flags = self
::READ_NORMAL
) {
396 if ( $this->mId
== 0 ) {
397 // Anonymous users are not in the database (don't need cache)
398 $this->loadDefaults();
402 // Try cache (unless this needs data from the master DB).
403 // NOTE: if this thread called saveSettings(), the cache was cleared.
404 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
406 if ( !$this->loadFromDatabase( $flags ) ) {
407 // Can't load from ID
411 $this->loadFromCache();
414 $this->mLoadedItems
= true;
415 $this->queryFlagsUsed
= $flags;
422 * @param string $wikiId
425 public static function purge( $wikiId, $userId ) {
426 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
427 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
428 $cache->delete( $key );
433 * @param WANObjectCache $cache
436 protected function getCacheKey( WANObjectCache
$cache ) {
437 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
439 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
443 * @param WANObjectCache $cache
447 public function getMutableCacheKeys( WANObjectCache
$cache ) {
448 $id = $this->getId();
450 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
454 * Load user data from shared cache, given mId has already been set.
459 protected function loadFromCache() {
460 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
461 $data = $cache->getWithSetCallback(
462 $this->getCacheKey( $cache ),
464 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
465 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
466 wfDebug( "User: cache miss for user {$this->mId}\n" );
468 $this->loadFromDatabase( self
::READ_NORMAL
);
470 $this->loadOptions();
473 foreach ( self
::$mCacheVars as $name ) {
474 $data[$name] = $this->$name;
477 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
479 // if a user group membership is about to expire, the cache needs to
480 // expire at that time (T163691)
481 foreach ( $this->mGroupMemberships
as $ugm ) {
482 if ( $ugm->getExpiry() ) {
483 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
484 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
485 $ttl = $secondsUntilExpiry;
492 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
495 // Restore from cache
496 foreach ( self
::$mCacheVars as $name ) {
497 $this->$name = $data[$name];
503 /** @name newFrom*() static factory methods */
507 * Static factory method for creation from username.
509 * This is slightly less efficient than newFromId(), so use newFromId() if
510 * you have both an ID and a name handy.
512 * @param string $name Username, validated by Title::newFromText()
513 * @param string|bool $validate Validate username. Takes the same parameters as
514 * User::getCanonicalName(), except that true is accepted as an alias
515 * for 'valid', for BC.
517 * @return User|bool User object, or false if the username is invalid
518 * (e.g. if it contains illegal characters or is an IP address). If the
519 * username is not present in the database, the result will be a user object
520 * with a name, zero user ID and default settings.
522 public static function newFromName( $name, $validate = 'valid' ) {
523 if ( $validate === true ) {
526 $name = self
::getCanonicalName( $name, $validate );
527 if ( $name === false ) {
531 // Create unloaded user object
535 $u->setItemLoaded( 'name' );
541 * Static factory method for creation from a given user ID.
543 * @param int $id Valid user ID
544 * @return User The corresponding User object
546 public static function newFromId( $id ) {
550 $u->setItemLoaded( 'id' );
555 * Static factory method for creation from a given actor ID.
558 * @param int $id Valid actor ID
559 * @return User The corresponding User object
561 public static function newFromActorId( $id ) {
562 global $wgActorTableSchemaMigrationStage;
564 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
565 // but it does little harm and might be needed for write callers loading a User.
566 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
567 throw new BadMethodCallException(
568 'Cannot use ' . __METHOD__
569 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
576 $u->setItemLoaded( 'actor' );
581 * Returns a User object corresponding to the given UserIdentity.
585 * @param UserIdentity $identity
589 public static function newFromIdentity( UserIdentity
$identity ) {
590 if ( $identity instanceof User
) {
594 return self
::newFromAnyId(
595 $identity->getId() === 0 ?
null : $identity->getId(),
596 $identity->getName() === '' ?
null : $identity->getName(),
597 $identity->getActorId() === 0 ?
null : $identity->getActorId()
602 * Static factory method for creation from an ID, name, and/or actor ID
604 * This does not check that the ID, name, and actor ID all correspond to
608 * @param int|null $userId User ID, if known
609 * @param string|null $userName User name, if known
610 * @param int|null $actorId Actor ID, if known
611 * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none
614 public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) {
615 global $wgActorTableSchemaMigrationStage;
617 // Stop-gap solution for the problem described in T222212.
618 // Force the User ID and Actor ID to zero for users loaded from the database
619 // of another wiki, to prevent subtle data corruption and confusing failure modes.
620 if ( $wikiId !== false ) {
626 $user->mFrom
= 'defaults';
628 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
629 // but it does little harm and might be needed for write callers loading a User.
630 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
631 $user->mActorId
= (int)$actorId;
632 if ( $user->mActorId
!== 0 ) {
633 $user->mFrom
= 'actor';
635 $user->setItemLoaded( 'actor' );
638 if ( $userName !== null && $userName !== '' ) {
639 $user->mName
= $userName;
640 $user->mFrom
= 'name';
641 $user->setItemLoaded( 'name' );
644 if ( $userId !== null ) {
645 $user->mId
= (int)$userId;
646 if ( $user->mId
!== 0 ) {
649 $user->setItemLoaded( 'id' );
652 if ( $user->mFrom
=== 'defaults' ) {
653 throw new InvalidArgumentException(
654 'Cannot create a user with no name, no ID, and no actor ID'
662 * Factory method to fetch whichever user has a given email confirmation code.
663 * This code is generated when an account is created or its e-mail address
666 * If the code is invalid or has expired, returns NULL.
668 * @param string $code Confirmation code
669 * @param int $flags User::READ_* bitfield
672 public static function newFromConfirmationCode( $code, $flags = 0 ) {
673 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
674 ?
wfGetDB( DB_MASTER
)
675 : wfGetDB( DB_REPLICA
);
677 $id = $db->selectField(
681 'user_email_token' => md5( $code ),
682 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
686 return $id ? self
::newFromId( $id ) : null;
690 * Create a new user object using data from session. If the login
691 * credentials are invalid, the result is an anonymous user.
693 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
696 public static function newFromSession( WebRequest
$request = null ) {
698 $user->mFrom
= 'session';
699 $user->mRequest
= $request;
704 * Create a new user object from a user row.
705 * The row should have the following fields from the user table in it:
706 * - either user_name or user_id to load further data if needed (or both)
708 * - all other fields (email, etc.)
709 * It is useless to provide the remaining fields if either user_id,
710 * user_name and user_real_name are not provided because the whole row
711 * will be loaded once more from the database when accessing them.
713 * @param stdClass $row A row from the user table
714 * @param array|null $data Further data to load into the object
715 * (see User::loadFromRow for valid keys)
718 public static function newFromRow( $row, $data = null ) {
720 $user->loadFromRow( $row, $data );
725 * Static factory method for creation of a "system" user from username.
727 * A "system" user is an account that's used to attribute logged actions
728 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
729 * might include the 'Maintenance script' or 'Conversion script' accounts
730 * used by various scripts in the maintenance/ directory or accounts such
731 * as 'MediaWiki message delivery' used by the MassMessage extension.
733 * This can optionally create the user if it doesn't exist, and "steal" the
734 * account if it does exist.
736 * "Stealing" an existing user is intended to make it impossible for normal
737 * authentication processes to use the account, effectively disabling the
738 * account for normal use:
739 * - Email is invalidated, to prevent account recovery by emailing a
740 * temporary password and to disassociate the account from the existing
742 * - The token is set to a magic invalid value, to kill existing sessions
743 * and to prevent $this->setToken() calls from resetting the token to a
745 * - SessionManager is instructed to prevent new sessions for the user, to
746 * do things like deauthorizing OAuth consumers.
747 * - AuthManager is instructed to revoke access, to invalidate or remove
748 * passwords and other credentials.
750 * @param string $name Username
751 * @param array $options Options are:
752 * - validate: As for User::getCanonicalName(), default 'valid'
753 * - create: Whether to create the user if it doesn't already exist, default true
754 * - steal: Whether to "disable" the account for normal use if it already
755 * exists, default false
759 public static function newSystemUser( $name, $options = [] ) {
761 'validate' => 'valid',
766 $name = self
::getCanonicalName( $name, $options['validate'] );
767 if ( $name === false ) {
771 $dbr = wfGetDB( DB_REPLICA
);
772 $userQuery = self
::getQueryInfo();
773 $row = $dbr->selectRow(
774 $userQuery['tables'],
775 $userQuery['fields'],
776 [ 'user_name' => $name ],
782 // Try the master database...
783 $dbw = wfGetDB( DB_MASTER
);
784 $row = $dbw->selectRow(
785 $userQuery['tables'],
786 $userQuery['fields'],
787 [ 'user_name' => $name ],
795 // No user. Create it?
796 return $options['create']
797 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
801 $user = self
::newFromRow( $row );
803 // A user is considered to exist as a non-system user if it can
804 // authenticate, or has an email set, or has a non-invalid token.
805 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
806 AuthManager
::singleton()->userCanAuthenticate( $name )
808 // User exists. Steal it?
809 if ( !$options['steal'] ) {
813 AuthManager
::singleton()->revokeAccessForUser( $name );
815 $user->invalidateEmail();
816 $user->mToken
= self
::INVALID_TOKEN
;
817 $user->saveSettings();
818 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
827 * Get the username corresponding to a given user ID
828 * @param int $id User ID
829 * @return string|bool The corresponding username
831 public static function whoIs( $id ) {
832 return UserCache
::singleton()->getProp( $id, 'name' );
836 * Get the real name of a user given their user ID
838 * @param int $id User ID
839 * @return string|bool The corresponding user's real name
841 public static function whoIsReal( $id ) {
842 return UserCache
::singleton()->getProp( $id, 'real_name' );
846 * Get database id given a user name
847 * @param string $name Username
848 * @param int $flags User::READ_* constant bitfield
849 * @return int|null The corresponding user's ID, or null if user is nonexistent
851 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
852 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
853 $name = (string)$name;
854 $nt = Title
::makeTitleSafe( NS_USER
, $name );
855 if ( is_null( $nt ) ) {
860 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
861 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
864 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
865 $db = wfGetDB( $index );
870 [ 'user_name' => $nt->getText() ],
875 if ( $s === false ) {
878 $result = (int)$s->user_id
;
881 if ( count( self
::$idCacheByName ) >= 1000 ) {
882 self
::$idCacheByName = [];
885 self
::$idCacheByName[$name] = $result;
891 * Reset the cache used in idFromName(). For use in tests.
893 public static function resetIdByNameCache() {
894 self
::$idCacheByName = [];
898 * Does the string match an anonymous IP address?
900 * This function exists for username validation, in order to reject
901 * usernames which are similar in form to IP addresses. Strings such
902 * as 300.300.300.300 will return true because it looks like an IP
903 * address, despite not being strictly valid.
905 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
906 * address because the usemod software would "cloak" anonymous IP
907 * addresses like this, if we allowed accounts like this to be created
908 * new users could get the old edits of these anonymous users.
910 * @param string $name Name to match
913 public static function isIP( $name ) {
914 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
915 || IP
::isIPv6( $name );
919 * Is the user an IP range?
924 public function isIPRange() {
925 return IP
::isValidRange( $this->mName
);
929 * Is the input a valid username?
931 * Checks if the input is a valid username, we don't want an empty string,
932 * an IP address, anything that contains slashes (would mess up subpages),
933 * is longer than the maximum allowed username size or doesn't begin with
936 * @param string $name Name to match
939 public static function isValidUserName( $name ) {
940 global $wgMaxNameChars;
943 || self
::isIP( $name )
944 ||
strpos( $name, '/' ) !== false
945 ||
strlen( $name ) > $wgMaxNameChars
946 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
951 // Ensure that the name can't be misresolved as a different title,
952 // such as with extra namespace keys at the start.
953 $parsed = Title
::newFromText( $name );
954 if ( is_null( $parsed )
955 ||
$parsed->getNamespace()
956 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
960 // Check an additional blacklist of troublemaker characters.
961 // Should these be merged into the title char list?
962 $unicodeBlacklist = '/[' .
963 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
964 '\x{00a0}' . # non-breaking space
965 '\x{2000}-\x{200f}' . # various whitespace
966 '\x{2028}-\x{202f}' . # breaks and control chars
967 '\x{3000}' . # ideographic space
968 '\x{e000}-\x{f8ff}' . # private use
970 if ( preg_match( $unicodeBlacklist, $name ) ) {
978 * Usernames which fail to pass this function will be blocked
979 * from user login and new account registrations, but may be used
980 * internally by batch processes.
982 * If an account already exists in this form, login will be blocked
983 * by a failure to pass this function.
985 * @param string $name Name to match
988 public static function isUsableName( $name ) {
989 global $wgReservedUsernames;
990 // Must be a valid username, obviously ;)
991 if ( !self
::isValidUserName( $name ) ) {
995 static $reservedUsernames = false;
996 if ( !$reservedUsernames ) {
997 $reservedUsernames = $wgReservedUsernames;
998 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1001 // Certain names may be reserved for batch processes.
1002 foreach ( $reservedUsernames as $reserved ) {
1003 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1004 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1006 if ( $reserved == $name ) {
1014 * Return the users who are members of the given group(s). In case of multiple groups,
1015 * users who are members of at least one of them are returned.
1017 * @param string|array $groups A single group name or an array of group names
1018 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1019 * records; larger values are ignored.
1020 * @param int|null $after ID the user to start after
1021 * @return UserArrayFromResult
1023 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1024 if ( $groups === [] ) {
1025 return UserArrayFromResult
::newFromIDs( [] );
1028 $groups = array_unique( (array)$groups );
1029 $limit = min( 5000, $limit );
1031 $conds = [ 'ug_group' => $groups ];
1032 if ( $after !== null ) {
1033 $conds[] = 'ug_user > ' . (int)$after;
1036 $dbr = wfGetDB( DB_REPLICA
);
1037 $ids = $dbr->selectFieldValues(
1044 'ORDER BY' => 'ug_user',
1048 return UserArray
::newFromIDs( $ids );
1052 * Usernames which fail to pass this function will be blocked
1053 * from new account registrations, but may be used internally
1054 * either by batch processes or by user accounts which have
1055 * already been created.
1057 * Additional blacklisting may be added here rather than in
1058 * isValidUserName() to avoid disrupting existing accounts.
1060 * @param string $name String to match
1063 public static function isCreatableName( $name ) {
1064 global $wgInvalidUsernameCharacters;
1066 // Ensure that the username isn't longer than 235 bytes, so that
1067 // (at least for the builtin skins) user javascript and css files
1068 // will work. (T25080)
1069 if ( strlen( $name ) > 235 ) {
1070 wfDebugLog( 'username', __METHOD__
.
1071 ": '$name' invalid due to length" );
1075 // Preg yells if you try to give it an empty string
1076 if ( $wgInvalidUsernameCharacters !== '' &&
1077 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1079 wfDebugLog( 'username', __METHOD__
.
1080 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1084 return self
::isUsableName( $name );
1088 * Is the input a valid password for this user?
1090 * @param string $password Desired password
1093 public function isValidPassword( $password ) {
1094 // simple boolean wrapper for checkPasswordValidity
1095 return $this->checkPasswordValidity( $password )->isGood();
1099 * Check if this is a valid password for this user
1101 * Returns a Status object with a set of messages describing
1102 * problems with the password. If the return status is fatal,
1103 * the action should be refused and the password should not be
1104 * checked at all (this is mainly meant for DoS mitigation).
1105 * If the return value is OK but not good, the password can be checked,
1106 * but the user should not be able to set their password to this.
1107 * The value of the returned Status object will be an array which
1108 * can have the following fields:
1109 * - forceChange (bool): if set to true, the user should not be
1110 * allowed to log with this password unless they change it during
1111 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1112 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1113 * a password change on login.
1115 * @param string $password Desired password
1119 public function checkPasswordValidity( $password ) {
1120 global $wgPasswordPolicy;
1122 $upp = new UserPasswordPolicy(
1123 $wgPasswordPolicy['policies'],
1124 $wgPasswordPolicy['checks']
1127 $status = Status
::newGood( [] );
1128 $result = false; // init $result to false for the internal checks
1130 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1131 $status->error( $result );
1135 if ( $result === false ) {
1136 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1140 if ( $result === true ) {
1144 $status->error( $result );
1145 return $status; // the isValidPassword hook set a string $result and returned true
1149 * Given unvalidated user input, return a canonical username, or false if
1150 * the username is invalid.
1151 * @param string $name User input
1152 * @param string|bool $validate Type of validation to use:
1153 * - false No validation
1154 * - 'valid' Valid for batch processes
1155 * - 'usable' Valid for batch processes and login
1156 * - 'creatable' Valid for batch processes, login and account creation
1158 * @throws InvalidArgumentException
1159 * @return bool|string
1161 public static function getCanonicalName( $name, $validate = 'valid' ) {
1162 // Force usernames to capital
1163 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1165 # Reject names containing '#'; these will be cleaned up
1166 # with title normalisation, but then it's too late to
1168 if ( strpos( $name, '#' ) !== false ) {
1172 // Clean up name according to title rules,
1173 // but only when validation is requested (T14654)
1174 $t = ( $validate !== false ) ?
1175 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1176 // Check for invalid titles
1177 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1181 $name = $t->getText();
1183 switch ( $validate ) {
1187 if ( !self
::isValidUserName( $name ) ) {
1192 if ( !self
::isUsableName( $name ) ) {
1197 if ( !self
::isCreatableName( $name ) ) {
1202 throw new InvalidArgumentException(
1203 'Invalid parameter value for $validate in ' . __METHOD__
);
1209 * Set cached properties to default.
1211 * @note This no longer clears uncached lazy-initialised properties;
1212 * the constructor does that instead.
1214 * @param string|bool $name
1216 public function loadDefaults( $name = false ) {
1218 $this->mName
= $name;
1219 $this->mActorId
= null;
1220 $this->mRealName
= '';
1222 $this->mOptionOverrides
= null;
1223 $this->mOptionsLoaded
= false;
1225 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1226 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1227 if ( $loggedOut !== 0 ) {
1228 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1230 $this->mTouched
= '1'; # Allow any pages to be cached
1233 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1234 $this->mEmailAuthenticated
= null;
1235 $this->mEmailToken
= '';
1236 $this->mEmailTokenExpires
= null;
1237 $this->mRegistration
= wfTimestamp( TS_MW
);
1238 $this->mGroupMemberships
= [];
1240 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1244 * Return whether an item has been loaded.
1246 * @param string $item Item to check. Current possibilities:
1250 * @param string $all 'all' to check if the whole object has been loaded
1251 * or any other string to check if only the item is available (e.g.
1255 public function isItemLoaded( $item, $all = 'all' ) {
1256 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1257 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1261 * Set that an item has been loaded
1263 * @param string $item
1265 protected function setItemLoaded( $item ) {
1266 if ( is_array( $this->mLoadedItems
) ) {
1267 $this->mLoadedItems
[$item] = true;
1272 * Load user data from the session.
1274 * @return bool True if the user is logged in, false otherwise.
1276 private function loadFromSession() {
1277 // MediaWiki\Session\Session already did the necessary authentication of the user
1278 // returned here, so just use it if applicable.
1279 $session = $this->getRequest()->getSession();
1280 $user = $session->getUser();
1281 if ( $user->isLoggedIn() ) {
1282 $this->loadFromUserObject( $user );
1284 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1285 // every session load, because an autoblocked editor might not edit again from the same
1286 // IP address after being blocked.
1287 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1289 // Other code expects these to be set in the session, so set them.
1290 $session->set( 'wsUserID', $this->getId() );
1291 $session->set( 'wsUserName', $this->getName() );
1292 $session->set( 'wsToken', $this->getToken() );
1301 * Set the 'BlockID' cookie depending on block type and user authentication status.
1303 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1305 public function trackBlockWithCookie() {
1306 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1310 * Load user and user_group data from the database.
1311 * $this->mId must be set, this is how the user is identified.
1313 * @param int $flags User::READ_* constant bitfield
1314 * @return bool True if the user exists, false if the user is anonymous
1316 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1318 $this->mId
= intval( $this->mId
);
1320 if ( !$this->mId
) {
1321 // Anonymous users are not in the database
1322 $this->loadDefaults();
1326 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1327 $db = wfGetDB( $index );
1329 $userQuery = self
::getQueryInfo();
1330 $s = $db->selectRow(
1331 $userQuery['tables'],
1332 $userQuery['fields'],
1333 [ 'user_id' => $this->mId
],
1339 $this->queryFlagsUsed
= $flags;
1340 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1342 if ( $s !== false ) {
1343 // Initialise user table data
1344 $this->loadFromRow( $s );
1345 $this->mGroupMemberships
= null; // deferred
1346 $this->getEditCount(); // revalidation for nulls
1352 $this->loadDefaults();
1358 * Initialize this object from a row from the user table.
1360 * @param stdClass $row Row from the user table to load.
1361 * @param array|null $data Further user data to load into the object
1363 * user_groups Array of arrays or stdClass result rows out of the user_groups
1364 * table. Previously you were supposed to pass an array of strings
1365 * here, but we also need expiry info nowadays, so an array of
1366 * strings is ignored.
1367 * user_properties Array with properties out of the user_properties table
1369 protected function loadFromRow( $row, $data = null ) {
1370 global $wgActorTableSchemaMigrationStage;
1372 if ( !is_object( $row ) ) {
1373 throw new InvalidArgumentException( '$row must be an object' );
1378 $this->mGroupMemberships
= null; // deferred
1380 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1381 // but it does little harm and might be needed for write callers loading a User.
1382 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1383 if ( isset( $row->actor_id
) ) {
1384 $this->mActorId
= (int)$row->actor_id
;
1385 if ( $this->mActorId
!== 0 ) {
1386 $this->mFrom
= 'actor';
1388 $this->setItemLoaded( 'actor' );
1394 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1395 $this->mName
= $row->user_name
;
1396 $this->mFrom
= 'name';
1397 $this->setItemLoaded( 'name' );
1402 if ( isset( $row->user_real_name
) ) {
1403 $this->mRealName
= $row->user_real_name
;
1404 $this->setItemLoaded( 'realname' );
1409 if ( isset( $row->user_id
) ) {
1410 $this->mId
= intval( $row->user_id
);
1411 if ( $this->mId
!== 0 ) {
1412 $this->mFrom
= 'id';
1414 $this->setItemLoaded( 'id' );
1419 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1420 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1423 if ( isset( $row->user_editcount
) ) {
1424 $this->mEditCount
= $row->user_editcount
;
1429 if ( isset( $row->user_touched
) ) {
1430 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1435 if ( isset( $row->user_token
) ) {
1436 // The definition for the column is binary(32), so trim the NULs
1437 // that appends. The previous definition was char(32), so trim
1439 $this->mToken
= rtrim( $row->user_token
, " \0" );
1440 if ( $this->mToken
=== '' ) {
1441 $this->mToken
= null;
1447 if ( isset( $row->user_email
) ) {
1448 $this->mEmail
= $row->user_email
;
1449 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1450 $this->mEmailToken
= $row->user_email_token
;
1451 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1452 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1458 $this->mLoadedItems
= true;
1461 if ( is_array( $data ) ) {
1462 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1463 if ( $data['user_groups'] === [] ) {
1464 $this->mGroupMemberships
= [];
1466 $firstGroup = reset( $data['user_groups'] );
1467 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1468 $this->mGroupMemberships
= [];
1469 foreach ( $data['user_groups'] as $row ) {
1470 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1471 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1476 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1477 $this->loadOptions( $data['user_properties'] );
1483 * Load the data for this user object from another user object.
1487 protected function loadFromUserObject( $user ) {
1489 foreach ( self
::$mCacheVars as $var ) {
1490 $this->$var = $user->$var;
1495 * Load the groups from the database if they aren't already loaded.
1497 private function loadGroups() {
1498 if ( is_null( $this->mGroupMemberships
) ) {
1499 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1500 ?
wfGetDB( DB_MASTER
)
1501 : wfGetDB( DB_REPLICA
);
1502 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1508 * Add the user to the group if he/she meets given criteria.
1510 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1511 * possible to remove manually via Special:UserRights. In such case it
1512 * will not be re-added automatically. The user will also not lose the
1513 * group if they no longer meet the criteria.
1515 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1517 * @return array Array of groups the user has been promoted to.
1519 * @see $wgAutopromoteOnce
1521 public function addAutopromoteOnceGroups( $event ) {
1522 global $wgAutopromoteOnceLogInRC;
1524 if ( wfReadOnly() ||
!$this->getId() ) {
1528 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1529 if ( $toPromote === [] ) {
1533 if ( !$this->checkAndSetTouched() ) {
1534 return []; // raced out (bug T48834)
1537 $oldGroups = $this->getGroups(); // previous groups
1538 $oldUGMs = $this->getGroupMemberships();
1539 foreach ( $toPromote as $group ) {
1540 $this->addGroup( $group );
1542 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1543 $newUGMs = $this->getGroupMemberships();
1545 // update groups in external authentication database
1546 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1548 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1549 $logEntry->setPerformer( $this );
1550 $logEntry->setTarget( $this->getUserPage() );
1551 $logEntry->setParameters( [
1552 '4::oldgroups' => $oldGroups,
1553 '5::newgroups' => $newGroups,
1555 $logid = $logEntry->insert();
1556 if ( $wgAutopromoteOnceLogInRC ) {
1557 $logEntry->publish( $logid );
1564 * Builds update conditions. Additional conditions may be added to $conditions to
1565 * protected against race conditions using a compare-and-set (CAS) mechanism
1566 * based on comparing $this->mTouched with the user_touched field.
1568 * @param IDatabase $db
1569 * @param array $conditions WHERE conditions for use with Database::update
1570 * @return array WHERE conditions for use with Database::update
1572 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1573 if ( $this->mTouched
) {
1574 // CAS check: only update if the row wasn't changed sicne it was loaded.
1575 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1582 * Bump user_touched if it didn't change since this object was loaded
1584 * On success, the mTouched field is updated.
1585 * The user serialization cache is always cleared.
1587 * @return bool Whether user_touched was actually updated
1590 protected function checkAndSetTouched() {
1593 if ( !$this->mId
) {
1594 return false; // anon
1597 // Get a new user_touched that is higher than the old one
1598 $newTouched = $this->newTouchedTimestamp();
1600 $dbw = wfGetDB( DB_MASTER
);
1601 $dbw->update( 'user',
1602 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1603 $this->makeUpdateConditions( $dbw, [
1604 'user_id' => $this->mId
,
1608 $success = ( $dbw->affectedRows() > 0 );
1611 $this->mTouched
= $newTouched;
1612 $this->clearSharedCache( 'changed' );
1614 // Clears on failure too since that is desired if the cache is stale
1615 $this->clearSharedCache( 'refresh' );
1622 * Clear various cached data stored in this object. The cache of the user table
1623 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1625 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1626 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1628 public function clearInstanceCache( $reloadFrom = false ) {
1629 global $wgFullyInitialised;
1631 $this->mNewtalk
= -1;
1632 $this->mDatePreference
= null;
1633 $this->mBlockedby
= -1; # Unset
1634 $this->mHash
= false;
1635 $this->mEffectiveGroups
= null;
1636 $this->mImplicitGroups
= null;
1637 $this->mGroupMemberships
= null;
1638 $this->mOptions
= null;
1639 $this->mOptionsLoaded
= false;
1640 $this->mEditCount
= null;
1642 // Replacement of former `$this->mRights = null` line
1643 if ( $wgFullyInitialised && $this->mFrom
) {
1644 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1649 if ( $reloadFrom ) {
1650 $this->mLoadedItems
= [];
1651 $this->mFrom
= $reloadFrom;
1655 /** @var array|null */
1656 private static $defOpt = null;
1657 /** @var string|null */
1658 private static $defOptLang = null;
1661 * Reset the process cache of default user options. This is only necessary
1662 * if the wiki configuration has changed since defaults were calculated,
1663 * and as such should only be performed inside the testing suite that
1664 * regularly changes wiki configuration.
1666 public static function resetGetDefaultOptionsForTestsOnly() {
1667 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1668 self
::$defOpt = null;
1669 self
::$defOptLang = null;
1673 * Combine the language default options with any site-specific options
1674 * and add the default language variants.
1676 * @return array Array of String options
1678 public static function getDefaultOptions() {
1679 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1681 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1682 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1683 // The content language does not change (and should not change) mid-request, but the
1684 // unit tests change it anyway, and expect this method to return values relevant to the
1685 // current content language.
1686 return self
::$defOpt;
1689 self
::$defOpt = $wgDefaultUserOptions;
1690 // Default language setting
1691 self
::$defOptLang = $contLang->getCode();
1692 self
::$defOpt['language'] = self
::$defOptLang;
1693 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1694 if ( $langCode === $contLang->getCode() ) {
1695 self
::$defOpt['variant'] = $langCode;
1697 self
::$defOpt["variant-$langCode"] = $langCode;
1701 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1702 // since extensions may change the set of searchable namespaces depending
1703 // on user groups/permissions.
1704 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1705 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1707 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1709 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1711 return self
::$defOpt;
1715 * Get a given default option value.
1717 * @param string $opt Name of option to retrieve
1718 * @return string Default option value
1720 public static function getDefaultOption( $opt ) {
1721 $defOpts = self
::getDefaultOptions();
1722 return $defOpts[$opt] ??
null;
1726 * Get blocking information
1728 * TODO: Move this into the BlockManager, along with block-related properties.
1730 * @param bool $fromReplica Whether to check the replica DB first.
1731 * To improve performance, non-critical checks are done against replica DBs.
1732 * Check when actually saving should be done against master.
1734 private function getBlockedStatus( $fromReplica = true ) {
1735 if ( $this->mBlockedby
!= -1 ) {
1739 wfDebug( __METHOD__
. ": checking...\n" );
1741 // Initialize data...
1742 // Otherwise something ends up stomping on $this->mBlockedby when
1743 // things get lazy-loaded later, causing false positive block hits
1744 // due to -1 !== 0. Probably session-related... Nothing should be
1745 // overwriting mBlockedby, surely?
1748 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1754 $this->mBlock
= $block;
1755 $this->mBlockedby
= $block->getByName();
1756 $this->mBlockreason
= $block->getReason();
1757 $this->mHideName
= $block->getHideName();
1758 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1760 $this->mBlock
= null;
1761 $this->mBlockedby
= '';
1762 $this->mBlockreason
= '';
1763 $this->mHideName
= 0;
1764 $this->mAllowUsertalk
= false;
1767 // Avoid PHP 7.1 warning of passing $this by reference
1770 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1774 * Whether the given IP is in a DNS blacklist.
1776 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1777 * @param string $ip IP to check
1778 * @param bool $checkWhitelist Whether to check the whitelist first
1779 * @return bool True if blacklisted.
1781 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1782 return MediaWikiServices
::getInstance()->getBlockManager()
1783 ->isDnsBlacklisted( $ip, $checkWhitelist );
1787 * Whether the given IP is in a given DNS blacklist.
1789 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1790 * @param string $ip IP to check
1791 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1792 * @return bool True if blacklisted.
1794 public function inDnsBlacklist( $ip, $bases ) {
1795 wfDeprecated( __METHOD__
, '1.34' );
1798 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1799 if ( IP
::isIPv4( $ip ) ) {
1800 // Reverse IP, T23255
1801 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1803 foreach ( (array)$bases as $base ) {
1805 // If we have an access key, use that too (ProjectHoneypot, etc.)
1807 if ( is_array( $base ) ) {
1808 if ( count( $base ) >= 2 ) {
1809 // Access key is 1, base URL is 0
1810 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1812 $host = "$ipReversed.{$base[0]}";
1814 $basename = $base[0];
1816 $host = "$ipReversed.$base";
1820 $ipList = gethostbynamel( $host );
1823 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1828 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1836 * Check if an IP address is in the local proxy list
1838 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1842 public static function isLocallyBlockedProxy( $ip ) {
1843 wfDeprecated( __METHOD__
, '1.34' );
1845 global $wgProxyList;
1847 if ( !$wgProxyList ) {
1851 if ( !is_array( $wgProxyList ) ) {
1852 // Load values from the specified file
1853 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1856 $resultProxyList = [];
1857 $deprecatedIPEntries = [];
1859 // backward compatibility: move all ip addresses in keys to values
1860 foreach ( $wgProxyList as $key => $value ) {
1861 $keyIsIP = IP
::isIPAddress( $key );
1862 $valueIsIP = IP
::isIPAddress( $value );
1863 if ( $keyIsIP && !$valueIsIP ) {
1864 $deprecatedIPEntries[] = $key;
1865 $resultProxyList[] = $key;
1866 } elseif ( $keyIsIP && $valueIsIP ) {
1867 $deprecatedIPEntries[] = $key;
1868 $resultProxyList[] = $key;
1869 $resultProxyList[] = $value;
1871 $resultProxyList[] = $value;
1875 if ( $deprecatedIPEntries ) {
1877 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1878 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1881 $proxyListIPSet = new IPSet( $resultProxyList );
1882 return $proxyListIPSet->match( $ip );
1886 * Is this user subject to rate limiting?
1888 * @return bool True if rate limited
1890 public function isPingLimitable() {
1891 global $wgRateLimitsExcludedIPs;
1892 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1893 // No other good way currently to disable rate limits
1894 // for specific IPs. :P
1895 // But this is a crappy hack and should die.
1898 return !$this->isAllowed( 'noratelimit' );
1902 * Primitive rate limits: enforce maximum actions per time period
1903 * to put a brake on flooding.
1905 * The method generates both a generic profiling point and a per action one
1906 * (suffix being "-$action".
1908 * @note When using a shared cache like memcached, IP-address
1909 * last-hit counters will be shared across wikis.
1911 * @param string $action Action to enforce; 'edit' if unspecified
1912 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1913 * @return bool True if a rate limiter was tripped
1915 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1916 // Avoid PHP 7.1 warning of passing $this by reference
1918 // Call the 'PingLimiter' hook
1920 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1924 global $wgRateLimits;
1925 if ( !isset( $wgRateLimits[$action] ) ) {
1929 $limits = array_merge(
1930 [ '&can-bypass' => true ],
1931 $wgRateLimits[$action]
1934 // Some groups shouldn't trigger the ping limiter, ever
1935 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1940 $id = $this->getId();
1942 $isNewbie = $this->isNewbie();
1943 $cache = ObjectCache
::getLocalClusterInstance();
1947 if ( isset( $limits['anon'] ) ) {
1948 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1950 } elseif ( isset( $limits['user'] ) ) {
1951 // limits for logged-in users
1952 $userLimit = $limits['user'];
1955 // limits for anons and for newbie logged-in users
1958 if ( isset( $limits['ip'] ) ) {
1959 $ip = $this->getRequest()->getIP();
1960 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1962 // subnet-based limits
1963 if ( isset( $limits['subnet'] ) ) {
1964 $ip = $this->getRequest()->getIP();
1965 $subnet = IP
::getSubnet( $ip );
1966 if ( $subnet !== false ) {
1967 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1972 // Check for group-specific permissions
1973 // If more than one group applies, use the group with the highest limit ratio (max/period)
1974 foreach ( $this->getGroups() as $group ) {
1975 if ( isset( $limits[$group] ) ) {
1976 if ( $userLimit === false
1977 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1979 $userLimit = $limits[$group];
1984 // limits for newbie logged-in users (override all the normal user limits)
1985 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1986 $userLimit = $limits['newbie'];
1989 // Set the user limit key
1990 if ( $userLimit !== false ) {
1991 // phan is confused because &can-bypass's value is a bool, so it assumes
1992 // that $userLimit is also a bool here.
1993 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
1994 list( $max, $period ) = $userLimit;
1995 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1996 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
1999 // ip-based limits for all ping-limitable users
2000 if ( isset( $limits['ip-all'] ) ) {
2001 $ip = $this->getRequest()->getIP();
2002 // ignore if user limit is more permissive
2003 if ( $isNewbie ||
$userLimit === false
2004 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2005 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2009 // subnet-based limits for all ping-limitable users
2010 if ( isset( $limits['subnet-all'] ) ) {
2011 $ip = $this->getRequest()->getIP();
2012 $subnet = IP
::getSubnet( $ip );
2013 if ( $subnet !== false ) {
2014 // ignore if user limit is more permissive
2015 if ( $isNewbie ||
$userLimit === false
2016 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2017 > $userLimit[0] / $userLimit[1] ) {
2018 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2024 foreach ( $keys as $key => $limit ) {
2025 // phan is confused because &can-bypass's value is a bool, so it assumes
2026 // that $userLimit is also a bool here.
2027 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2028 list( $max, $period ) = $limit;
2029 $summary = "(limit $max in {$period}s)";
2030 $count = $cache->get( $key );
2033 if ( $count >= $max ) {
2034 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2035 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2038 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2041 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2042 if ( $incrBy > 0 ) {
2043 $cache->add( $key, 0, intval( $period ) ); // first ping
2046 if ( $incrBy > 0 ) {
2047 $cache->incr( $key, $incrBy );
2055 * Check if user is blocked
2057 * @deprecated since 1.34, use User::getBlock() or
2058 * PermissionManager::isBlockedFrom() or
2059 * PermissionManager::userCan() instead.
2061 * @param bool $fromReplica Whether to check the replica DB instead of
2062 * the master. Hacked from false due to horrible probs on site.
2063 * @return bool True if blocked, false otherwise
2065 public function isBlocked( $fromReplica = true ) {
2066 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2067 $this->getBlock()->appliesToRight( 'edit' );
2071 * Get the block affecting the user, or null if the user is not blocked
2073 * @param bool $fromReplica Whether to check the replica DB instead of the master
2074 * @return AbstractBlock|null
2076 public function getBlock( $fromReplica = true ) {
2077 $this->getBlockedStatus( $fromReplica );
2078 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2082 * Check if user is blocked from editing a particular article
2084 * @param Title $title Title to check
2085 * @param bool $fromReplica Whether to check the replica DB instead of the master
2088 * @deprecated since 1.33,
2089 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2092 public function isBlockedFrom( $title, $fromReplica = false ) {
2093 return MediaWikiServices
::getInstance()->getPermissionManager()
2094 ->isBlockedFrom( $this, $title, $fromReplica );
2098 * If user is blocked, return the name of the user who placed the block
2099 * @return string Name of blocker
2101 public function blockedBy() {
2102 $this->getBlockedStatus();
2103 return $this->mBlockedby
;
2107 * If user is blocked, return the specified reason for the block
2108 * @return string Blocking reason
2110 public function blockedFor() {
2111 $this->getBlockedStatus();
2112 return $this->mBlockreason
;
2116 * If user is blocked, return the ID for the block
2117 * @return int Block ID
2119 public function getBlockId() {
2120 $this->getBlockedStatus();
2121 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2125 * Check if user is blocked on all wikis.
2126 * Do not use for actual edit permission checks!
2127 * This is intended for quick UI checks.
2129 * @param string $ip IP address, uses current client if none given
2130 * @return bool True if blocked, false otherwise
2132 public function isBlockedGlobally( $ip = '' ) {
2133 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2137 * Check if user is blocked on all wikis.
2138 * Do not use for actual edit permission checks!
2139 * This is intended for quick UI checks.
2141 * @param string $ip IP address, uses current client if none given
2142 * @return AbstractBlock|null Block object if blocked, null otherwise
2143 * @throws FatalError
2144 * @throws MWException
2146 public function getGlobalBlock( $ip = '' ) {
2147 if ( $this->mGlobalBlock
!== null ) {
2148 return $this->mGlobalBlock ?
: null;
2150 // User is already an IP?
2151 if ( IP
::isIPAddress( $this->getName() ) ) {
2152 $ip = $this->getName();
2154 $ip = $this->getRequest()->getIP();
2156 // Avoid PHP 7.1 warning of passing $this by reference
2160 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2162 if ( $blocked && $block === null ) {
2163 // back-compat: UserIsBlockedGlobally didn't have $block param first
2164 $block = new SystemBlock( [
2166 'systemBlock' => 'global-block'
2170 $this->mGlobalBlock
= $blocked ?
$block : false;
2171 return $this->mGlobalBlock ?
: null;
2175 * Check if user account is locked
2177 * @return bool True if locked, false otherwise
2179 public function isLocked() {
2180 if ( $this->mLocked
!== null ) {
2181 return $this->mLocked
;
2184 $this->mLocked
= false;
2185 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2186 return $this->mLocked
;
2190 * Check if user account is hidden
2192 * @return bool True if hidden, false otherwise
2194 public function isHidden() {
2195 if ( $this->mHideName
!== null ) {
2196 return (bool)$this->mHideName
;
2198 $this->getBlockedStatus();
2199 if ( !$this->mHideName
) {
2201 $this->mHideName
= false;
2202 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2204 return (bool)$this->mHideName
;
2208 * Get the user's ID.
2209 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2211 public function getId() {
2212 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2213 // Special case, we know the user is anonymous
2217 if ( !$this->isItemLoaded( 'id' ) ) {
2218 // Don't load if this was initialized from an ID
2222 return (int)$this->mId
;
2226 * Set the user and reload all fields according to a given ID
2227 * @param int $v User ID to reload
2229 public function setId( $v ) {
2231 $this->clearInstanceCache( 'id' );
2235 * Get the user name, or the IP of an anonymous user
2236 * @return string User's name or IP address
2238 public function getName() {
2239 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2240 // Special case optimisation
2241 return $this->mName
;
2245 if ( $this->mName
=== false ) {
2247 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2250 return $this->mName
;
2254 * Set the user name.
2256 * This does not reload fields from the database according to the given
2257 * name. Rather, it is used to create a temporary "nonexistent user" for
2258 * later addition to the database. It can also be used to set the IP
2259 * address for an anonymous user to something other than the current
2262 * @note User::newFromName() has roughly the same function, when the named user
2264 * @param string $str New user name to set
2266 public function setName( $str ) {
2268 $this->mName
= $str;
2272 * Get the user's actor ID.
2274 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2275 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2277 public function getActorId( IDatabase
$dbw = null ) {
2278 global $wgActorTableSchemaMigrationStage;
2280 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2281 // but it does little harm and might be needed for write callers loading a User.
2282 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2286 if ( !$this->isItemLoaded( 'actor' ) ) {
2290 // Currently $this->mActorId might be null if $this was loaded from a
2291 // cache entry that was written when $wgActorTableSchemaMigrationStage
2292 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2293 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2294 // has been removed), that condition may be removed.
2295 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2297 'actor_user' => $this->getId() ?
: null,
2298 'actor_name' => (string)$this->getName(),
2301 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2302 throw new CannotCreateActorException(
2303 'Cannot create an actor for a usable name that is not an existing user'
2306 if ( $q['actor_name'] === '' ) {
2307 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2309 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2310 if ( $dbw->affectedRows() ) {
2311 $this->mActorId
= (int)$dbw->insertId();
2314 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2315 $this->mActorId
= (int)$dbw->selectField(
2320 [ 'LOCK IN SHARE MODE' ]
2322 if ( !$this->mActorId
) {
2323 throw new CannotCreateActorException(
2324 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2328 $this->invalidateCache();
2330 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2331 $db = wfGetDB( $index );
2332 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2334 $this->setItemLoaded( 'actor' );
2337 return (int)$this->mActorId
;
2341 * Get the user's name escaped by underscores.
2342 * @return string Username escaped by underscores.
2344 public function getTitleKey() {
2345 return str_replace( ' ', '_', $this->getName() );
2349 * Check if the user has new messages.
2350 * @return bool True if the user has new messages
2352 public function getNewtalk() {
2355 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2356 if ( $this->mNewtalk
=== -1 ) {
2357 $this->mNewtalk
= false; # reset talk page status
2359 // Check memcached separately for anons, who have no
2360 // entire User object stored in there.
2361 if ( !$this->mId
) {
2362 global $wgDisableAnonTalk;
2363 if ( $wgDisableAnonTalk ) {
2364 // Anon newtalk disabled by configuration.
2365 $this->mNewtalk
= false;
2367 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2370 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2374 return (bool)$this->mNewtalk
;
2378 * Return the data needed to construct links for new talk page message
2379 * alerts. If there are new messages, this will return an associative array
2380 * with the following data:
2381 * wiki: The database name of the wiki
2382 * link: Root-relative link to the user's talk page
2383 * rev: The last talk page revision that the user has seen or null. This
2384 * is useful for building diff links.
2385 * If there are no new messages, it returns an empty array.
2386 * @note This function was designed to accomodate multiple talk pages, but
2387 * currently only returns a single link and revision.
2390 public function getNewMessageLinks() {
2391 // Avoid PHP 7.1 warning of passing $this by reference
2394 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2398 if ( !$this->getNewtalk() ) {
2401 $utp = $this->getTalkPage();
2402 $dbr = wfGetDB( DB_REPLICA
);
2403 // Get the "last viewed rev" timestamp from the oldest message notification
2404 $timestamp = $dbr->selectField( 'user_newtalk',
2405 'MIN(user_last_timestamp)',
2406 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2408 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2411 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2412 'link' => $utp->getLocalURL(),
2419 * Get the revision ID for the last talk page revision viewed by the talk
2421 * @return int|null Revision ID or null
2423 public function getNewMessageRevisionId() {
2424 $newMessageRevisionId = null;
2425 $newMessageLinks = $this->getNewMessageLinks();
2427 // Note: getNewMessageLinks() never returns more than a single link
2428 // and it is always for the same wiki, but we double-check here in
2429 // case that changes some time in the future.
2430 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2431 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2432 && $newMessageLinks[0]['rev']
2434 /** @var Revision $newMessageRevision */
2435 $newMessageRevision = $newMessageLinks[0]['rev'];
2436 $newMessageRevisionId = $newMessageRevision->getId();
2439 return $newMessageRevisionId;
2443 * Internal uncached check for new messages
2446 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2447 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2448 * @return bool True if the user has new messages
2450 protected function checkNewtalk( $field, $id ) {
2451 $dbr = wfGetDB( DB_REPLICA
);
2453 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2455 return $ok !== false;
2459 * Add or update the new messages flag
2460 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2461 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2462 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2463 * @return bool True if successful, false otherwise
2465 protected function updateNewtalk( $field, $id, $curRev = null ) {
2466 // Get timestamp of the talk page revision prior to the current one
2467 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2468 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2469 // Mark the user as having new messages since this revision
2470 $dbw = wfGetDB( DB_MASTER
);
2471 $dbw->insert( 'user_newtalk',
2472 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2475 if ( $dbw->affectedRows() ) {
2476 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2480 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2485 * Clear the new messages flag for the given user
2486 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2487 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2488 * @return bool True if successful, false otherwise
2490 protected function deleteNewtalk( $field, $id ) {
2491 $dbw = wfGetDB( DB_MASTER
);
2492 $dbw->delete( 'user_newtalk',
2495 if ( $dbw->affectedRows() ) {
2496 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2500 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2505 * Update the 'You have new messages!' status.
2506 * @param bool $val Whether the user has new messages
2507 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2508 * page. Ignored if null or !$val.
2510 public function setNewtalk( $val, $curRev = null ) {
2511 if ( wfReadOnly() ) {
2516 $this->mNewtalk
= $val;
2518 if ( $this->isAnon() ) {
2520 $id = $this->getName();
2523 $id = $this->getId();
2527 $changed = $this->updateNewtalk( $field, $id, $curRev );
2529 $changed = $this->deleteNewtalk( $field, $id );
2533 $this->invalidateCache();
2538 * Generate a current or new-future timestamp to be stored in the
2539 * user_touched field when we update things.
2541 * @return string Timestamp in TS_MW format
2543 private function newTouchedTimestamp() {
2545 if ( $this->mTouched
) {
2546 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2549 return wfTimestamp( TS_MW
, $time );
2553 * Clear user data from memcached
2555 * Use after applying updates to the database; caller's
2556 * responsibility to update user_touched if appropriate.
2558 * Called implicitly from invalidateCache() and saveSettings().
2560 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2562 public function clearSharedCache( $mode = 'refresh' ) {
2563 if ( !$this->getId() ) {
2567 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2568 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2569 $key = $this->getCacheKey( $cache );
2571 if ( $mode === 'refresh' ) {
2572 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2574 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2575 function () use ( $cache, $key ) {
2576 $cache->delete( $key );
2584 * Immediately touch the user data cache for this account
2586 * Calls touch() and removes account data from memcached
2588 public function invalidateCache() {
2590 $this->clearSharedCache( 'changed' );
2594 * Update the "touched" timestamp for the user
2596 * This is useful on various login/logout events when making sure that
2597 * a browser or proxy that has multiple tenants does not suffer cache
2598 * pollution where the new user sees the old users content. The value
2599 * of getTouched() is checked when determining 304 vs 200 responses.
2600 * Unlike invalidateCache(), this preserves the User object cache and
2601 * avoids database writes.
2605 public function touch() {
2606 $id = $this->getId();
2608 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2609 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2610 $cache->touchCheckKey( $key );
2611 $this->mQuickTouched
= null;
2616 * Validate the cache for this account.
2617 * @param string $timestamp A timestamp in TS_MW format
2620 public function validateCache( $timestamp ) {
2621 return ( $timestamp >= $this->getTouched() );
2625 * Get the user touched timestamp
2627 * Use this value only to validate caches via inequalities
2628 * such as in the case of HTTP If-Modified-Since response logic
2630 * @return string TS_MW Timestamp
2632 public function getTouched() {
2636 if ( $this->mQuickTouched
=== null ) {
2637 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2638 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2640 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2643 return max( $this->mTouched
, $this->mQuickTouched
);
2646 return $this->mTouched
;
2650 * Get the user_touched timestamp field (time of last DB updates)
2651 * @return string TS_MW Timestamp
2654 public function getDBTouched() {
2657 return $this->mTouched
;
2661 * Set the password and reset the random token.
2662 * Calls through to authentication plugin if necessary;
2663 * will have no effect if the auth plugin refuses to
2664 * pass the change through or if the legal password
2667 * As a special case, setting the password to null
2668 * wipes it, so the account cannot be logged in until
2669 * a new password is set, for instance via e-mail.
2671 * @deprecated since 1.27, use AuthManager instead
2672 * @param string $str New password to set
2673 * @throws PasswordError On failure
2676 public function setPassword( $str ) {
2677 wfDeprecated( __METHOD__
, '1.27' );
2678 return $this->setPasswordInternal( $str );
2682 * Set the password and reset the random token unconditionally.
2684 * @deprecated since 1.27, use AuthManager instead
2685 * @param string|null $str New password to set or null to set an invalid
2686 * password hash meaning that the user will not be able to log in
2687 * through the web interface.
2689 public function setInternalPassword( $str ) {
2690 wfDeprecated( __METHOD__
, '1.27' );
2691 $this->setPasswordInternal( $str );
2695 * Actually set the password and such
2696 * @since 1.27 cannot set a password for a user not in the database
2697 * @param string|null $str New password to set or null to set an invalid
2698 * password hash meaning that the user will not be able to log in
2699 * through the web interface.
2700 * @return bool Success
2702 private function setPasswordInternal( $str ) {
2703 $manager = AuthManager
::singleton();
2705 // If the user doesn't exist yet, fail
2706 if ( !$manager->userExists( $this->getName() ) ) {
2707 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2710 $status = $this->changeAuthenticationData( [
2711 'username' => $this->getName(),
2715 if ( !$status->isGood() ) {
2716 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2717 ->info( __METHOD__
. ': Password change rejected: '
2718 . $status->getWikiText( null, null, 'en' ) );
2722 $this->setOption( 'watchlisttoken', false );
2723 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2729 * Changes credentials of the user.
2731 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2732 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2733 * e.g. when no provider handled the change.
2735 * @param array $data A set of authentication data in fieldname => value format. This is the
2736 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2740 public function changeAuthenticationData( array $data ) {
2741 $manager = AuthManager
::singleton();
2742 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2743 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2745 $status = Status
::newGood( 'ignored' );
2746 foreach ( $reqs as $req ) {
2747 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2749 if ( $status->getValue() === 'ignored' ) {
2750 $status->warning( 'authenticationdatachange-ignored' );
2753 if ( $status->isGood() ) {
2754 foreach ( $reqs as $req ) {
2755 $manager->changeAuthenticationData( $req );
2762 * Get the user's current token.
2763 * @param bool $forceCreation Force the generation of a new token if the
2764 * user doesn't have one (default=true for backwards compatibility).
2765 * @return string|null Token
2767 public function getToken( $forceCreation = true ) {
2768 global $wgAuthenticationTokenVersion;
2771 if ( !$this->mToken
&& $forceCreation ) {
2775 if ( !$this->mToken
) {
2776 // The user doesn't have a token, return null to indicate that.
2780 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2781 // We return a random value here so existing token checks are very
2783 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2786 if ( $wgAuthenticationTokenVersion === null ) {
2787 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2788 return $this->mToken
;
2791 // $wgAuthenticationTokenVersion in use, so hmac it.
2792 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2794 // The raw hash can be overly long. Shorten it up.
2795 $len = max( 32, self
::TOKEN_LENGTH
);
2796 if ( strlen( $ret ) < $len ) {
2797 // Should never happen, even md5 is 128 bits
2798 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2801 return substr( $ret, -$len );
2805 * Set the random token (used for persistent authentication)
2806 * Called from loadDefaults() among other places.
2808 * @param string|bool $token If specified, set the token to this value
2810 public function setToken( $token = false ) {
2812 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2813 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2814 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2815 } elseif ( !$token ) {
2816 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2818 $this->mToken
= $token;
2823 * Set the password for a password reminder or new account email
2825 * @deprecated Removed in 1.27. Use PasswordReset instead.
2826 * @param string $str New password to set or null to set an invalid
2827 * password hash meaning that the user will not be able to use it
2828 * @param bool $throttle If true, reset the throttle timestamp to the present
2830 public function setNewpassword( $str, $throttle = true ) {
2831 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2835 * Get the user's e-mail address
2836 * @return string User's email address
2838 public function getEmail() {
2840 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2841 return $this->mEmail
;
2845 * Get the timestamp of the user's e-mail authentication
2846 * @return string TS_MW timestamp
2848 public function getEmailAuthenticationTimestamp() {
2850 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2851 return $this->mEmailAuthenticated
;
2855 * Set the user's e-mail address
2856 * @param string $str New e-mail address
2858 public function setEmail( $str ) {
2860 if ( $str == $this->mEmail
) {
2863 $this->invalidateEmail();
2864 $this->mEmail
= $str;
2865 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2869 * Set the user's e-mail address and a confirmation mail if needed.
2872 * @param string $str New e-mail address
2875 public function setEmailWithConfirmation( $str ) {
2876 global $wgEnableEmail, $wgEmailAuthentication;
2878 if ( !$wgEnableEmail ) {
2879 return Status
::newFatal( 'emaildisabled' );
2882 $oldaddr = $this->getEmail();
2883 if ( $str === $oldaddr ) {
2884 return Status
::newGood( true );
2887 $type = $oldaddr != '' ?
'changed' : 'set';
2888 $notificationResult = null;
2890 if ( $wgEmailAuthentication && $type === 'changed' ) {
2891 // Send the user an email notifying the user of the change in registered
2892 // email address on their previous email address
2893 $change = $str != '' ?
'changed' : 'removed';
2894 $notificationResult = $this->sendMail(
2895 wfMessage( 'notificationemail_subject_' . $change )->text(),
2896 wfMessage( 'notificationemail_body_' . $change,
2897 $this->getRequest()->getIP(),
2903 $this->setEmail( $str );
2905 if ( $str !== '' && $wgEmailAuthentication ) {
2906 // Send a confirmation request to the new address if needed
2907 $result = $this->sendConfirmationMail( $type );
2909 if ( $notificationResult !== null ) {
2910 $result->merge( $notificationResult );
2913 if ( $result->isGood() ) {
2914 // Say to the caller that a confirmation and notification mail has been sent
2915 $result->value
= 'eauth';
2918 $result = Status
::newGood( true );
2925 * Get the user's real name
2926 * @return string User's real name
2928 public function getRealName() {
2929 if ( !$this->isItemLoaded( 'realname' ) ) {
2933 return $this->mRealName
;
2937 * Set the user's real name
2938 * @param string $str New real name
2940 public function setRealName( $str ) {
2942 $this->mRealName
= $str;
2946 * Get the user's current setting for a given option.
2948 * @param string $oname The option to check
2949 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2950 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2951 * @return string|array|int|null User's current value for the option
2952 * @see getBoolOption()
2953 * @see getIntOption()
2955 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2956 global $wgHiddenPrefs;
2957 $this->loadOptions();
2959 # We want 'disabled' preferences to always behave as the default value for
2960 # users, even if they have set the option explicitly in their settings (ie they
2961 # set it, and then it was disabled removing their ability to change it). But
2962 # we don't want to erase the preferences in the database in case the preference
2963 # is re-enabled again. So don't touch $mOptions, just override the returned value
2964 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2965 return self
::getDefaultOption( $oname );
2968 if ( array_key_exists( $oname, $this->mOptions
) ) {
2969 return $this->mOptions
[$oname];
2972 return $defaultOverride;
2976 * Get all user's options
2978 * @param int $flags Bitwise combination of:
2979 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2980 * to the default value. (Since 1.25)
2983 public function getOptions( $flags = 0 ) {
2984 global $wgHiddenPrefs;
2985 $this->loadOptions();
2986 $options = $this->mOptions
;
2988 # We want 'disabled' preferences to always behave as the default value for
2989 # users, even if they have set the option explicitly in their settings (ie they
2990 # set it, and then it was disabled removing their ability to change it). But
2991 # we don't want to erase the preferences in the database in case the preference
2992 # is re-enabled again. So don't touch $mOptions, just override the returned value
2993 foreach ( $wgHiddenPrefs as $pref ) {
2994 $default = self
::getDefaultOption( $pref );
2995 if ( $default !== null ) {
2996 $options[$pref] = $default;
3000 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3001 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3008 * Get the user's current setting for a given option, as a boolean value.
3010 * @param string $oname The option to check
3011 * @return bool User's current value for the option
3014 public function getBoolOption( $oname ) {
3015 return (bool)$this->getOption( $oname );
3019 * Get the user's current setting for a given option, as an integer value.
3021 * @param string $oname The option to check
3022 * @param int $defaultOverride A default value returned if the option does not exist
3023 * @return int User's current value for the option
3026 public function getIntOption( $oname, $defaultOverride = 0 ) {
3027 $val = $this->getOption( $oname );
3029 $val = $defaultOverride;
3031 return intval( $val );
3035 * Set the given option for a user.
3037 * You need to call saveSettings() to actually write to the database.
3039 * @param string $oname The option to set
3040 * @param mixed $val New value to set
3042 public function setOption( $oname, $val ) {
3043 $this->loadOptions();
3045 // Explicitly NULL values should refer to defaults
3046 if ( is_null( $val ) ) {
3047 $val = self
::getDefaultOption( $oname );
3050 $this->mOptions
[$oname] = $val;
3054 * Get a token stored in the preferences (like the watchlist one),
3055 * resetting it if it's empty (and saving changes).
3057 * @param string $oname The option name to retrieve the token from
3058 * @return string|bool User's current value for the option, or false if this option is disabled.
3059 * @see resetTokenFromOption()
3061 * @deprecated since 1.26 Applications should use the OAuth extension
3063 public function getTokenFromOption( $oname ) {
3064 global $wgHiddenPrefs;
3066 $id = $this->getId();
3067 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3071 $token = $this->getOption( $oname );
3073 // Default to a value based on the user token to avoid space
3074 // wasted on storing tokens for all users. When this option
3075 // is set manually by the user, only then is it stored.
3076 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3083 * Reset a token stored in the preferences (like the watchlist one).
3084 * *Does not* save user's preferences (similarly to setOption()).
3086 * @param string $oname The option name to reset the token in
3087 * @return string|bool New token value, or false if this option is disabled.
3088 * @see getTokenFromOption()
3091 public function resetTokenFromOption( $oname ) {
3092 global $wgHiddenPrefs;
3093 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3097 $token = MWCryptRand
::generateHex( 40 );
3098 $this->setOption( $oname, $token );
3103 * Return a list of the types of user options currently returned by
3104 * User::getOptionKinds().
3106 * Currently, the option kinds are:
3107 * - 'registered' - preferences which are registered in core MediaWiki or
3108 * by extensions using the UserGetDefaultOptions hook.
3109 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3110 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3111 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3112 * be used by user scripts.
3113 * - 'special' - "preferences" that are not accessible via User::getOptions
3114 * or User::setOptions.
3115 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3116 * These are usually legacy options, removed in newer versions.
3118 * The API (and possibly others) use this function to determine the possible
3119 * option types for validation purposes, so make sure to update this when a
3120 * new option kind is added.
3122 * @see User::getOptionKinds
3123 * @return array Option kinds
3125 public static function listOptionKinds() {
3128 'registered-multiselect',
3129 'registered-checkmatrix',
3137 * Return an associative array mapping preferences keys to the kind of a preference they're
3138 * used for. Different kinds are handled differently when setting or reading preferences.
3140 * See User::listOptionKinds for the list of valid option types that can be provided.
3142 * @see User::listOptionKinds
3143 * @param IContextSource $context
3144 * @param array|null $options Assoc. array with options keys to check as keys.
3145 * Defaults to $this->mOptions.
3146 * @return array The key => kind mapping data
3148 public function getOptionKinds( IContextSource
$context, $options = null ) {
3149 $this->loadOptions();
3150 if ( $options === null ) {
3151 $options = $this->mOptions
;
3154 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3155 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3158 // Pull out the "special" options, so they don't get converted as
3159 // multiselect or checkmatrix.
3160 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3161 foreach ( $specialOptions as $name => $value ) {
3162 unset( $prefs[$name] );
3165 // Multiselect and checkmatrix options are stored in the database with
3166 // one key per option, each having a boolean value. Extract those keys.
3167 $multiselectOptions = [];
3168 foreach ( $prefs as $name => $info ) {
3169 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3170 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3171 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3172 $prefix = $info['prefix'] ??
$name;
3174 foreach ( $opts as $value ) {
3175 $multiselectOptions["$prefix$value"] = true;
3178 unset( $prefs[$name] );
3181 $checkmatrixOptions = [];
3182 foreach ( $prefs as $name => $info ) {
3183 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3184 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3185 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3186 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3187 $prefix = $info['prefix'] ??
$name;
3189 foreach ( $columns as $column ) {
3190 foreach ( $rows as $row ) {
3191 $checkmatrixOptions["$prefix$column-$row"] = true;
3195 unset( $prefs[$name] );
3199 // $value is ignored
3200 foreach ( $options as $key => $value ) {
3201 if ( isset( $prefs[$key] ) ) {
3202 $mapping[$key] = 'registered';
3203 } elseif ( isset( $multiselectOptions[$key] ) ) {
3204 $mapping[$key] = 'registered-multiselect';
3205 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3206 $mapping[$key] = 'registered-checkmatrix';
3207 } elseif ( isset( $specialOptions[$key] ) ) {
3208 $mapping[$key] = 'special';
3209 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3210 $mapping[$key] = 'userjs';
3212 $mapping[$key] = 'unused';
3220 * Reset certain (or all) options to the site defaults
3222 * The optional parameter determines which kinds of preferences will be reset.
3223 * Supported values are everything that can be reported by getOptionKinds()
3224 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3226 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3227 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3228 * for backwards-compatibility.
3229 * @param IContextSource|null $context Context source used when $resetKinds
3230 * does not contain 'all', passed to getOptionKinds().
3231 * Defaults to RequestContext::getMain() when null.
3233 public function resetOptions(
3234 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3235 IContextSource
$context = null
3238 $defaultOptions = self
::getDefaultOptions();
3240 if ( !is_array( $resetKinds ) ) {
3241 $resetKinds = [ $resetKinds ];
3244 if ( in_array( 'all', $resetKinds ) ) {
3245 $newOptions = $defaultOptions;
3247 if ( $context === null ) {
3248 $context = RequestContext
::getMain();
3251 $optionKinds = $this->getOptionKinds( $context );
3252 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3255 // Use default values for the options that should be deleted, and
3256 // copy old values for the ones that shouldn't.
3257 foreach ( $this->mOptions
as $key => $value ) {
3258 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3259 if ( array_key_exists( $key, $defaultOptions ) ) {
3260 $newOptions[$key] = $defaultOptions[$key];
3263 $newOptions[$key] = $value;
3268 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3270 $this->mOptions
= $newOptions;
3271 $this->mOptionsLoaded
= true;
3275 * Get the user's preferred date format.
3276 * @return string User's preferred date format
3278 public function getDatePreference() {
3279 // Important migration for old data rows
3280 if ( is_null( $this->mDatePreference
) ) {
3282 $value = $this->getOption( 'date' );
3283 $map = $wgLang->getDatePreferenceMigrationMap();
3284 if ( isset( $map[$value] ) ) {
3285 $value = $map[$value];
3287 $this->mDatePreference
= $value;
3289 return $this->mDatePreference
;
3293 * Determine based on the wiki configuration and the user's options,
3294 * whether this user must be over HTTPS no matter what.
3298 public function requiresHTTPS() {
3299 global $wgSecureLogin;
3300 if ( !$wgSecureLogin ) {
3304 $https = $this->getBoolOption( 'prefershttps' );
3305 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3307 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3314 * Get the user preferred stub threshold
3318 public function getStubThreshold() {
3319 global $wgMaxArticleSize; # Maximum article size, in Kb
3320 $threshold = $this->getIntOption( 'stubthreshold' );
3321 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3322 // If they have set an impossible value, disable the preference
3323 // so we can use the parser cache again.
3330 * Get the permissions this user has.
3331 * @return string[] permission names
3333 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3334 * ->getUserPermissions(..) instead
3337 public function getRights() {
3338 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3342 * Get the list of explicit group memberships this user has.
3343 * The implicit * and user groups are not included.
3345 * @return string[] Array of internal group names (sorted since 1.33)
3347 public function getGroups() {
3349 $this->loadGroups();
3350 return array_keys( $this->mGroupMemberships
);
3354 * Get the list of explicit group memberships this user has, stored as
3355 * UserGroupMembership objects. Implicit groups are not included.
3357 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3360 public function getGroupMemberships() {
3362 $this->loadGroups();
3363 return $this->mGroupMemberships
;
3367 * Get the list of implicit group memberships this user has.
3368 * This includes all explicit groups, plus 'user' if logged in,
3369 * '*' for all accounts, and autopromoted groups
3370 * @param bool $recache Whether to avoid the cache
3371 * @return array Array of String internal group names
3373 public function getEffectiveGroups( $recache = false ) {
3374 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3375 $this->mEffectiveGroups
= array_unique( array_merge(
3376 $this->getGroups(), // explicit groups
3377 $this->getAutomaticGroups( $recache ) // implicit groups
3379 // Avoid PHP 7.1 warning of passing $this by reference
3381 // Hook for additional groups
3382 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3383 // Force reindexation of groups when a hook has unset one of them
3384 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3386 return $this->mEffectiveGroups
;
3390 * Get the list of implicit group memberships this user has.
3391 * This includes 'user' if logged in, '*' for all accounts,
3392 * and autopromoted groups
3393 * @param bool $recache Whether to avoid the cache
3394 * @return array Array of String internal group names
3396 public function getAutomaticGroups( $recache = false ) {
3397 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3398 $this->mImplicitGroups
= [ '*' ];
3399 if ( $this->getId() ) {
3400 $this->mImplicitGroups
[] = 'user';
3402 $this->mImplicitGroups
= array_unique( array_merge(
3403 $this->mImplicitGroups
,
3404 Autopromote
::getAutopromoteGroups( $this )
3408 // Assure data consistency with rights/groups,
3409 // as getEffectiveGroups() depends on this function
3410 $this->mEffectiveGroups
= null;
3413 return $this->mImplicitGroups
;
3417 * Returns the groups the user has belonged to.
3419 * The user may still belong to the returned groups. Compare with getGroups().
3421 * The function will not return groups the user had belonged to before MW 1.17
3423 * @return array Names of the groups the user has belonged to.
3425 public function getFormerGroups() {
3428 if ( is_null( $this->mFormerGroups
) ) {
3429 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3430 ?
wfGetDB( DB_MASTER
)
3431 : wfGetDB( DB_REPLICA
);
3432 $res = $db->select( 'user_former_groups',
3434 [ 'ufg_user' => $this->mId
],
3436 $this->mFormerGroups
= [];
3437 foreach ( $res as $row ) {
3438 $this->mFormerGroups
[] = $row->ufg_group
;
3442 return $this->mFormerGroups
;
3446 * Get the user's edit count.
3447 * @return int|null Null for anonymous users
3449 public function getEditCount() {
3450 if ( !$this->getId() ) {
3454 if ( $this->mEditCount
=== null ) {
3455 /* Populate the count, if it has not been populated yet */
3456 $dbr = wfGetDB( DB_REPLICA
);
3457 // check if the user_editcount field has been initialized
3458 $count = $dbr->selectField(
3459 'user', 'user_editcount',
3460 [ 'user_id' => $this->mId
],
3464 if ( $count === null ) {
3465 // it has not been initialized. do so.
3466 $count = $this->initEditCountInternal( $dbr );
3468 $this->mEditCount
= $count;
3470 return (int)$this->mEditCount
;
3474 * Add the user to the given group. This takes immediate effect.
3475 * If the user is already in the group, the expiry time will be updated to the new
3476 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3479 * @param string $group Name of the group to add
3480 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3481 * wfTimestamp(), or null if the group assignment should not expire
3484 public function addGroup( $group, $expiry = null ) {
3486 $this->loadGroups();
3489 $expiry = wfTimestamp( TS_MW
, $expiry );
3492 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3496 // create the new UserGroupMembership and put it in the DB
3497 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3498 if ( !$ugm->insert( true ) ) {
3502 $this->mGroupMemberships
[$group] = $ugm;
3504 // Refresh the groups caches, and clear the rights cache so it will be
3505 // refreshed on the next call to $this->getRights().
3506 $this->getEffectiveGroups( true );
3507 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3508 $this->invalidateCache();
3514 * Remove the user from the given group.
3515 * This takes immediate effect.
3516 * @param string $group Name of the group to remove
3519 public function removeGroup( $group ) {
3522 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3526 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3527 // delete the membership entry
3528 if ( !$ugm ||
!$ugm->delete() ) {
3532 $this->loadGroups();
3533 unset( $this->mGroupMemberships
[$group] );
3535 // Refresh the groups caches, and clear the rights cache so it will be
3536 // refreshed on the next call to $this->getRights().
3537 $this->getEffectiveGroups( true );
3538 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3539 $this->invalidateCache();
3545 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3546 * only this new name and not the old isLoggedIn() variant.
3548 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3549 * anonymous or has no local account (which can happen when importing). This is equivalent to
3550 * getId() != 0 and is provided for code readability.
3553 public function isRegistered() {
3554 return $this->getId() != 0;
3558 * Get whether the user is logged in
3561 public function isLoggedIn() {
3562 return $this->isRegistered();
3566 * Get whether the user is anonymous
3569 public function isAnon() {
3570 return !$this->isRegistered();
3574 * @return bool Whether this user is flagged as being a bot role account
3577 public function isBot() {
3578 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3583 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3589 * Check if user is allowed to access a feature / make an action
3591 * @param string $permissions,... Permissions to test
3592 * @return bool True if user is allowed to perform *any* of the given actions
3594 public function isAllowedAny() {
3595 $permissions = func_get_args();
3596 foreach ( $permissions as $permission ) {
3597 if ( $this->isAllowed( $permission ) ) {
3606 * @param string $permissions,... Permissions to test
3607 * @return bool True if the user is allowed to perform *all* of the given actions
3609 public function isAllowedAll() {
3610 $permissions = func_get_args();
3611 foreach ( $permissions as $permission ) {
3612 if ( !$this->isAllowed( $permission ) ) {
3620 * Internal mechanics of testing a permission
3622 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3623 * ->getPermissionManager()->userHasRight(...) instead
3625 * @param string $action
3629 public function isAllowed( $action = '' ) {
3630 return MediaWikiServices
::getInstance()->getPermissionManager()
3631 ->userHasRight( $this, $action );
3635 * Check whether to enable recent changes patrol features for this user
3636 * @return bool True or false
3638 public function useRCPatrol() {
3639 global $wgUseRCPatrol;
3640 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3644 * Check whether to enable new pages patrol features for this user
3645 * @return bool True or false
3647 public function useNPPatrol() {
3648 global $wgUseRCPatrol, $wgUseNPPatrol;
3650 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3651 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3656 * Check whether to enable new files patrol features for this user
3657 * @return bool True or false
3659 public function useFilePatrol() {
3660 global $wgUseRCPatrol, $wgUseFilePatrol;
3662 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3663 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3668 * Get the WebRequest object to use with this object
3670 * @return WebRequest
3672 public function getRequest() {
3673 if ( $this->mRequest
) {
3674 return $this->mRequest
;
3682 * Check the watched status of an article.
3683 * @since 1.22 $checkRights parameter added
3684 * @param Title $title Title of the article to look at
3685 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3686 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3689 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3690 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3691 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3698 * @since 1.22 $checkRights parameter added
3699 * @param Title $title Title of the article to look at
3700 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3701 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3703 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3704 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3705 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3707 [ $title->getSubjectPage(), $title->getTalkPage() ]
3710 $this->invalidateCache();
3714 * Stop watching an article.
3715 * @since 1.22 $checkRights parameter added
3716 * @param Title $title Title of the article to look at
3717 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3718 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3720 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3721 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3722 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3723 $store->removeWatch( $this, $title->getSubjectPage() );
3724 $store->removeWatch( $this, $title->getTalkPage() );
3726 $this->invalidateCache();
3730 * Clear the user's notification timestamp for the given title.
3731 * If e-notif e-mails are on, they will receive notification mails on
3732 * the next change of the page if it's watched etc.
3733 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3734 * @param Title &$title Title of the article to look at
3735 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3737 public function clearNotification( &$title, $oldid = 0 ) {
3738 global $wgUseEnotif, $wgShowUpdatedMarker;
3740 // Do nothing if the database is locked to writes
3741 if ( wfReadOnly() ) {
3745 // Do nothing if not allowed to edit the watchlist
3746 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3750 // If we're working on user's talk page, we should update the talk page message indicator
3751 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3752 // Avoid PHP 7.1 warning of passing $this by reference
3754 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3758 // Try to update the DB post-send and only if needed...
3759 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3760 if ( !$this->getNewtalk() ) {
3761 return; // no notifications to clear
3764 // Delete the last notifications (they stack up)
3765 $this->setNewtalk( false );
3767 // If there is a new, unseen, revision, use its timestamp
3769 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3772 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3777 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3781 if ( $this->isAnon() ) {
3782 // Nothing else to do...
3786 // Only update the timestamp if the page is being watched.
3787 // The query to find out if it is watched is cached both in memcached and per-invocation,
3788 // and when it does have to be executed, it can be on a replica DB
3789 // If this is the user's newtalk page, we always update the timestamp
3791 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3795 MediaWikiServices
::getInstance()->getWatchedItemStore()
3796 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3800 * Resets all of the given user's page-change notification timestamps.
3801 * If e-notif e-mails are on, they will receive notification mails on
3802 * the next change of any watched page.
3803 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3805 public function clearAllNotifications() {
3806 global $wgUseEnotif, $wgShowUpdatedMarker;
3807 // Do nothing if not allowed to edit the watchlist
3808 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3812 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3813 $this->setNewtalk( false );
3817 $id = $this->getId();
3822 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3823 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3825 // We also need to clear here the "you have new message" notification for the own
3826 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3830 * Compute experienced level based on edit count and registration date.
3832 * @return string 'newcomer', 'learner', or 'experienced'
3834 public function getExperienceLevel() {
3835 global $wgLearnerEdits,
3836 $wgExperiencedUserEdits,
3837 $wgLearnerMemberSince,
3838 $wgExperiencedUserMemberSince;
3840 if ( $this->isAnon() ) {
3844 $editCount = $this->getEditCount();
3845 $registration = $this->getRegistration();
3847 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3848 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3850 if ( $editCount < $wgLearnerEdits ||
3851 $registration > $learnerRegistration ) {
3855 if ( $editCount > $wgExperiencedUserEdits &&
3856 $registration <= $experiencedRegistration
3858 return 'experienced';
3865 * Persist this user's session (e.g. set cookies)
3867 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3869 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3870 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3872 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3874 if ( $this->mId
== 0 ) {
3878 $session = $this->getRequest()->getSession();
3879 if ( $request && $session->getRequest() !== $request ) {
3880 $session = $session->sessionWithRequest( $request );
3882 $delay = $session->delaySave();
3884 if ( !$session->getUser()->equals( $this ) ) {
3885 if ( !$session->canSetUser() ) {
3886 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3887 ->warning( __METHOD__
.
3888 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3892 $session->setUser( $this );
3895 $session->setRememberUser( $rememberMe );
3896 if ( $secure !== null ) {
3897 $session->setForceHTTPS( $secure );
3900 $session->persist();
3902 ScopedCallback
::consume( $delay );
3906 * Log this user out.
3908 public function logout() {
3909 // Avoid PHP 7.1 warning of passing $this by reference
3911 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3917 * Clear the user's session, and reset the instance cache.
3920 public function doLogout() {
3921 $session = $this->getRequest()->getSession();
3922 if ( !$session->canSetUser() ) {
3923 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3924 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3925 $error = 'immutable';
3926 } elseif ( !$session->getUser()->equals( $this ) ) {
3927 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3928 ->warning( __METHOD__
.
3929 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3931 // But we still may as well make this user object anon
3932 $this->clearInstanceCache( 'defaults' );
3933 $error = 'wronguser';
3935 $this->clearInstanceCache( 'defaults' );
3936 $delay = $session->delaySave();
3937 $session->unpersist(); // Clear cookies (T127436)
3938 $session->setLoggedOutTimestamp( time() );
3939 $session->setUser( new User
);
3940 $session->set( 'wsUserID', 0 ); // Other code expects this
3941 $session->resetAllTokens();
3942 ScopedCallback
::consume( $delay );
3945 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3946 'event' => 'logout',
3947 'successful' => $error === false,
3948 'status' => $error ?
: 'success',
3953 * Save this user's settings into the database.
3954 * @todo Only rarely do all these fields need to be set!
3956 public function saveSettings() {
3957 if ( wfReadOnly() ) {
3958 // @TODO: caller should deal with this instead!
3959 // This should really just be an exception.
3960 MWExceptionHandler
::logException( new DBExpectedError(
3962 "Could not update user with ID '{$this->mId}'; DB is read-only."
3968 if ( $this->mId
== 0 ) {
3972 // Get a new user_touched that is higher than the old one.
3973 // This will be used for a CAS check as a last-resort safety
3974 // check against race conditions and replica DB lag.
3975 $newTouched = $this->newTouchedTimestamp();
3977 $dbw = wfGetDB( DB_MASTER
);
3978 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3979 global $wgActorTableSchemaMigrationStage;
3981 $dbw->update( 'user',
3983 'user_name' => $this->mName
,
3984 'user_real_name' => $this->mRealName
,
3985 'user_email' => $this->mEmail
,
3986 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3987 'user_touched' => $dbw->timestamp( $newTouched ),
3988 'user_token' => strval( $this->mToken
),
3989 'user_email_token' => $this->mEmailToken
,
3990 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3991 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3992 'user_id' => $this->mId
,
3996 if ( !$dbw->affectedRows() ) {
3997 // Maybe the problem was a missed cache update; clear it to be safe
3998 $this->clearSharedCache( 'refresh' );
3999 // User was changed in the meantime or loaded with stale data
4000 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4001 LoggerFactory
::getInstance( 'preferences' )->warning(
4002 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4003 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4005 throw new MWException( "CAS update failed on user_touched. " .
4006 "The version of the user to be saved is older than the current version."
4010 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4013 [ 'actor_name' => $this->mName
],
4014 [ 'actor_user' => $this->mId
],
4020 $this->mTouched
= $newTouched;
4021 $this->saveOptions();
4023 Hooks
::run( 'UserSaveSettings', [ $this ] );
4024 $this->clearSharedCache( 'changed' );
4025 $this->getUserPage()->purgeSquid();
4029 * If only this user's username is known, and it exists, return the user ID.
4031 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4034 public function idForName( $flags = 0 ) {
4035 $s = trim( $this->getName() );
4040 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4041 ?
wfGetDB( DB_MASTER
)
4042 : wfGetDB( DB_REPLICA
);
4044 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4045 ?
[ 'LOCK IN SHARE MODE' ]
4048 $id = $db->selectField( 'user',
4049 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4055 * Add a user to the database, return the user object
4057 * @param string $name Username to add
4058 * @param array $params Array of Strings Non-default parameters to save to
4059 * the database as user_* fields:
4060 * - email: The user's email address.
4061 * - email_authenticated: The email authentication timestamp.
4062 * - real_name: The user's real name.
4063 * - options: An associative array of non-default options.
4064 * - token: Random authentication token. Do not set.
4065 * - registration: Registration timestamp. Do not set.
4067 * @return User|null User object, or null if the username already exists.
4069 public static function createNew( $name, $params = [] ) {
4070 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4071 if ( isset( $params[$field] ) ) {
4072 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4073 unset( $params[$field] );
4079 $user->setToken(); // init token
4080 if ( isset( $params['options'] ) ) {
4081 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4082 unset( $params['options'] );
4084 $dbw = wfGetDB( DB_MASTER
);
4086 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4089 'user_name' => $name,
4090 'user_password' => $noPass,
4091 'user_newpassword' => $noPass,
4092 'user_email' => $user->mEmail
,
4093 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4094 'user_real_name' => $user->mRealName
,
4095 'user_token' => strval( $user->mToken
),
4096 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4097 'user_editcount' => 0,
4098 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4100 foreach ( $params as $name => $value ) {
4101 $fields["user_$name"] = $value;
4104 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4105 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4106 if ( $dbw->affectedRows() ) {
4107 $newUser = self
::newFromId( $dbw->insertId() );
4108 $newUser->mName
= $fields['user_name'];
4109 $newUser->updateActorId( $dbw );
4110 // Load the user from master to avoid replica lag
4111 $newUser->load( self
::READ_LATEST
);
4120 * Add this existing user object to the database. If the user already
4121 * exists, a fatal status object is returned, and the user object is
4122 * initialised with the data from the database.
4124 * Previously, this function generated a DB error due to a key conflict
4125 * if the user already existed. Many extension callers use this function
4126 * in code along the lines of:
4128 * $user = User::newFromName( $name );
4129 * if ( !$user->isLoggedIn() ) {
4130 * $user->addToDatabase();
4132 * // do something with $user...
4134 * However, this was vulnerable to a race condition (T18020). By
4135 * initialising the user object if the user exists, we aim to support this
4136 * calling sequence as far as possible.
4138 * Note that if the user exists, this function will acquire a write lock,
4139 * so it is still advisable to make the call conditional on isLoggedIn(),
4140 * and to commit the transaction after calling.
4142 * @throws MWException
4145 public function addToDatabase() {
4147 if ( !$this->mToken
) {
4148 $this->setToken(); // init token
4151 if ( !is_string( $this->mName
) ) {
4152 throw new RuntimeException( "User name field is not set." );
4155 $this->mTouched
= $this->newTouchedTimestamp();
4157 $dbw = wfGetDB( DB_MASTER
);
4158 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4159 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4160 $dbw->insert( 'user',
4162 'user_name' => $this->mName
,
4163 'user_password' => $noPass,
4164 'user_newpassword' => $noPass,
4165 'user_email' => $this->mEmail
,
4166 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4167 'user_real_name' => $this->mRealName
,
4168 'user_token' => strval( $this->mToken
),
4169 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4170 'user_editcount' => 0,
4171 'user_touched' => $dbw->timestamp( $this->mTouched
),
4175 if ( !$dbw->affectedRows() ) {
4176 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4177 $this->mId
= $dbw->selectField(
4180 [ 'user_name' => $this->mName
],
4182 [ 'LOCK IN SHARE MODE' ]
4185 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4189 throw new MWException( $fname . ": hit a key conflict attempting " .
4190 "to insert user '{$this->mName}' row, but it was not present in select!" );
4192 return Status
::newFatal( 'userexists' );
4194 $this->mId
= $dbw->insertId();
4195 self
::$idCacheByName[$this->mName
] = $this->mId
;
4196 $this->updateActorId( $dbw );
4198 return Status
::newGood();
4200 if ( !$status->isGood() ) {
4204 // Clear instance cache other than user table data and actor, which is already accurate
4205 $this->clearInstanceCache();
4207 $this->saveOptions();
4208 return Status
::newGood();
4212 * Update the actor ID after an insert
4213 * @param IDatabase $dbw Writable database handle
4215 private function updateActorId( IDatabase
$dbw ) {
4216 global $wgActorTableSchemaMigrationStage;
4218 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4221 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4224 $this->mActorId
= (int)$dbw->insertId();
4229 * If this user is logged-in and blocked,
4230 * block any IP address they've successfully logged in from.
4231 * @return bool A block was spread
4233 public function spreadAnyEditBlock() {
4234 if ( $this->isLoggedIn() && $this->getBlock() ) {
4235 return $this->spreadBlock();
4242 * If this (non-anonymous) user is blocked,
4243 * block the IP address they've successfully logged in from.
4244 * @return bool A block was spread
4246 protected function spreadBlock() {
4247 wfDebug( __METHOD__
. "()\n" );
4249 if ( $this->mId
== 0 ) {
4253 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4254 if ( !$userblock ) {
4258 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4262 * Get whether the user is explicitly blocked from account creation.
4263 * @return bool|AbstractBlock
4265 public function isBlockedFromCreateAccount() {
4266 $this->getBlockedStatus();
4267 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4268 return $this->mBlock
;
4271 # T15611: if the IP address the user is trying to create an account from is
4272 # blocked with createaccount disabled, prevent new account creation there even
4273 # when the user is logged in
4274 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4275 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4276 null, $this->getRequest()->getIP()
4279 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4280 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4281 ?
$this->mBlockedFromCreateAccount
4286 * Get whether the user is blocked from using Special:Emailuser.
4289 public function isBlockedFromEmailuser() {
4290 $this->getBlockedStatus();
4291 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4295 * Get whether the user is blocked from using Special:Upload
4300 public function isBlockedFromUpload() {
4301 $this->getBlockedStatus();
4302 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4306 * Get whether the user is allowed to create an account.
4309 public function isAllowedToCreateAccount() {
4310 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4314 * Get this user's personal page title.
4316 * @return Title User's personal page title
4318 public function getUserPage() {
4319 return Title
::makeTitle( NS_USER
, $this->getName() );
4323 * Get this user's talk page title.
4325 * @return Title User's talk page title
4327 public function getTalkPage() {
4328 $title = $this->getUserPage();
4329 return $title->getTalkPage();
4333 * Determine whether the user is a newbie. Newbies are either
4334 * anonymous IPs, or the most recently created accounts.
4337 public function isNewbie() {
4338 return !$this->isAllowed( 'autoconfirmed' );
4342 * Check to see if the given clear-text password is one of the accepted passwords
4343 * @deprecated since 1.27, use AuthManager instead
4344 * @param string $password User password
4345 * @return bool True if the given password is correct, otherwise False
4347 public function checkPassword( $password ) {
4348 wfDeprecated( __METHOD__
, '1.27' );
4350 $manager = AuthManager
::singleton();
4351 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4352 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4354 'username' => $this->getName(),
4355 'password' => $password,
4358 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4359 switch ( $res->status
) {
4360 case AuthenticationResponse
::PASS
:
4362 case AuthenticationResponse
::FAIL
:
4363 // Hope it's not a PreAuthenticationProvider that failed...
4364 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4365 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4368 throw new BadMethodCallException(
4369 'AuthManager returned a response unsupported by ' . __METHOD__
4375 * Check if the given clear-text password matches the temporary password
4376 * sent by e-mail for password reset operations.
4378 * @deprecated since 1.27, use AuthManager instead
4379 * @param string $plaintext
4380 * @return bool True if matches, false otherwise
4382 public function checkTemporaryPassword( $plaintext ) {
4383 wfDeprecated( __METHOD__
, '1.27' );
4384 // Can't check the temporary password individually.
4385 return $this->checkPassword( $plaintext );
4389 * Initialize (if necessary) and return a session token value
4390 * which can be used in edit forms to show that the user's
4391 * login credentials aren't being hijacked with a foreign form
4395 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4396 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4397 * @return MediaWiki\Session\Token The new edit token
4399 public function getEditTokenObject( $salt = '', $request = null ) {
4400 if ( $this->isAnon() ) {
4401 return new LoggedOutEditToken();
4405 $request = $this->getRequest();
4407 return $request->getSession()->getToken( $salt );
4411 * Initialize (if necessary) and return a session token value
4412 * which can be used in edit forms to show that the user's
4413 * login credentials aren't being hijacked with a foreign form
4416 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4419 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4420 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4421 * @return string The new edit token
4423 public function getEditToken( $salt = '', $request = null ) {
4424 return $this->getEditTokenObject( $salt, $request )->toString();
4428 * Check given value against the token value stored in the session.
4429 * A match should confirm that the form was submitted from the
4430 * user's own login session, not a form submission from a third-party
4433 * @param string $val Input value to compare
4434 * @param string|array $salt Optional function-specific data for hashing
4435 * @param WebRequest|null $request Object to use or null to use $wgRequest
4436 * @param int|null $maxage Fail tokens older than this, in seconds
4437 * @return bool Whether the token matches
4439 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4440 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4444 * Check given value against the token value stored in the session,
4445 * ignoring the suffix.
4447 * @param string $val Input value to compare
4448 * @param string|array $salt Optional function-specific data for hashing
4449 * @param WebRequest|null $request Object to use or null to use $wgRequest
4450 * @param int|null $maxage Fail tokens older than this, in seconds
4451 * @return bool Whether the token matches
4453 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4454 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4455 return $this->matchEditToken( $val, $salt, $request, $maxage );
4459 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4460 * mail to the user's given address.
4462 * @param string $type Message to send, either "created", "changed" or "set"
4465 public function sendConfirmationMail( $type = 'created' ) {
4467 $expiration = null; // gets passed-by-ref and defined in next line.
4468 $token = $this->confirmationToken( $expiration );
4469 $url = $this->confirmationTokenUrl( $token );
4470 $invalidateURL = $this->invalidationTokenUrl( $token );
4471 $this->saveSettings();
4473 if ( $type == 'created' ||
$type === false ) {
4474 $message = 'confirmemail_body';
4476 } elseif ( $type === true ) {
4477 $message = 'confirmemail_body_changed';
4480 // Messages: confirmemail_body_changed, confirmemail_body_set
4481 $message = 'confirmemail_body_' . $type;
4485 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4486 'body' => wfMessage( $message,
4487 $this->getRequest()->getIP(),
4490 $wgLang->userTimeAndDate( $expiration, $this ),
4492 $wgLang->userDate( $expiration, $this ),
4493 $wgLang->userTime( $expiration, $this ) )->text(),
4499 'ip' => $this->getRequest()->getIP(),
4500 'confirmURL' => $url,
4501 'invalidateURL' => $invalidateURL,
4502 'expiration' => $expiration
4505 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4506 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4510 * Send an e-mail to this user's account. Does not check for
4511 * confirmed status or validity.
4513 * @param string $subject Message subject
4514 * @param string $body Message body
4515 * @param User|null $from Optional sending user; if unspecified, default
4516 * $wgPasswordSender will be used.
4517 * @param MailAddress|null $replyto Reply-To address
4520 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4521 global $wgPasswordSender;
4523 if ( $from instanceof User
) {
4524 $sender = MailAddress
::newFromUser( $from );
4526 $sender = new MailAddress( $wgPasswordSender,
4527 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4529 $to = MailAddress
::newFromUser( $this );
4531 return UserMailer
::send( $to, $sender, $subject, $body, [
4532 'replyTo' => $replyto,
4537 * Generate, store, and return a new e-mail confirmation code.
4538 * A hash (unsalted, since it's used as a key) is stored.
4540 * @note Call saveSettings() after calling this function to commit
4541 * this change to the database.
4543 * @param string &$expiration Accepts the expiration time
4544 * @return string New token
4546 protected function confirmationToken( &$expiration ) {
4547 global $wgUserEmailConfirmationTokenExpiry;
4549 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4550 $expiration = wfTimestamp( TS_MW
, $expires );
4552 $token = MWCryptRand
::generateHex( 32 );
4553 $hash = md5( $token );
4554 $this->mEmailToken
= $hash;
4555 $this->mEmailTokenExpires
= $expiration;
4560 * Return a URL the user can use to confirm their email address.
4561 * @param string $token Accepts the email confirmation token
4562 * @return string New token URL
4564 protected function confirmationTokenUrl( $token ) {
4565 return $this->getTokenUrl( 'ConfirmEmail', $token );
4569 * Return a URL the user can use to invalidate their email address.
4570 * @param string $token Accepts the email confirmation token
4571 * @return string New token URL
4573 protected function invalidationTokenUrl( $token ) {
4574 return $this->getTokenUrl( 'InvalidateEmail', $token );
4578 * Internal function to format the e-mail validation/invalidation URLs.
4579 * This uses a quickie hack to use the
4580 * hardcoded English names of the Special: pages, for ASCII safety.
4582 * @note Since these URLs get dropped directly into emails, using the
4583 * short English names avoids insanely long URL-encoded links, which
4584 * also sometimes can get corrupted in some browsers/mailers
4585 * (T8957 with Gmail and Internet Explorer).
4587 * @param string $page Special page
4588 * @param string $token
4589 * @return string Formatted URL
4591 protected function getTokenUrl( $page, $token ) {
4592 // Hack to bypass localization of 'Special:'
4593 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4594 return $title->getCanonicalURL();
4598 * Mark the e-mail address confirmed.
4600 * @note Call saveSettings() after calling this function to commit the change.
4604 public function confirmEmail() {
4605 // Check if it's already confirmed, so we don't touch the database
4606 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4607 if ( !$this->isEmailConfirmed() ) {
4608 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4609 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4615 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4616 * address if it was already confirmed.
4618 * @note Call saveSettings() after calling this function to commit the change.
4619 * @return bool Returns true
4621 public function invalidateEmail() {
4623 $this->mEmailToken
= null;
4624 $this->mEmailTokenExpires
= null;
4625 $this->setEmailAuthenticationTimestamp( null );
4627 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4632 * Set the e-mail authentication timestamp.
4633 * @param string $timestamp TS_MW timestamp
4635 public function setEmailAuthenticationTimestamp( $timestamp ) {
4637 $this->mEmailAuthenticated
= $timestamp;
4638 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4642 * Is this user allowed to send e-mails within limits of current
4643 * site configuration?
4646 public function canSendEmail() {
4647 global $wgEnableEmail, $wgEnableUserEmail;
4648 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4651 $canSend = $this->isEmailConfirmed();
4652 // Avoid PHP 7.1 warning of passing $this by reference
4654 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4659 * Is this user allowed to receive e-mails within limits of current
4660 * site configuration?
4663 public function canReceiveEmail() {
4664 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4668 * Is this user's e-mail address valid-looking and confirmed within
4669 * limits of the current site configuration?
4671 * @note If $wgEmailAuthentication is on, this may require the user to have
4672 * confirmed their address by returning a code or using a password
4673 * sent to the address from the wiki.
4677 public function isEmailConfirmed() {
4678 global $wgEmailAuthentication;
4680 // Avoid PHP 7.1 warning of passing $this by reference
4683 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4684 if ( $this->isAnon() ) {
4687 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4690 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4700 * Check whether there is an outstanding request for e-mail confirmation.
4703 public function isEmailConfirmationPending() {
4704 global $wgEmailAuthentication;
4705 return $wgEmailAuthentication &&
4706 !$this->isEmailConfirmed() &&
4707 $this->mEmailToken
&&
4708 $this->mEmailTokenExpires
> wfTimestamp();
4712 * Get the timestamp of account creation.
4714 * @return string|bool|null Timestamp of account creation, false for
4715 * non-existent/anonymous user accounts, or null if existing account
4716 * but information is not in database.
4718 public function getRegistration() {
4719 if ( $this->isAnon() ) {
4723 return $this->mRegistration
;
4727 * Get the timestamp of the first edit
4729 * @return string|bool Timestamp of first edit, or false for
4730 * non-existent/anonymous user accounts.
4732 public function getFirstEditTimestamp() {
4733 return $this->getEditTimestamp( true );
4737 * Get the timestamp of the latest edit
4740 * @return string|bool Timestamp of first edit, or false for
4741 * non-existent/anonymous user accounts.
4743 public function getLatestEditTimestamp() {
4744 return $this->getEditTimestamp( false );
4748 * Get the timestamp of the first or latest edit
4750 * @param bool $first True for the first edit, false for the latest one
4751 * @return string|bool Timestamp of first or latest edit, or false for
4752 * non-existent/anonymous user accounts.
4754 private function getEditTimestamp( $first ) {
4755 if ( $this->getId() == 0 ) {
4756 return false; // anons
4758 $dbr = wfGetDB( DB_REPLICA
);
4759 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4760 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4761 ?
'revactor_timestamp' : 'rev_timestamp';
4762 $sortOrder = $first ?
'ASC' : 'DESC';
4763 $time = $dbr->selectField(
4764 [ 'revision' ] +
$actorWhere['tables'],
4766 [ $actorWhere['conds'] ],
4768 [ 'ORDER BY' => "$tsField $sortOrder" ],
4769 $actorWhere['joins']
4772 return false; // no edits
4774 return wfTimestamp( TS_MW
, $time );
4778 * Get the permissions associated with a given list of groups
4780 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4781 * ->getGroupPermissions() instead
4783 * @param array $groups Array of Strings List of internal group names
4784 * @return array Array of Strings List of permission key names for given groups combined
4786 public static function getGroupPermissions( $groups ) {
4787 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4791 * Get all the groups who have a given permission
4793 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4794 * ->getGroupsWithPermission() instead
4796 * @param string $role Role to check
4797 * @return array Array of Strings List of internal group names with the given permission
4799 public static function getGroupsWithPermission( $role ) {
4800 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4804 * Check, if the given group has the given permission
4806 * If you're wanting to check whether all users have a permission, use
4807 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4810 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4811 * ->groupHasPermission(..) instead
4814 * @param string $group Group to check
4815 * @param string $role Role to check
4818 public static function groupHasPermission( $group, $role ) {
4819 return MediaWikiServices
::getInstance()->getPermissionManager()
4820 ->groupHasPermission( $group, $role );
4824 * Check if all users may be assumed to have the given permission
4826 * We generally assume so if the right is granted to '*' and isn't revoked
4827 * on any group. It doesn't attempt to take grants or other extension
4828 * limitations on rights into account in the general case, though, as that
4829 * would require it to always return false and defeat the purpose.
4830 * Specifically, session-based rights restrictions (such as OAuth or bot
4831 * passwords) are applied based on the current session.
4833 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4834 * ->isEveryoneAllowed() instead
4836 * @param string $right Right to check
4841 public static function isEveryoneAllowed( $right ) {
4842 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4846 * Return the set of defined explicit groups.
4847 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4848 * are not included, as they are defined automatically, not in the database.
4849 * @return array Array of internal group names
4851 public static function getAllGroups() {
4852 global $wgGroupPermissions, $wgRevokePermissions;
4853 return array_values( array_diff(
4854 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4855 self
::getImplicitGroups()
4860 * Get a list of all available permissions.
4862 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4863 * ->getAllPermissions() instead
4865 * @return string[] Array of permission names
4867 public static function getAllRights() {
4868 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4872 * Get a list of implicit groups
4873 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4875 * @return array Array of Strings Array of internal group names
4877 public static function getImplicitGroups() {
4878 global $wgImplicitGroups;
4879 return $wgImplicitGroups;
4883 * Returns an array of the groups that a particular group can add/remove.
4885 * @param string $group The group to check for whether it can add/remove
4886 * @return array [ 'add' => [ addablegroups ],
4887 * 'remove' => [ removablegroups ],
4888 * 'add-self' => [ addablegroups to self ],
4889 * 'remove-self' => [ removable groups from self ] ]
4891 public static function changeableByGroup( $group ) {
4892 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4901 if ( empty( $wgAddGroups[$group] ) ) {
4902 // Don't add anything to $groups
4903 } elseif ( $wgAddGroups[$group] === true ) {
4904 // You get everything
4905 $groups['add'] = self
::getAllGroups();
4906 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4907 $groups['add'] = $wgAddGroups[$group];
4910 // Same thing for remove
4911 if ( empty( $wgRemoveGroups[$group] ) ) {
4913 } elseif ( $wgRemoveGroups[$group] === true ) {
4914 $groups['remove'] = self
::getAllGroups();
4915 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4916 $groups['remove'] = $wgRemoveGroups[$group];
4919 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4920 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4921 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4922 if ( is_int( $key ) ) {
4923 $wgGroupsAddToSelf['user'][] = $value;
4928 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4929 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4930 if ( is_int( $key ) ) {
4931 $wgGroupsRemoveFromSelf['user'][] = $value;
4936 // Now figure out what groups the user can add to him/herself
4937 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4939 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4940 // No idea WHY this would be used, but it's there
4941 $groups['add-self'] = self
::getAllGroups();
4942 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4943 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4946 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4948 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4949 $groups['remove-self'] = self
::getAllGroups();
4950 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4951 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4958 * Returns an array of groups that this user can add and remove
4959 * @return array [ 'add' => [ addablegroups ],
4960 * 'remove' => [ removablegroups ],
4961 * 'add-self' => [ addablegroups to self ],
4962 * 'remove-self' => [ removable groups from self ] ]
4964 public function changeableGroups() {
4965 if ( $this->isAllowed( 'userrights' ) ) {
4966 // This group gives the right to modify everything (reverse-
4967 // compatibility with old "userrights lets you change
4969 // Using array_merge to make the groups reindexed
4970 $all = array_merge( self
::getAllGroups() );
4979 // Okay, it's not so simple, we will have to go through the arrays
4986 $addergroups = $this->getEffectiveGroups();
4988 foreach ( $addergroups as $addergroup ) {
4989 $groups = array_merge_recursive(
4990 $groups, $this->changeableByGroup( $addergroup )
4992 $groups['add'] = array_unique( $groups['add'] );
4993 $groups['remove'] = array_unique( $groups['remove'] );
4994 $groups['add-self'] = array_unique( $groups['add-self'] );
4995 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5001 * Schedule a deferred update to update the user's edit count
5003 public function incEditCount() {
5004 if ( $this->isAnon() ) {
5008 DeferredUpdates
::addUpdate(
5009 new UserEditCountUpdate( $this, 1 ),
5010 DeferredUpdates
::POSTSEND
5015 * This method should not be called outside User/UserEditCountUpdate
5019 public function setEditCountInternal( $count ) {
5020 $this->mEditCount
= $count;
5024 * Initialize user_editcount from data out of the revision table
5026 * @internal This method should not be called outside User/UserEditCountUpdate
5027 * @param IDatabase $dbr Replica database
5028 * @return int Number of edits
5030 public function initEditCountInternal( IDatabase
$dbr ) {
5031 // Pull from a replica DB to be less cruel to servers
5032 // Accuracy isn't the point anyway here
5033 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5034 $count = (int)$dbr->selectField(
5035 [ 'revision' ] +
$actorWhere['tables'],
5037 [ $actorWhere['conds'] ],
5040 $actorWhere['joins']
5043 $dbw = wfGetDB( DB_MASTER
);
5046 [ 'user_editcount' => $count ],
5048 'user_id' => $this->getId(),
5049 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5058 * Get the description of a given right
5061 * @param string $right Right to query
5062 * @return string Localized description of the right
5064 public static function getRightDescription( $right ) {
5065 $key = "right-$right";
5066 $msg = wfMessage( $key );
5067 return $msg->isDisabled() ?
$right : $msg->text();
5071 * Get the name of a given grant
5074 * @param string $grant Grant to query
5075 * @return string Localized name of the grant
5077 public static function getGrantName( $grant ) {
5078 $key = "grant-$grant";
5079 $msg = wfMessage( $key );
5080 return $msg->isDisabled() ?
$grant : $msg->text();
5084 * Add a newuser log entry for this user.
5085 * Before 1.19 the return value was always true.
5087 * @deprecated since 1.27, AuthManager handles logging
5088 * @param string|bool $action Account creation type.
5089 * - String, one of the following values:
5090 * - 'create' for an anonymous user creating an account for himself.
5091 * This will force the action's performer to be the created user itself,
5092 * no matter the value of $wgUser
5093 * - 'create2' for a logged in user creating an account for someone else
5094 * - 'byemail' when the created user will receive its password by e-mail
5095 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5096 * - Boolean means whether the account was created by e-mail (deprecated):
5097 * - true will be converted to 'byemail'
5098 * - false will be converted to 'create' if this object is the same as
5099 * $wgUser and to 'create2' otherwise
5100 * @param string $reason User supplied reason
5103 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5104 return true; // disabled
5108 * Add an autocreate newuser log entry for this user
5109 * Used by things like CentralAuth and perhaps other authplugins.
5110 * Consider calling addNewUserLogEntry() directly instead.
5112 * @deprecated since 1.27, AuthManager handles logging
5115 public function addNewUserLogEntryAutoCreate() {
5116 $this->addNewUserLogEntry( 'autocreate' );
5122 * Load the user options either from cache, the database or an array
5124 * @param array|null $data Rows for the current user out of the user_properties table
5126 protected function loadOptions( $data = null ) {
5129 if ( $this->mOptionsLoaded
) {
5133 $this->mOptions
= self
::getDefaultOptions();
5135 if ( !$this->getId() ) {
5136 // For unlogged-in users, load language/variant options from request.
5137 // There's no need to do it for logged-in users: they can set preferences,
5138 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5139 // so don't override user's choice (especially when the user chooses site default).
5140 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5141 $this->mOptions
['variant'] = $variant;
5142 $this->mOptions
['language'] = $variant;
5143 $this->mOptionsLoaded
= true;
5147 // Maybe load from the object
5148 if ( !is_null( $this->mOptionOverrides
) ) {
5149 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5150 foreach ( $this->mOptionOverrides
as $key => $value ) {
5151 $this->mOptions
[$key] = $value;
5154 if ( !is_array( $data ) ) {
5155 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5156 // Load from database
5157 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5158 ?
wfGetDB( DB_MASTER
)
5159 : wfGetDB( DB_REPLICA
);
5161 $res = $dbr->select(
5163 [ 'up_property', 'up_value' ],
5164 [ 'up_user' => $this->getId() ],
5168 $this->mOptionOverrides
= [];
5170 foreach ( $res as $row ) {
5171 // Convert '0' to 0. PHP's boolean conversion considers them both
5172 // false, but e.g. JavaScript considers the former as true.
5173 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5174 // and convert all values here.
5175 if ( $row->up_value
=== '0' ) {
5178 $data[$row->up_property
] = $row->up_value
;
5182 foreach ( $data as $property => $value ) {
5183 $this->mOptionOverrides
[$property] = $value;
5184 $this->mOptions
[$property] = $value;
5188 // Replace deprecated language codes
5189 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5190 $this->mOptions
['language']
5193 $this->mOptionsLoaded
= true;
5195 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5199 * Saves the non-default options for this user, as previously set e.g. via
5200 * setOption(), in the database's "user_properties" (preferences) table.
5201 * Usually used via saveSettings().
5203 protected function saveOptions() {
5204 $this->loadOptions();
5206 // Not using getOptions(), to keep hidden preferences in database
5207 $saveOptions = $this->mOptions
;
5209 // Allow hooks to abort, for instance to save to a global profile.
5210 // Reset options to default state before saving.
5211 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5215 $userId = $this->getId();
5217 $insert_rows = []; // all the new preference rows
5218 foreach ( $saveOptions as $key => $value ) {
5219 // Don't bother storing default values
5220 $defaultOption = self
::getDefaultOption( $key );
5221 if ( ( $defaultOption === null && $value !== false && $value !== null )
5222 ||
$value != $defaultOption
5225 'up_user' => $userId,
5226 'up_property' => $key,
5227 'up_value' => $value,
5232 $dbw = wfGetDB( DB_MASTER
);
5234 $res = $dbw->select( 'user_properties',
5235 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5237 // Find prior rows that need to be removed or updated. These rows will
5238 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5240 foreach ( $res as $row ) {
5241 if ( !isset( $saveOptions[$row->up_property
] )
5242 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5244 $keysDelete[] = $row->up_property
;
5248 if ( count( $keysDelete ) ) {
5249 // Do the DELETE by PRIMARY KEY for prior rows.
5250 // In the past a very large portion of calls to this function are for setting
5251 // 'rememberpassword' for new accounts (a preference that has since been removed).
5252 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5253 // caused gap locks on [max user ID,+infinity) which caused high contention since
5254 // updates would pile up on each other as they are for higher (newer) user IDs.
5255 // It might not be necessary these days, but it shouldn't hurt either.
5256 $dbw->delete( 'user_properties',
5257 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5259 // Insert the new preference rows
5260 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5264 * Return the list of user fields that should be selected to create
5265 * a new user object.
5266 * @deprecated since 1.31, use self::getQueryInfo() instead.
5269 public static function selectFields() {
5270 wfDeprecated( __METHOD__
, '1.31' );
5278 'user_email_authenticated',
5280 'user_email_token_expires',
5281 'user_registration',
5287 * Return the tables, fields, and join conditions to be selected to create
5288 * a new user object.
5290 * @return array With three keys:
5291 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5292 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5293 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5295 public static function getQueryInfo() {
5296 global $wgActorTableSchemaMigrationStage;
5299 'tables' => [ 'user' ],
5307 'user_email_authenticated',
5309 'user_email_token_expires',
5310 'user_registration',
5316 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5317 // but it does little harm and might be needed for write callers loading a User.
5318 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5319 $ret['tables']['user_actor'] = 'actor';
5320 $ret['fields'][] = 'user_actor.actor_id';
5321 $ret['joins']['user_actor'] = [
5322 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5323 [ 'user_actor.actor_user = user_id' ]
5331 * Factory function for fatal permission-denied errors
5334 * @param string $permission User right required
5337 static function newFatalPermissionDeniedStatus( $permission ) {
5341 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5342 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5346 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5349 return Status
::newFatal( 'badaccess-group0' );
5353 * Get a new instance of this user that was loaded from the master via a locking read
5355 * Use this instead of the main context User when updating that user. This avoids races
5356 * where that user was loaded from a replica DB or even the master but without proper locks.
5358 * @return User|null Returns null if the user was not found in the DB
5361 public function getInstanceForUpdate() {
5362 if ( !$this->getId() ) {
5363 return null; // anon
5366 $user = self
::newFromId( $this->getId() );
5367 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5375 * Checks if two user objects point to the same user.
5377 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5378 * @param UserIdentity $user
5381 public function equals( UserIdentity
$user ) {
5382 // XXX it's not clear whether central ID providers are supposed to obey this
5383 return $this->getName() === $user->getName();
5387 * Checks if usertalk is allowed
5391 public function isAllowUsertalk() {
5392 return $this->mAllowUsertalk
;