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 );
1283 if ( $user->getBlock() ) {
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 );
1290 // Other code expects these to be set in the session, so set them.
1291 $session->set( 'wsUserID', $this->getId() );
1292 $session->set( 'wsUserName', $this->getName() );
1293 $session->set( 'wsToken', $this->getToken() );
1302 * Set the 'BlockID' cookie depending on block type and user authentication status.
1304 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1306 public function trackBlockWithCookie() {
1307 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1311 * Load user and user_group data from the database.
1312 * $this->mId must be set, this is how the user is identified.
1314 * @param int $flags User::READ_* constant bitfield
1315 * @return bool True if the user exists, false if the user is anonymous
1317 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1319 $this->mId
= intval( $this->mId
);
1321 if ( !$this->mId
) {
1322 // Anonymous users are not in the database
1323 $this->loadDefaults();
1327 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1328 $db = wfGetDB( $index );
1330 $userQuery = self
::getQueryInfo();
1331 $s = $db->selectRow(
1332 $userQuery['tables'],
1333 $userQuery['fields'],
1334 [ 'user_id' => $this->mId
],
1340 $this->queryFlagsUsed
= $flags;
1341 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1343 if ( $s !== false ) {
1344 // Initialise user table data
1345 $this->loadFromRow( $s );
1346 $this->mGroupMemberships
= null; // deferred
1347 $this->getEditCount(); // revalidation for nulls
1353 $this->loadDefaults();
1359 * Initialize this object from a row from the user table.
1361 * @param stdClass $row Row from the user table to load.
1362 * @param array|null $data Further user data to load into the object
1364 * user_groups Array of arrays or stdClass result rows out of the user_groups
1365 * table. Previously you were supposed to pass an array of strings
1366 * here, but we also need expiry info nowadays, so an array of
1367 * strings is ignored.
1368 * user_properties Array with properties out of the user_properties table
1370 protected function loadFromRow( $row, $data = null ) {
1371 global $wgActorTableSchemaMigrationStage;
1373 if ( !is_object( $row ) ) {
1374 throw new InvalidArgumentException( '$row must be an object' );
1379 $this->mGroupMemberships
= null; // deferred
1381 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1382 // but it does little harm and might be needed for write callers loading a User.
1383 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1384 if ( isset( $row->actor_id
) ) {
1385 $this->mActorId
= (int)$row->actor_id
;
1386 if ( $this->mActorId
!== 0 ) {
1387 $this->mFrom
= 'actor';
1389 $this->setItemLoaded( 'actor' );
1395 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1396 $this->mName
= $row->user_name
;
1397 $this->mFrom
= 'name';
1398 $this->setItemLoaded( 'name' );
1403 if ( isset( $row->user_real_name
) ) {
1404 $this->mRealName
= $row->user_real_name
;
1405 $this->setItemLoaded( 'realname' );
1410 if ( isset( $row->user_id
) ) {
1411 $this->mId
= intval( $row->user_id
);
1412 if ( $this->mId
!== 0 ) {
1413 $this->mFrom
= 'id';
1415 $this->setItemLoaded( 'id' );
1420 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1421 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1424 if ( isset( $row->user_editcount
) ) {
1425 $this->mEditCount
= $row->user_editcount
;
1430 if ( isset( $row->user_touched
) ) {
1431 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1436 if ( isset( $row->user_token
) ) {
1437 // The definition for the column is binary(32), so trim the NULs
1438 // that appends. The previous definition was char(32), so trim
1440 $this->mToken
= rtrim( $row->user_token
, " \0" );
1441 if ( $this->mToken
=== '' ) {
1442 $this->mToken
= null;
1448 if ( isset( $row->user_email
) ) {
1449 $this->mEmail
= $row->user_email
;
1450 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1451 $this->mEmailToken
= $row->user_email_token
;
1452 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1453 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1459 $this->mLoadedItems
= true;
1462 if ( is_array( $data ) ) {
1463 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1464 if ( $data['user_groups'] === [] ) {
1465 $this->mGroupMemberships
= [];
1467 $firstGroup = reset( $data['user_groups'] );
1468 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1469 $this->mGroupMemberships
= [];
1470 foreach ( $data['user_groups'] as $row ) {
1471 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1472 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1477 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1478 $this->loadOptions( $data['user_properties'] );
1484 * Load the data for this user object from another user object.
1488 protected function loadFromUserObject( $user ) {
1490 foreach ( self
::$mCacheVars as $var ) {
1491 $this->$var = $user->$var;
1496 * Load the groups from the database if they aren't already loaded.
1498 private function loadGroups() {
1499 if ( is_null( $this->mGroupMemberships
) ) {
1500 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1501 ?
wfGetDB( DB_MASTER
)
1502 : wfGetDB( DB_REPLICA
);
1503 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1509 * Add the user to the group if he/she meets given criteria.
1511 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1512 * possible to remove manually via Special:UserRights. In such case it
1513 * will not be re-added automatically. The user will also not lose the
1514 * group if they no longer meet the criteria.
1516 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1518 * @return array Array of groups the user has been promoted to.
1520 * @see $wgAutopromoteOnce
1522 public function addAutopromoteOnceGroups( $event ) {
1523 global $wgAutopromoteOnceLogInRC;
1525 if ( wfReadOnly() ||
!$this->getId() ) {
1529 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1530 if ( $toPromote === [] ) {
1534 if ( !$this->checkAndSetTouched() ) {
1535 return []; // raced out (bug T48834)
1538 $oldGroups = $this->getGroups(); // previous groups
1539 $oldUGMs = $this->getGroupMemberships();
1540 foreach ( $toPromote as $group ) {
1541 $this->addGroup( $group );
1543 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1544 $newUGMs = $this->getGroupMemberships();
1546 // update groups in external authentication database
1547 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1549 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1550 $logEntry->setPerformer( $this );
1551 $logEntry->setTarget( $this->getUserPage() );
1552 $logEntry->setParameters( [
1553 '4::oldgroups' => $oldGroups,
1554 '5::newgroups' => $newGroups,
1556 $logid = $logEntry->insert();
1557 if ( $wgAutopromoteOnceLogInRC ) {
1558 $logEntry->publish( $logid );
1565 * Builds update conditions. Additional conditions may be added to $conditions to
1566 * protected against race conditions using a compare-and-set (CAS) mechanism
1567 * based on comparing $this->mTouched with the user_touched field.
1569 * @param IDatabase $db
1570 * @param array $conditions WHERE conditions for use with Database::update
1571 * @return array WHERE conditions for use with Database::update
1573 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1574 if ( $this->mTouched
) {
1575 // CAS check: only update if the row wasn't changed sicne it was loaded.
1576 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1583 * Bump user_touched if it didn't change since this object was loaded
1585 * On success, the mTouched field is updated.
1586 * The user serialization cache is always cleared.
1588 * @return bool Whether user_touched was actually updated
1591 protected function checkAndSetTouched() {
1594 if ( !$this->mId
) {
1595 return false; // anon
1598 // Get a new user_touched that is higher than the old one
1599 $newTouched = $this->newTouchedTimestamp();
1601 $dbw = wfGetDB( DB_MASTER
);
1602 $dbw->update( 'user',
1603 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1604 $this->makeUpdateConditions( $dbw, [
1605 'user_id' => $this->mId
,
1609 $success = ( $dbw->affectedRows() > 0 );
1612 $this->mTouched
= $newTouched;
1613 $this->clearSharedCache( 'changed' );
1615 // Clears on failure too since that is desired if the cache is stale
1616 $this->clearSharedCache( 'refresh' );
1623 * Clear various cached data stored in this object. The cache of the user table
1624 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1626 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1627 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1629 public function clearInstanceCache( $reloadFrom = false ) {
1630 global $wgFullyInitialised;
1632 $this->mNewtalk
= -1;
1633 $this->mDatePreference
= null;
1634 $this->mBlockedby
= -1; # Unset
1635 $this->mHash
= false;
1636 $this->mEffectiveGroups
= null;
1637 $this->mImplicitGroups
= null;
1638 $this->mGroupMemberships
= null;
1639 $this->mOptions
= null;
1640 $this->mOptionsLoaded
= false;
1641 $this->mEditCount
= null;
1643 // Replacement of former `$this->mRights = null` line
1644 if ( $wgFullyInitialised && $this->mFrom
) {
1645 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1650 if ( $reloadFrom ) {
1651 $this->mLoadedItems
= [];
1652 $this->mFrom
= $reloadFrom;
1656 /** @var array|null */
1657 private static $defOpt = null;
1658 /** @var string|null */
1659 private static $defOptLang = null;
1662 * Reset the process cache of default user options. This is only necessary
1663 * if the wiki configuration has changed since defaults were calculated,
1664 * and as such should only be performed inside the testing suite that
1665 * regularly changes wiki configuration.
1667 public static function resetGetDefaultOptionsForTestsOnly() {
1668 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1669 self
::$defOpt = null;
1670 self
::$defOptLang = null;
1674 * Combine the language default options with any site-specific options
1675 * and add the default language variants.
1677 * @return array Array of String options
1679 public static function getDefaultOptions() {
1680 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1682 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1683 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1684 // The content language does not change (and should not change) mid-request, but the
1685 // unit tests change it anyway, and expect this method to return values relevant to the
1686 // current content language.
1687 return self
::$defOpt;
1690 self
::$defOpt = $wgDefaultUserOptions;
1691 // Default language setting
1692 self
::$defOptLang = $contLang->getCode();
1693 self
::$defOpt['language'] = self
::$defOptLang;
1694 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1695 if ( $langCode === $contLang->getCode() ) {
1696 self
::$defOpt['variant'] = $langCode;
1698 self
::$defOpt["variant-$langCode"] = $langCode;
1702 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1703 // since extensions may change the set of searchable namespaces depending
1704 // on user groups/permissions.
1705 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1706 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1708 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1710 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1712 return self
::$defOpt;
1716 * Get a given default option value.
1718 * @param string $opt Name of option to retrieve
1719 * @return string Default option value
1721 public static function getDefaultOption( $opt ) {
1722 $defOpts = self
::getDefaultOptions();
1723 return $defOpts[$opt] ??
null;
1727 * Get blocking information
1729 * TODO: Move this into the BlockManager, along with block-related properties.
1731 * @param bool $fromReplica Whether to check the replica DB first.
1732 * To improve performance, non-critical checks are done against replica DBs.
1733 * Check when actually saving should be done against master.
1735 private function getBlockedStatus( $fromReplica = true ) {
1736 if ( $this->mBlockedby
!= -1 ) {
1740 wfDebug( __METHOD__
. ": checking...\n" );
1742 // Initialize data...
1743 // Otherwise something ends up stomping on $this->mBlockedby when
1744 // things get lazy-loaded later, causing false positive block hits
1745 // due to -1 !== 0. Probably session-related... Nothing should be
1746 // overwriting mBlockedby, surely?
1749 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1755 $this->mBlock
= $block;
1756 $this->mBlockedby
= $block->getByName();
1757 $this->mBlockreason
= $block->getReason();
1758 $this->mHideName
= $block->getHideName();
1759 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1761 $this->mBlock
= null;
1762 $this->mBlockedby
= '';
1763 $this->mBlockreason
= '';
1764 $this->mHideName
= 0;
1765 $this->mAllowUsertalk
= false;
1768 // Avoid PHP 7.1 warning of passing $this by reference
1771 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1775 * Whether the given IP is in a DNS blacklist.
1777 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1778 * @param string $ip IP to check
1779 * @param bool $checkWhitelist Whether to check the whitelist first
1780 * @return bool True if blacklisted.
1782 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1783 return MediaWikiServices
::getInstance()->getBlockManager()
1784 ->isDnsBlacklisted( $ip, $checkWhitelist );
1788 * Whether the given IP is in a given DNS blacklist.
1790 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1791 * @param string $ip IP to check
1792 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1793 * @return bool True if blacklisted.
1795 public function inDnsBlacklist( $ip, $bases ) {
1796 wfDeprecated( __METHOD__
, '1.34' );
1799 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1800 if ( IP
::isIPv4( $ip ) ) {
1801 // Reverse IP, T23255
1802 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1804 foreach ( (array)$bases as $base ) {
1806 // If we have an access key, use that too (ProjectHoneypot, etc.)
1808 if ( is_array( $base ) ) {
1809 if ( count( $base ) >= 2 ) {
1810 // Access key is 1, base URL is 0
1811 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1813 $host = "$ipReversed.{$base[0]}";
1815 $basename = $base[0];
1817 $host = "$ipReversed.$base";
1821 $ipList = gethostbynamel( $host );
1824 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1829 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1837 * Check if an IP address is in the local proxy list
1839 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1843 public static function isLocallyBlockedProxy( $ip ) {
1844 wfDeprecated( __METHOD__
, '1.34' );
1846 global $wgProxyList;
1848 if ( !$wgProxyList ) {
1852 if ( !is_array( $wgProxyList ) ) {
1853 // Load values from the specified file
1854 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1857 $resultProxyList = [];
1858 $deprecatedIPEntries = [];
1860 // backward compatibility: move all ip addresses in keys to values
1861 foreach ( $wgProxyList as $key => $value ) {
1862 $keyIsIP = IP
::isIPAddress( $key );
1863 $valueIsIP = IP
::isIPAddress( $value );
1864 if ( $keyIsIP && !$valueIsIP ) {
1865 $deprecatedIPEntries[] = $key;
1866 $resultProxyList[] = $key;
1867 } elseif ( $keyIsIP && $valueIsIP ) {
1868 $deprecatedIPEntries[] = $key;
1869 $resultProxyList[] = $key;
1870 $resultProxyList[] = $value;
1872 $resultProxyList[] = $value;
1876 if ( $deprecatedIPEntries ) {
1878 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1879 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1882 $proxyListIPSet = new IPSet( $resultProxyList );
1883 return $proxyListIPSet->match( $ip );
1887 * Is this user subject to rate limiting?
1889 * @return bool True if rate limited
1891 public function isPingLimitable() {
1892 global $wgRateLimitsExcludedIPs;
1893 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1894 // No other good way currently to disable rate limits
1895 // for specific IPs. :P
1896 // But this is a crappy hack and should die.
1899 return !$this->isAllowed( 'noratelimit' );
1903 * Primitive rate limits: enforce maximum actions per time period
1904 * to put a brake on flooding.
1906 * The method generates both a generic profiling point and a per action one
1907 * (suffix being "-$action".
1909 * @note When using a shared cache like memcached, IP-address
1910 * last-hit counters will be shared across wikis.
1912 * @param string $action Action to enforce; 'edit' if unspecified
1913 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1914 * @return bool True if a rate limiter was tripped
1916 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1917 // Avoid PHP 7.1 warning of passing $this by reference
1919 // Call the 'PingLimiter' hook
1921 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1925 global $wgRateLimits;
1926 if ( !isset( $wgRateLimits[$action] ) ) {
1930 $limits = array_merge(
1931 [ '&can-bypass' => true ],
1932 $wgRateLimits[$action]
1935 // Some groups shouldn't trigger the ping limiter, ever
1936 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1941 $id = $this->getId();
1943 $isNewbie = $this->isNewbie();
1944 $cache = ObjectCache
::getLocalClusterInstance();
1948 if ( isset( $limits['anon'] ) ) {
1949 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1951 } elseif ( isset( $limits['user'] ) ) {
1952 // limits for logged-in users
1953 $userLimit = $limits['user'];
1956 // limits for anons and for newbie logged-in users
1959 if ( isset( $limits['ip'] ) ) {
1960 $ip = $this->getRequest()->getIP();
1961 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1963 // subnet-based limits
1964 if ( isset( $limits['subnet'] ) ) {
1965 $ip = $this->getRequest()->getIP();
1966 $subnet = IP
::getSubnet( $ip );
1967 if ( $subnet !== false ) {
1968 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1973 // Check for group-specific permissions
1974 // If more than one group applies, use the group with the highest limit ratio (max/period)
1975 foreach ( $this->getGroups() as $group ) {
1976 if ( isset( $limits[$group] ) ) {
1977 if ( $userLimit === false
1978 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1980 $userLimit = $limits[$group];
1985 // limits for newbie logged-in users (override all the normal user limits)
1986 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1987 $userLimit = $limits['newbie'];
1990 // Set the user limit key
1991 if ( $userLimit !== false ) {
1992 // phan is confused because &can-bypass's value is a bool, so it assumes
1993 // that $userLimit is also a bool here.
1994 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
1995 list( $max, $period ) = $userLimit;
1996 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1997 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2000 // ip-based limits for all ping-limitable users
2001 if ( isset( $limits['ip-all'] ) ) {
2002 $ip = $this->getRequest()->getIP();
2003 // ignore if user limit is more permissive
2004 if ( $isNewbie ||
$userLimit === false
2005 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2006 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2010 // subnet-based limits for all ping-limitable users
2011 if ( isset( $limits['subnet-all'] ) ) {
2012 $ip = $this->getRequest()->getIP();
2013 $subnet = IP
::getSubnet( $ip );
2014 if ( $subnet !== false ) {
2015 // ignore if user limit is more permissive
2016 if ( $isNewbie ||
$userLimit === false
2017 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2018 > $userLimit[0] / $userLimit[1] ) {
2019 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2025 foreach ( $keys as $key => $limit ) {
2026 // phan is confused because &can-bypass's value is a bool, so it assumes
2027 // that $userLimit is also a bool here.
2028 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2029 list( $max, $period ) = $limit;
2030 $summary = "(limit $max in {$period}s)";
2031 $count = $cache->get( $key );
2034 if ( $count >= $max ) {
2035 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2036 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2039 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2042 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2043 if ( $incrBy > 0 ) {
2044 $cache->add( $key, 0, intval( $period ) ); // first ping
2047 if ( $incrBy > 0 ) {
2048 $cache->incr( $key, $incrBy );
2056 * Check if user is blocked
2058 * @deprecated since 1.34, use User::getBlock() or
2059 * PermissionManager::isBlockedFrom() or
2060 * PermissionManager::userCan() instead.
2062 * @param bool $fromReplica Whether to check the replica DB instead of
2063 * the master. Hacked from false due to horrible probs on site.
2064 * @return bool True if blocked, false otherwise
2066 public function isBlocked( $fromReplica = true ) {
2067 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2068 $this->getBlock()->appliesToRight( 'edit' );
2072 * Get the block affecting the user, or null if the user is not blocked
2074 * @param bool $fromReplica Whether to check the replica DB instead of the master
2075 * @return AbstractBlock|null
2077 public function getBlock( $fromReplica = true ) {
2078 $this->getBlockedStatus( $fromReplica );
2079 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2083 * Check if user is blocked from editing a particular article
2085 * @param Title $title Title to check
2086 * @param bool $fromReplica Whether to check the replica DB instead of the master
2089 * @deprecated since 1.33,
2090 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2093 public function isBlockedFrom( $title, $fromReplica = false ) {
2094 return MediaWikiServices
::getInstance()->getPermissionManager()
2095 ->isBlockedFrom( $this, $title, $fromReplica );
2099 * If user is blocked, return the name of the user who placed the block
2100 * @return string Name of blocker
2102 public function blockedBy() {
2103 $this->getBlockedStatus();
2104 return $this->mBlockedby
;
2108 * If user is blocked, return the specified reason for the block
2109 * @return string Blocking reason
2111 public function blockedFor() {
2112 $this->getBlockedStatus();
2113 return $this->mBlockreason
;
2117 * If user is blocked, return the ID for the block
2118 * @return int Block ID
2120 public function getBlockId() {
2121 $this->getBlockedStatus();
2122 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2126 * Check if user is blocked on all wikis.
2127 * Do not use for actual edit permission checks!
2128 * This is intended for quick UI checks.
2130 * @param string $ip IP address, uses current client if none given
2131 * @return bool True if blocked, false otherwise
2133 public function isBlockedGlobally( $ip = '' ) {
2134 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2138 * Check if user is blocked on all wikis.
2139 * Do not use for actual edit permission checks!
2140 * This is intended for quick UI checks.
2142 * @param string $ip IP address, uses current client if none given
2143 * @return AbstractBlock|null Block object if blocked, null otherwise
2144 * @throws FatalError
2145 * @throws MWException
2147 public function getGlobalBlock( $ip = '' ) {
2148 if ( $this->mGlobalBlock
!== null ) {
2149 return $this->mGlobalBlock ?
: null;
2151 // User is already an IP?
2152 if ( IP
::isIPAddress( $this->getName() ) ) {
2153 $ip = $this->getName();
2155 $ip = $this->getRequest()->getIP();
2157 // Avoid PHP 7.1 warning of passing $this by reference
2161 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2163 if ( $blocked && $block === null ) {
2164 // back-compat: UserIsBlockedGlobally didn't have $block param first
2165 $block = new SystemBlock( [
2167 'systemBlock' => 'global-block'
2171 $this->mGlobalBlock
= $blocked ?
$block : false;
2172 return $this->mGlobalBlock ?
: null;
2176 * Check if user account is locked
2178 * @return bool True if locked, false otherwise
2180 public function isLocked() {
2181 if ( $this->mLocked
!== null ) {
2182 return $this->mLocked
;
2185 $this->mLocked
= false;
2186 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2187 return $this->mLocked
;
2191 * Check if user account is hidden
2193 * @return bool True if hidden, false otherwise
2195 public function isHidden() {
2196 if ( $this->mHideName
!== null ) {
2197 return (bool)$this->mHideName
;
2199 $this->getBlockedStatus();
2200 if ( !$this->mHideName
) {
2202 $this->mHideName
= false;
2203 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2205 return (bool)$this->mHideName
;
2209 * Get the user's ID.
2210 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2212 public function getId() {
2213 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2214 // Special case, we know the user is anonymous
2218 if ( !$this->isItemLoaded( 'id' ) ) {
2219 // Don't load if this was initialized from an ID
2223 return (int)$this->mId
;
2227 * Set the user and reload all fields according to a given ID
2228 * @param int $v User ID to reload
2230 public function setId( $v ) {
2232 $this->clearInstanceCache( 'id' );
2236 * Get the user name, or the IP of an anonymous user
2237 * @return string User's name or IP address
2239 public function getName() {
2240 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2241 // Special case optimisation
2242 return $this->mName
;
2246 if ( $this->mName
=== false ) {
2248 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2251 return $this->mName
;
2255 * Set the user name.
2257 * This does not reload fields from the database according to the given
2258 * name. Rather, it is used to create a temporary "nonexistent user" for
2259 * later addition to the database. It can also be used to set the IP
2260 * address for an anonymous user to something other than the current
2263 * @note User::newFromName() has roughly the same function, when the named user
2265 * @param string $str New user name to set
2267 public function setName( $str ) {
2269 $this->mName
= $str;
2273 * Get the user's actor ID.
2275 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2276 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2278 public function getActorId( IDatabase
$dbw = null ) {
2279 global $wgActorTableSchemaMigrationStage;
2281 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2282 // but it does little harm and might be needed for write callers loading a User.
2283 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2287 if ( !$this->isItemLoaded( 'actor' ) ) {
2291 // Currently $this->mActorId might be null if $this was loaded from a
2292 // cache entry that was written when $wgActorTableSchemaMigrationStage
2293 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2294 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2295 // has been removed), that condition may be removed.
2296 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2298 'actor_user' => $this->getId() ?
: null,
2299 'actor_name' => (string)$this->getName(),
2302 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2303 throw new CannotCreateActorException(
2304 'Cannot create an actor for a usable name that is not an existing user'
2307 if ( $q['actor_name'] === '' ) {
2308 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2310 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2311 if ( $dbw->affectedRows() ) {
2312 $this->mActorId
= (int)$dbw->insertId();
2315 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2316 $this->mActorId
= (int)$dbw->selectField(
2321 [ 'LOCK IN SHARE MODE' ]
2323 if ( !$this->mActorId
) {
2324 throw new CannotCreateActorException(
2325 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2329 $this->invalidateCache();
2331 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2332 $db = wfGetDB( $index );
2333 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2335 $this->setItemLoaded( 'actor' );
2338 return (int)$this->mActorId
;
2342 * Get the user's name escaped by underscores.
2343 * @return string Username escaped by underscores.
2345 public function getTitleKey() {
2346 return str_replace( ' ', '_', $this->getName() );
2350 * Check if the user has new messages.
2351 * @return bool True if the user has new messages
2353 public function getNewtalk() {
2356 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2357 if ( $this->mNewtalk
=== -1 ) {
2358 $this->mNewtalk
= false; # reset talk page status
2360 // Check memcached separately for anons, who have no
2361 // entire User object stored in there.
2362 if ( !$this->mId
) {
2363 global $wgDisableAnonTalk;
2364 if ( $wgDisableAnonTalk ) {
2365 // Anon newtalk disabled by configuration.
2366 $this->mNewtalk
= false;
2368 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2371 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2375 return (bool)$this->mNewtalk
;
2379 * Return the data needed to construct links for new talk page message
2380 * alerts. If there are new messages, this will return an associative array
2381 * with the following data:
2382 * wiki: The database name of the wiki
2383 * link: Root-relative link to the user's talk page
2384 * rev: The last talk page revision that the user has seen or null. This
2385 * is useful for building diff links.
2386 * If there are no new messages, it returns an empty array.
2387 * @note This function was designed to accomodate multiple talk pages, but
2388 * currently only returns a single link and revision.
2391 public function getNewMessageLinks() {
2392 // Avoid PHP 7.1 warning of passing $this by reference
2395 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2399 if ( !$this->getNewtalk() ) {
2402 $utp = $this->getTalkPage();
2403 $dbr = wfGetDB( DB_REPLICA
);
2404 // Get the "last viewed rev" timestamp from the oldest message notification
2405 $timestamp = $dbr->selectField( 'user_newtalk',
2406 'MIN(user_last_timestamp)',
2407 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2409 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2412 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2413 'link' => $utp->getLocalURL(),
2420 * Get the revision ID for the last talk page revision viewed by the talk
2422 * @return int|null Revision ID or null
2424 public function getNewMessageRevisionId() {
2425 $newMessageRevisionId = null;
2426 $newMessageLinks = $this->getNewMessageLinks();
2428 // Note: getNewMessageLinks() never returns more than a single link
2429 // and it is always for the same wiki, but we double-check here in
2430 // case that changes some time in the future.
2431 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2432 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2433 && $newMessageLinks[0]['rev']
2435 /** @var Revision $newMessageRevision */
2436 $newMessageRevision = $newMessageLinks[0]['rev'];
2437 $newMessageRevisionId = $newMessageRevision->getId();
2440 return $newMessageRevisionId;
2444 * Internal uncached check for new messages
2447 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2448 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2449 * @return bool True if the user has new messages
2451 protected function checkNewtalk( $field, $id ) {
2452 $dbr = wfGetDB( DB_REPLICA
);
2454 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2456 return $ok !== false;
2460 * Add or update the new messages flag
2461 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2462 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2463 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2464 * @return bool True if successful, false otherwise
2466 protected function updateNewtalk( $field, $id, $curRev = null ) {
2467 // Get timestamp of the talk page revision prior to the current one
2468 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2469 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2470 // Mark the user as having new messages since this revision
2471 $dbw = wfGetDB( DB_MASTER
);
2472 $dbw->insert( 'user_newtalk',
2473 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2476 if ( $dbw->affectedRows() ) {
2477 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2481 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2486 * Clear the new messages flag for the given user
2487 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2488 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2489 * @return bool True if successful, false otherwise
2491 protected function deleteNewtalk( $field, $id ) {
2492 $dbw = wfGetDB( DB_MASTER
);
2493 $dbw->delete( 'user_newtalk',
2496 if ( $dbw->affectedRows() ) {
2497 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2501 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2506 * Update the 'You have new messages!' status.
2507 * @param bool $val Whether the user has new messages
2508 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2509 * page. Ignored if null or !$val.
2511 public function setNewtalk( $val, $curRev = null ) {
2512 if ( wfReadOnly() ) {
2517 $this->mNewtalk
= $val;
2519 if ( $this->isAnon() ) {
2521 $id = $this->getName();
2524 $id = $this->getId();
2528 $changed = $this->updateNewtalk( $field, $id, $curRev );
2530 $changed = $this->deleteNewtalk( $field, $id );
2534 $this->invalidateCache();
2539 * Generate a current or new-future timestamp to be stored in the
2540 * user_touched field when we update things.
2542 * @return string Timestamp in TS_MW format
2544 private function newTouchedTimestamp() {
2546 if ( $this->mTouched
) {
2547 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2550 return wfTimestamp( TS_MW
, $time );
2554 * Clear user data from memcached
2556 * Use after applying updates to the database; caller's
2557 * responsibility to update user_touched if appropriate.
2559 * Called implicitly from invalidateCache() and saveSettings().
2561 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2563 public function clearSharedCache( $mode = 'refresh' ) {
2564 if ( !$this->getId() ) {
2568 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2569 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2570 $key = $this->getCacheKey( $cache );
2572 if ( $mode === 'refresh' ) {
2573 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2575 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2576 function () use ( $cache, $key ) {
2577 $cache->delete( $key );
2585 * Immediately touch the user data cache for this account
2587 * Calls touch() and removes account data from memcached
2589 public function invalidateCache() {
2591 $this->clearSharedCache( 'changed' );
2595 * Update the "touched" timestamp for the user
2597 * This is useful on various login/logout events when making sure that
2598 * a browser or proxy that has multiple tenants does not suffer cache
2599 * pollution where the new user sees the old users content. The value
2600 * of getTouched() is checked when determining 304 vs 200 responses.
2601 * Unlike invalidateCache(), this preserves the User object cache and
2602 * avoids database writes.
2606 public function touch() {
2607 $id = $this->getId();
2609 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2610 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2611 $cache->touchCheckKey( $key );
2612 $this->mQuickTouched
= null;
2617 * Validate the cache for this account.
2618 * @param string $timestamp A timestamp in TS_MW format
2621 public function validateCache( $timestamp ) {
2622 return ( $timestamp >= $this->getTouched() );
2626 * Get the user touched timestamp
2628 * Use this value only to validate caches via inequalities
2629 * such as in the case of HTTP If-Modified-Since response logic
2631 * @return string TS_MW Timestamp
2633 public function getTouched() {
2637 if ( $this->mQuickTouched
=== null ) {
2638 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2639 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2641 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2644 return max( $this->mTouched
, $this->mQuickTouched
);
2647 return $this->mTouched
;
2651 * Get the user_touched timestamp field (time of last DB updates)
2652 * @return string TS_MW Timestamp
2655 public function getDBTouched() {
2658 return $this->mTouched
;
2662 * Set the password and reset the random token.
2663 * Calls through to authentication plugin if necessary;
2664 * will have no effect if the auth plugin refuses to
2665 * pass the change through or if the legal password
2668 * As a special case, setting the password to null
2669 * wipes it, so the account cannot be logged in until
2670 * a new password is set, for instance via e-mail.
2672 * @deprecated since 1.27, use AuthManager instead
2673 * @param string $str New password to set
2674 * @throws PasswordError On failure
2677 public function setPassword( $str ) {
2678 wfDeprecated( __METHOD__
, '1.27' );
2679 return $this->setPasswordInternal( $str );
2683 * Set the password and reset the random token unconditionally.
2685 * @deprecated since 1.27, use AuthManager instead
2686 * @param string|null $str New password to set or null to set an invalid
2687 * password hash meaning that the user will not be able to log in
2688 * through the web interface.
2690 public function setInternalPassword( $str ) {
2691 wfDeprecated( __METHOD__
, '1.27' );
2692 $this->setPasswordInternal( $str );
2696 * Actually set the password and such
2697 * @since 1.27 cannot set a password for a user not in the database
2698 * @param string|null $str New password to set or null to set an invalid
2699 * password hash meaning that the user will not be able to log in
2700 * through the web interface.
2701 * @return bool Success
2703 private function setPasswordInternal( $str ) {
2704 $manager = AuthManager
::singleton();
2706 // If the user doesn't exist yet, fail
2707 if ( !$manager->userExists( $this->getName() ) ) {
2708 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2711 $status = $this->changeAuthenticationData( [
2712 'username' => $this->getName(),
2716 if ( !$status->isGood() ) {
2717 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2718 ->info( __METHOD__
. ': Password change rejected: '
2719 . $status->getWikiText( null, null, 'en' ) );
2723 $this->setOption( 'watchlisttoken', false );
2724 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2730 * Changes credentials of the user.
2732 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2733 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2734 * e.g. when no provider handled the change.
2736 * @param array $data A set of authentication data in fieldname => value format. This is the
2737 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2741 public function changeAuthenticationData( array $data ) {
2742 $manager = AuthManager
::singleton();
2743 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2744 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2746 $status = Status
::newGood( 'ignored' );
2747 foreach ( $reqs as $req ) {
2748 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2750 if ( $status->getValue() === 'ignored' ) {
2751 $status->warning( 'authenticationdatachange-ignored' );
2754 if ( $status->isGood() ) {
2755 foreach ( $reqs as $req ) {
2756 $manager->changeAuthenticationData( $req );
2763 * Get the user's current token.
2764 * @param bool $forceCreation Force the generation of a new token if the
2765 * user doesn't have one (default=true for backwards compatibility).
2766 * @return string|null Token
2768 public function getToken( $forceCreation = true ) {
2769 global $wgAuthenticationTokenVersion;
2772 if ( !$this->mToken
&& $forceCreation ) {
2776 if ( !$this->mToken
) {
2777 // The user doesn't have a token, return null to indicate that.
2781 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2782 // We return a random value here so existing token checks are very
2784 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2787 if ( $wgAuthenticationTokenVersion === null ) {
2788 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2789 return $this->mToken
;
2792 // $wgAuthenticationTokenVersion in use, so hmac it.
2793 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2795 // The raw hash can be overly long. Shorten it up.
2796 $len = max( 32, self
::TOKEN_LENGTH
);
2797 if ( strlen( $ret ) < $len ) {
2798 // Should never happen, even md5 is 128 bits
2799 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2802 return substr( $ret, -$len );
2806 * Set the random token (used for persistent authentication)
2807 * Called from loadDefaults() among other places.
2809 * @param string|bool $token If specified, set the token to this value
2811 public function setToken( $token = false ) {
2813 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2814 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2815 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2816 } elseif ( !$token ) {
2817 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2819 $this->mToken
= $token;
2824 * Set the password for a password reminder or new account email
2826 * @deprecated Removed in 1.27. Use PasswordReset instead.
2827 * @param string $str New password to set or null to set an invalid
2828 * password hash meaning that the user will not be able to use it
2829 * @param bool $throttle If true, reset the throttle timestamp to the present
2831 public function setNewpassword( $str, $throttle = true ) {
2832 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2836 * Get the user's e-mail address
2837 * @return string User's email address
2839 public function getEmail() {
2841 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2842 return $this->mEmail
;
2846 * Get the timestamp of the user's e-mail authentication
2847 * @return string TS_MW timestamp
2849 public function getEmailAuthenticationTimestamp() {
2851 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2852 return $this->mEmailAuthenticated
;
2856 * Set the user's e-mail address
2857 * @param string $str New e-mail address
2859 public function setEmail( $str ) {
2861 if ( $str == $this->mEmail
) {
2864 $this->invalidateEmail();
2865 $this->mEmail
= $str;
2866 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2870 * Set the user's e-mail address and a confirmation mail if needed.
2873 * @param string $str New e-mail address
2876 public function setEmailWithConfirmation( $str ) {
2877 global $wgEnableEmail, $wgEmailAuthentication;
2879 if ( !$wgEnableEmail ) {
2880 return Status
::newFatal( 'emaildisabled' );
2883 $oldaddr = $this->getEmail();
2884 if ( $str === $oldaddr ) {
2885 return Status
::newGood( true );
2888 $type = $oldaddr != '' ?
'changed' : 'set';
2889 $notificationResult = null;
2891 if ( $wgEmailAuthentication && $type === 'changed' ) {
2892 // Send the user an email notifying the user of the change in registered
2893 // email address on their previous email address
2894 $change = $str != '' ?
'changed' : 'removed';
2895 $notificationResult = $this->sendMail(
2896 wfMessage( 'notificationemail_subject_' . $change )->text(),
2897 wfMessage( 'notificationemail_body_' . $change,
2898 $this->getRequest()->getIP(),
2904 $this->setEmail( $str );
2906 if ( $str !== '' && $wgEmailAuthentication ) {
2907 // Send a confirmation request to the new address if needed
2908 $result = $this->sendConfirmationMail( $type );
2910 if ( $notificationResult !== null ) {
2911 $result->merge( $notificationResult );
2914 if ( $result->isGood() ) {
2915 // Say to the caller that a confirmation and notification mail has been sent
2916 $result->value
= 'eauth';
2919 $result = Status
::newGood( true );
2926 * Get the user's real name
2927 * @return string User's real name
2929 public function getRealName() {
2930 if ( !$this->isItemLoaded( 'realname' ) ) {
2934 return $this->mRealName
;
2938 * Set the user's real name
2939 * @param string $str New real name
2941 public function setRealName( $str ) {
2943 $this->mRealName
= $str;
2947 * Get the user's current setting for a given option.
2949 * @param string $oname The option to check
2950 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2951 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2952 * @return string|array|int|null User's current value for the option
2953 * @see getBoolOption()
2954 * @see getIntOption()
2956 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2957 global $wgHiddenPrefs;
2958 $this->loadOptions();
2960 # We want 'disabled' preferences to always behave as the default value for
2961 # users, even if they have set the option explicitly in their settings (ie they
2962 # set it, and then it was disabled removing their ability to change it). But
2963 # we don't want to erase the preferences in the database in case the preference
2964 # is re-enabled again. So don't touch $mOptions, just override the returned value
2965 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2966 return self
::getDefaultOption( $oname );
2969 if ( array_key_exists( $oname, $this->mOptions
) ) {
2970 return $this->mOptions
[$oname];
2973 return $defaultOverride;
2977 * Get all user's options
2979 * @param int $flags Bitwise combination of:
2980 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2981 * to the default value. (Since 1.25)
2984 public function getOptions( $flags = 0 ) {
2985 global $wgHiddenPrefs;
2986 $this->loadOptions();
2987 $options = $this->mOptions
;
2989 # We want 'disabled' preferences to always behave as the default value for
2990 # users, even if they have set the option explicitly in their settings (ie they
2991 # set it, and then it was disabled removing their ability to change it). But
2992 # we don't want to erase the preferences in the database in case the preference
2993 # is re-enabled again. So don't touch $mOptions, just override the returned value
2994 foreach ( $wgHiddenPrefs as $pref ) {
2995 $default = self
::getDefaultOption( $pref );
2996 if ( $default !== null ) {
2997 $options[$pref] = $default;
3001 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3002 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3009 * Get the user's current setting for a given option, as a boolean value.
3011 * @param string $oname The option to check
3012 * @return bool User's current value for the option
3015 public function getBoolOption( $oname ) {
3016 return (bool)$this->getOption( $oname );
3020 * Get the user's current setting for a given option, as an integer value.
3022 * @param string $oname The option to check
3023 * @param int $defaultOverride A default value returned if the option does not exist
3024 * @return int User's current value for the option
3027 public function getIntOption( $oname, $defaultOverride = 0 ) {
3028 $val = $this->getOption( $oname );
3030 $val = $defaultOverride;
3032 return intval( $val );
3036 * Set the given option for a user.
3038 * You need to call saveSettings() to actually write to the database.
3040 * @param string $oname The option to set
3041 * @param mixed $val New value to set
3043 public function setOption( $oname, $val ) {
3044 $this->loadOptions();
3046 // Explicitly NULL values should refer to defaults
3047 if ( is_null( $val ) ) {
3048 $val = self
::getDefaultOption( $oname );
3051 $this->mOptions
[$oname] = $val;
3055 * Get a token stored in the preferences (like the watchlist one),
3056 * resetting it if it's empty (and saving changes).
3058 * @param string $oname The option name to retrieve the token from
3059 * @return string|bool User's current value for the option, or false if this option is disabled.
3060 * @see resetTokenFromOption()
3062 * @deprecated since 1.26 Applications should use the OAuth extension
3064 public function getTokenFromOption( $oname ) {
3065 global $wgHiddenPrefs;
3067 $id = $this->getId();
3068 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3072 $token = $this->getOption( $oname );
3074 // Default to a value based on the user token to avoid space
3075 // wasted on storing tokens for all users. When this option
3076 // is set manually by the user, only then is it stored.
3077 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3084 * Reset a token stored in the preferences (like the watchlist one).
3085 * *Does not* save user's preferences (similarly to setOption()).
3087 * @param string $oname The option name to reset the token in
3088 * @return string|bool New token value, or false if this option is disabled.
3089 * @see getTokenFromOption()
3092 public function resetTokenFromOption( $oname ) {
3093 global $wgHiddenPrefs;
3094 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3098 $token = MWCryptRand
::generateHex( 40 );
3099 $this->setOption( $oname, $token );
3104 * Return a list of the types of user options currently returned by
3105 * User::getOptionKinds().
3107 * Currently, the option kinds are:
3108 * - 'registered' - preferences which are registered in core MediaWiki or
3109 * by extensions using the UserGetDefaultOptions hook.
3110 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3111 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3112 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3113 * be used by user scripts.
3114 * - 'special' - "preferences" that are not accessible via User::getOptions
3115 * or User::setOptions.
3116 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3117 * These are usually legacy options, removed in newer versions.
3119 * The API (and possibly others) use this function to determine the possible
3120 * option types for validation purposes, so make sure to update this when a
3121 * new option kind is added.
3123 * @see User::getOptionKinds
3124 * @return array Option kinds
3126 public static function listOptionKinds() {
3129 'registered-multiselect',
3130 'registered-checkmatrix',
3138 * Return an associative array mapping preferences keys to the kind of a preference they're
3139 * used for. Different kinds are handled differently when setting or reading preferences.
3141 * See User::listOptionKinds for the list of valid option types that can be provided.
3143 * @see User::listOptionKinds
3144 * @param IContextSource $context
3145 * @param array|null $options Assoc. array with options keys to check as keys.
3146 * Defaults to $this->mOptions.
3147 * @return array The key => kind mapping data
3149 public function getOptionKinds( IContextSource
$context, $options = null ) {
3150 $this->loadOptions();
3151 if ( $options === null ) {
3152 $options = $this->mOptions
;
3155 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3156 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3159 // Pull out the "special" options, so they don't get converted as
3160 // multiselect or checkmatrix.
3161 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3162 foreach ( $specialOptions as $name => $value ) {
3163 unset( $prefs[$name] );
3166 // Multiselect and checkmatrix options are stored in the database with
3167 // one key per option, each having a boolean value. Extract those keys.
3168 $multiselectOptions = [];
3169 foreach ( $prefs as $name => $info ) {
3170 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3171 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3172 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3173 $prefix = $info['prefix'] ??
$name;
3175 foreach ( $opts as $value ) {
3176 $multiselectOptions["$prefix$value"] = true;
3179 unset( $prefs[$name] );
3182 $checkmatrixOptions = [];
3183 foreach ( $prefs as $name => $info ) {
3184 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3185 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3186 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3187 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3188 $prefix = $info['prefix'] ??
$name;
3190 foreach ( $columns as $column ) {
3191 foreach ( $rows as $row ) {
3192 $checkmatrixOptions["$prefix$column-$row"] = true;
3196 unset( $prefs[$name] );
3200 // $value is ignored
3201 foreach ( $options as $key => $value ) {
3202 if ( isset( $prefs[$key] ) ) {
3203 $mapping[$key] = 'registered';
3204 } elseif ( isset( $multiselectOptions[$key] ) ) {
3205 $mapping[$key] = 'registered-multiselect';
3206 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3207 $mapping[$key] = 'registered-checkmatrix';
3208 } elseif ( isset( $specialOptions[$key] ) ) {
3209 $mapping[$key] = 'special';
3210 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3211 $mapping[$key] = 'userjs';
3213 $mapping[$key] = 'unused';
3221 * Reset certain (or all) options to the site defaults
3223 * The optional parameter determines which kinds of preferences will be reset.
3224 * Supported values are everything that can be reported by getOptionKinds()
3225 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3227 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3228 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3229 * for backwards-compatibility.
3230 * @param IContextSource|null $context Context source used when $resetKinds
3231 * does not contain 'all', passed to getOptionKinds().
3232 * Defaults to RequestContext::getMain() when null.
3234 public function resetOptions(
3235 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3236 IContextSource
$context = null
3239 $defaultOptions = self
::getDefaultOptions();
3241 if ( !is_array( $resetKinds ) ) {
3242 $resetKinds = [ $resetKinds ];
3245 if ( in_array( 'all', $resetKinds ) ) {
3246 $newOptions = $defaultOptions;
3248 if ( $context === null ) {
3249 $context = RequestContext
::getMain();
3252 $optionKinds = $this->getOptionKinds( $context );
3253 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3256 // Use default values for the options that should be deleted, and
3257 // copy old values for the ones that shouldn't.
3258 foreach ( $this->mOptions
as $key => $value ) {
3259 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3260 if ( array_key_exists( $key, $defaultOptions ) ) {
3261 $newOptions[$key] = $defaultOptions[$key];
3264 $newOptions[$key] = $value;
3269 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3271 $this->mOptions
= $newOptions;
3272 $this->mOptionsLoaded
= true;
3276 * Get the user's preferred date format.
3277 * @return string User's preferred date format
3279 public function getDatePreference() {
3280 // Important migration for old data rows
3281 if ( is_null( $this->mDatePreference
) ) {
3283 $value = $this->getOption( 'date' );
3284 $map = $wgLang->getDatePreferenceMigrationMap();
3285 if ( isset( $map[$value] ) ) {
3286 $value = $map[$value];
3288 $this->mDatePreference
= $value;
3290 return $this->mDatePreference
;
3294 * Determine based on the wiki configuration and the user's options,
3295 * whether this user must be over HTTPS no matter what.
3299 public function requiresHTTPS() {
3300 global $wgSecureLogin;
3301 if ( !$wgSecureLogin ) {
3305 $https = $this->getBoolOption( 'prefershttps' );
3306 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3308 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3315 * Get the user preferred stub threshold
3319 public function getStubThreshold() {
3320 global $wgMaxArticleSize; # Maximum article size, in Kb
3321 $threshold = $this->getIntOption( 'stubthreshold' );
3322 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3323 // If they have set an impossible value, disable the preference
3324 // so we can use the parser cache again.
3331 * Get the permissions this user has.
3332 * @return string[] permission names
3334 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3335 * ->getUserPermissions(..) instead
3338 public function getRights() {
3339 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3343 * Get the list of explicit group memberships this user has.
3344 * The implicit * and user groups are not included.
3346 * @return string[] Array of internal group names (sorted since 1.33)
3348 public function getGroups() {
3350 $this->loadGroups();
3351 return array_keys( $this->mGroupMemberships
);
3355 * Get the list of explicit group memberships this user has, stored as
3356 * UserGroupMembership objects. Implicit groups are not included.
3358 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3361 public function getGroupMemberships() {
3363 $this->loadGroups();
3364 return $this->mGroupMemberships
;
3368 * Get the list of implicit group memberships this user has.
3369 * This includes all explicit groups, plus 'user' if logged in,
3370 * '*' for all accounts, and autopromoted groups
3371 * @param bool $recache Whether to avoid the cache
3372 * @return array Array of String internal group names
3374 public function getEffectiveGroups( $recache = false ) {
3375 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3376 $this->mEffectiveGroups
= array_unique( array_merge(
3377 $this->getGroups(), // explicit groups
3378 $this->getAutomaticGroups( $recache ) // implicit groups
3380 // Avoid PHP 7.1 warning of passing $this by reference
3382 // Hook for additional groups
3383 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3384 // Force reindexation of groups when a hook has unset one of them
3385 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3387 return $this->mEffectiveGroups
;
3391 * Get the list of implicit group memberships this user has.
3392 * This includes 'user' if logged in, '*' for all accounts,
3393 * and autopromoted groups
3394 * @param bool $recache Whether to avoid the cache
3395 * @return array Array of String internal group names
3397 public function getAutomaticGroups( $recache = false ) {
3398 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3399 $this->mImplicitGroups
= [ '*' ];
3400 if ( $this->getId() ) {
3401 $this->mImplicitGroups
[] = 'user';
3403 $this->mImplicitGroups
= array_unique( array_merge(
3404 $this->mImplicitGroups
,
3405 Autopromote
::getAutopromoteGroups( $this )
3409 // Assure data consistency with rights/groups,
3410 // as getEffectiveGroups() depends on this function
3411 $this->mEffectiveGroups
= null;
3414 return $this->mImplicitGroups
;
3418 * Returns the groups the user has belonged to.
3420 * The user may still belong to the returned groups. Compare with getGroups().
3422 * The function will not return groups the user had belonged to before MW 1.17
3424 * @return array Names of the groups the user has belonged to.
3426 public function getFormerGroups() {
3429 if ( is_null( $this->mFormerGroups
) ) {
3430 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3431 ?
wfGetDB( DB_MASTER
)
3432 : wfGetDB( DB_REPLICA
);
3433 $res = $db->select( 'user_former_groups',
3435 [ 'ufg_user' => $this->mId
],
3437 $this->mFormerGroups
= [];
3438 foreach ( $res as $row ) {
3439 $this->mFormerGroups
[] = $row->ufg_group
;
3443 return $this->mFormerGroups
;
3447 * Get the user's edit count.
3448 * @return int|null Null for anonymous users
3450 public function getEditCount() {
3451 if ( !$this->getId() ) {
3455 if ( $this->mEditCount
=== null ) {
3456 /* Populate the count, if it has not been populated yet */
3457 $dbr = wfGetDB( DB_REPLICA
);
3458 // check if the user_editcount field has been initialized
3459 $count = $dbr->selectField(
3460 'user', 'user_editcount',
3461 [ 'user_id' => $this->mId
],
3465 if ( $count === null ) {
3466 // it has not been initialized. do so.
3467 $count = $this->initEditCountInternal( $dbr );
3469 $this->mEditCount
= $count;
3471 return (int)$this->mEditCount
;
3475 * Add the user to the given group. This takes immediate effect.
3476 * If the user is already in the group, the expiry time will be updated to the new
3477 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3480 * @param string $group Name of the group to add
3481 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3482 * wfTimestamp(), or null if the group assignment should not expire
3485 public function addGroup( $group, $expiry = null ) {
3487 $this->loadGroups();
3490 $expiry = wfTimestamp( TS_MW
, $expiry );
3493 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3497 // create the new UserGroupMembership and put it in the DB
3498 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3499 if ( !$ugm->insert( true ) ) {
3503 $this->mGroupMemberships
[$group] = $ugm;
3505 // Refresh the groups caches, and clear the rights cache so it will be
3506 // refreshed on the next call to $this->getRights().
3507 $this->getEffectiveGroups( true );
3508 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3509 $this->invalidateCache();
3515 * Remove the user from the given group.
3516 * This takes immediate effect.
3517 * @param string $group Name of the group to remove
3520 public function removeGroup( $group ) {
3523 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3527 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3528 // delete the membership entry
3529 if ( !$ugm ||
!$ugm->delete() ) {
3533 $this->loadGroups();
3534 unset( $this->mGroupMemberships
[$group] );
3536 // Refresh the groups caches, and clear the rights cache so it will be
3537 // refreshed on the next call to $this->getRights().
3538 $this->getEffectiveGroups( true );
3539 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3540 $this->invalidateCache();
3546 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3547 * only this new name and not the old isLoggedIn() variant.
3549 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3550 * anonymous or has no local account (which can happen when importing). This is equivalent to
3551 * getId() != 0 and is provided for code readability.
3554 public function isRegistered() {
3555 return $this->getId() != 0;
3559 * Get whether the user is logged in
3562 public function isLoggedIn() {
3563 return $this->isRegistered();
3567 * Get whether the user is anonymous
3570 public function isAnon() {
3571 return !$this->isRegistered();
3575 * @return bool Whether this user is flagged as being a bot role account
3578 public function isBot() {
3579 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3584 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3590 * Check if user is allowed to access a feature / make an action
3592 * @param string $permissions,... Permissions to test
3593 * @return bool True if user is allowed to perform *any* of the given actions
3595 public function isAllowedAny() {
3596 $permissions = func_get_args();
3597 foreach ( $permissions as $permission ) {
3598 if ( $this->isAllowed( $permission ) ) {
3607 * @param string $permissions,... Permissions to test
3608 * @return bool True if the user is allowed to perform *all* of the given actions
3610 public function isAllowedAll() {
3611 $permissions = func_get_args();
3612 foreach ( $permissions as $permission ) {
3613 if ( !$this->isAllowed( $permission ) ) {
3621 * Internal mechanics of testing a permission
3623 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3624 * ->getPermissionManager()->userHasRight(...) instead
3626 * @param string $action
3630 public function isAllowed( $action = '' ) {
3631 return MediaWikiServices
::getInstance()->getPermissionManager()
3632 ->userHasRight( $this, $action );
3636 * Check whether to enable recent changes patrol features for this user
3637 * @return bool True or false
3639 public function useRCPatrol() {
3640 global $wgUseRCPatrol;
3641 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3645 * Check whether to enable new pages patrol features for this user
3646 * @return bool True or false
3648 public function useNPPatrol() {
3649 global $wgUseRCPatrol, $wgUseNPPatrol;
3651 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3652 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3657 * Check whether to enable new files patrol features for this user
3658 * @return bool True or false
3660 public function useFilePatrol() {
3661 global $wgUseRCPatrol, $wgUseFilePatrol;
3663 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3664 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3669 * Get the WebRequest object to use with this object
3671 * @return WebRequest
3673 public function getRequest() {
3674 if ( $this->mRequest
) {
3675 return $this->mRequest
;
3683 * Check the watched status of an article.
3684 * @since 1.22 $checkRights parameter added
3685 * @param Title $title Title of the article to look at
3686 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3687 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3690 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3691 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3692 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3699 * @since 1.22 $checkRights parameter added
3700 * @param Title $title Title of the article to look at
3701 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3702 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3704 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3705 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3706 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3708 [ $title->getSubjectPage(), $title->getTalkPage() ]
3711 $this->invalidateCache();
3715 * Stop watching an article.
3716 * @since 1.22 $checkRights parameter added
3717 * @param Title $title Title of the article to look at
3718 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3719 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3721 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3722 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3723 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3724 $store->removeWatch( $this, $title->getSubjectPage() );
3725 $store->removeWatch( $this, $title->getTalkPage() );
3727 $this->invalidateCache();
3731 * Clear the user's notification timestamp for the given title.
3732 * If e-notif e-mails are on, they will receive notification mails on
3733 * the next change of the page if it's watched etc.
3734 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3735 * @param Title &$title Title of the article to look at
3736 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3738 public function clearNotification( &$title, $oldid = 0 ) {
3739 global $wgUseEnotif, $wgShowUpdatedMarker;
3741 // Do nothing if the database is locked to writes
3742 if ( wfReadOnly() ) {
3746 // Do nothing if not allowed to edit the watchlist
3747 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3751 // If we're working on user's talk page, we should update the talk page message indicator
3752 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3753 // Avoid PHP 7.1 warning of passing $this by reference
3755 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3759 // Try to update the DB post-send and only if needed...
3760 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3761 if ( !$this->getNewtalk() ) {
3762 return; // no notifications to clear
3765 // Delete the last notifications (they stack up)
3766 $this->setNewtalk( false );
3768 // If there is a new, unseen, revision, use its timestamp
3770 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3773 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3778 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3782 if ( $this->isAnon() ) {
3783 // Nothing else to do...
3787 // Only update the timestamp if the page is being watched.
3788 // The query to find out if it is watched is cached both in memcached and per-invocation,
3789 // and when it does have to be executed, it can be on a replica DB
3790 // If this is the user's newtalk page, we always update the timestamp
3792 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3796 MediaWikiServices
::getInstance()->getWatchedItemStore()
3797 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3801 * Resets all of the given user's page-change notification timestamps.
3802 * If e-notif e-mails are on, they will receive notification mails on
3803 * the next change of any watched page.
3804 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3806 public function clearAllNotifications() {
3807 global $wgUseEnotif, $wgShowUpdatedMarker;
3808 // Do nothing if not allowed to edit the watchlist
3809 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3813 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3814 $this->setNewtalk( false );
3818 $id = $this->getId();
3823 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3824 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3826 // We also need to clear here the "you have new message" notification for the own
3827 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3831 * Compute experienced level based on edit count and registration date.
3833 * @return string 'newcomer', 'learner', or 'experienced'
3835 public function getExperienceLevel() {
3836 global $wgLearnerEdits,
3837 $wgExperiencedUserEdits,
3838 $wgLearnerMemberSince,
3839 $wgExperiencedUserMemberSince;
3841 if ( $this->isAnon() ) {
3845 $editCount = $this->getEditCount();
3846 $registration = $this->getRegistration();
3848 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3849 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3851 if ( $editCount < $wgLearnerEdits ||
3852 $registration > $learnerRegistration ) {
3856 if ( $editCount > $wgExperiencedUserEdits &&
3857 $registration <= $experiencedRegistration
3859 return 'experienced';
3866 * Persist this user's session (e.g. set cookies)
3868 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3870 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3871 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3873 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3875 if ( $this->mId
== 0 ) {
3879 $session = $this->getRequest()->getSession();
3880 if ( $request && $session->getRequest() !== $request ) {
3881 $session = $session->sessionWithRequest( $request );
3883 $delay = $session->delaySave();
3885 if ( !$session->getUser()->equals( $this ) ) {
3886 if ( !$session->canSetUser() ) {
3887 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3888 ->warning( __METHOD__
.
3889 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3893 $session->setUser( $this );
3896 $session->setRememberUser( $rememberMe );
3897 if ( $secure !== null ) {
3898 $session->setForceHTTPS( $secure );
3901 $session->persist();
3903 ScopedCallback
::consume( $delay );
3907 * Log this user out.
3909 public function logout() {
3910 // Avoid PHP 7.1 warning of passing $this by reference
3912 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3918 * Clear the user's session, and reset the instance cache.
3921 public function doLogout() {
3922 $session = $this->getRequest()->getSession();
3923 if ( !$session->canSetUser() ) {
3924 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3925 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3926 $error = 'immutable';
3927 } elseif ( !$session->getUser()->equals( $this ) ) {
3928 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3929 ->warning( __METHOD__
.
3930 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3932 // But we still may as well make this user object anon
3933 $this->clearInstanceCache( 'defaults' );
3934 $error = 'wronguser';
3936 $this->clearInstanceCache( 'defaults' );
3937 $delay = $session->delaySave();
3938 $session->unpersist(); // Clear cookies (T127436)
3939 $session->setLoggedOutTimestamp( time() );
3940 $session->setUser( new User
);
3941 $session->set( 'wsUserID', 0 ); // Other code expects this
3942 $session->resetAllTokens();
3943 ScopedCallback
::consume( $delay );
3946 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3947 'event' => 'logout',
3948 'successful' => $error === false,
3949 'status' => $error ?
: 'success',
3954 * Save this user's settings into the database.
3955 * @todo Only rarely do all these fields need to be set!
3957 public function saveSettings() {
3958 if ( wfReadOnly() ) {
3959 // @TODO: caller should deal with this instead!
3960 // This should really just be an exception.
3961 MWExceptionHandler
::logException( new DBExpectedError(
3963 "Could not update user with ID '{$this->mId}'; DB is read-only."
3969 if ( $this->mId
== 0 ) {
3973 // Get a new user_touched that is higher than the old one.
3974 // This will be used for a CAS check as a last-resort safety
3975 // check against race conditions and replica DB lag.
3976 $newTouched = $this->newTouchedTimestamp();
3978 $dbw = wfGetDB( DB_MASTER
);
3979 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3980 global $wgActorTableSchemaMigrationStage;
3982 $dbw->update( 'user',
3984 'user_name' => $this->mName
,
3985 'user_real_name' => $this->mRealName
,
3986 'user_email' => $this->mEmail
,
3987 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3988 'user_touched' => $dbw->timestamp( $newTouched ),
3989 'user_token' => strval( $this->mToken
),
3990 'user_email_token' => $this->mEmailToken
,
3991 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3992 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3993 'user_id' => $this->mId
,
3997 if ( !$dbw->affectedRows() ) {
3998 // Maybe the problem was a missed cache update; clear it to be safe
3999 $this->clearSharedCache( 'refresh' );
4000 // User was changed in the meantime or loaded with stale data
4001 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4002 LoggerFactory
::getInstance( 'preferences' )->warning(
4003 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4004 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4006 throw new MWException( "CAS update failed on user_touched. " .
4007 "The version of the user to be saved is older than the current version."
4011 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4014 [ 'actor_name' => $this->mName
],
4015 [ 'actor_user' => $this->mId
],
4021 $this->mTouched
= $newTouched;
4022 $this->saveOptions();
4024 Hooks
::run( 'UserSaveSettings', [ $this ] );
4025 $this->clearSharedCache( 'changed' );
4026 $this->getUserPage()->purgeSquid();
4030 * If only this user's username is known, and it exists, return the user ID.
4032 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4035 public function idForName( $flags = 0 ) {
4036 $s = trim( $this->getName() );
4041 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4042 ?
wfGetDB( DB_MASTER
)
4043 : wfGetDB( DB_REPLICA
);
4045 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4046 ?
[ 'LOCK IN SHARE MODE' ]
4049 $id = $db->selectField( 'user',
4050 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4056 * Add a user to the database, return the user object
4058 * @param string $name Username to add
4059 * @param array $params Array of Strings Non-default parameters to save to
4060 * the database as user_* fields:
4061 * - email: The user's email address.
4062 * - email_authenticated: The email authentication timestamp.
4063 * - real_name: The user's real name.
4064 * - options: An associative array of non-default options.
4065 * - token: Random authentication token. Do not set.
4066 * - registration: Registration timestamp. Do not set.
4068 * @return User|null User object, or null if the username already exists.
4070 public static function createNew( $name, $params = [] ) {
4071 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4072 if ( isset( $params[$field] ) ) {
4073 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4074 unset( $params[$field] );
4080 $user->setToken(); // init token
4081 if ( isset( $params['options'] ) ) {
4082 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4083 unset( $params['options'] );
4085 $dbw = wfGetDB( DB_MASTER
);
4087 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4090 'user_name' => $name,
4091 'user_password' => $noPass,
4092 'user_newpassword' => $noPass,
4093 'user_email' => $user->mEmail
,
4094 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4095 'user_real_name' => $user->mRealName
,
4096 'user_token' => strval( $user->mToken
),
4097 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4098 'user_editcount' => 0,
4099 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4101 foreach ( $params as $name => $value ) {
4102 $fields["user_$name"] = $value;
4105 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4106 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4107 if ( $dbw->affectedRows() ) {
4108 $newUser = self
::newFromId( $dbw->insertId() );
4109 $newUser->mName
= $fields['user_name'];
4110 $newUser->updateActorId( $dbw );
4111 // Load the user from master to avoid replica lag
4112 $newUser->load( self
::READ_LATEST
);
4121 * Add this existing user object to the database. If the user already
4122 * exists, a fatal status object is returned, and the user object is
4123 * initialised with the data from the database.
4125 * Previously, this function generated a DB error due to a key conflict
4126 * if the user already existed. Many extension callers use this function
4127 * in code along the lines of:
4129 * $user = User::newFromName( $name );
4130 * if ( !$user->isLoggedIn() ) {
4131 * $user->addToDatabase();
4133 * // do something with $user...
4135 * However, this was vulnerable to a race condition (T18020). By
4136 * initialising the user object if the user exists, we aim to support this
4137 * calling sequence as far as possible.
4139 * Note that if the user exists, this function will acquire a write lock,
4140 * so it is still advisable to make the call conditional on isLoggedIn(),
4141 * and to commit the transaction after calling.
4143 * @throws MWException
4146 public function addToDatabase() {
4148 if ( !$this->mToken
) {
4149 $this->setToken(); // init token
4152 if ( !is_string( $this->mName
) ) {
4153 throw new RuntimeException( "User name field is not set." );
4156 $this->mTouched
= $this->newTouchedTimestamp();
4158 $dbw = wfGetDB( DB_MASTER
);
4159 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4160 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4161 $dbw->insert( 'user',
4163 'user_name' => $this->mName
,
4164 'user_password' => $noPass,
4165 'user_newpassword' => $noPass,
4166 'user_email' => $this->mEmail
,
4167 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4168 'user_real_name' => $this->mRealName
,
4169 'user_token' => strval( $this->mToken
),
4170 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4171 'user_editcount' => 0,
4172 'user_touched' => $dbw->timestamp( $this->mTouched
),
4176 if ( !$dbw->affectedRows() ) {
4177 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4178 $this->mId
= $dbw->selectField(
4181 [ 'user_name' => $this->mName
],
4183 [ 'LOCK IN SHARE MODE' ]
4186 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4190 throw new MWException( $fname . ": hit a key conflict attempting " .
4191 "to insert user '{$this->mName}' row, but it was not present in select!" );
4193 return Status
::newFatal( 'userexists' );
4195 $this->mId
= $dbw->insertId();
4196 self
::$idCacheByName[$this->mName
] = $this->mId
;
4197 $this->updateActorId( $dbw );
4199 return Status
::newGood();
4201 if ( !$status->isGood() ) {
4205 // Clear instance cache other than user table data and actor, which is already accurate
4206 $this->clearInstanceCache();
4208 $this->saveOptions();
4209 return Status
::newGood();
4213 * Update the actor ID after an insert
4214 * @param IDatabase $dbw Writable database handle
4216 private function updateActorId( IDatabase
$dbw ) {
4217 global $wgActorTableSchemaMigrationStage;
4219 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4222 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4225 $this->mActorId
= (int)$dbw->insertId();
4230 * If this user is logged-in and blocked,
4231 * block any IP address they've successfully logged in from.
4232 * @return bool A block was spread
4234 public function spreadAnyEditBlock() {
4235 if ( $this->isLoggedIn() && $this->getBlock() ) {
4236 return $this->spreadBlock();
4243 * If this (non-anonymous) user is blocked,
4244 * block the IP address they've successfully logged in from.
4245 * @return bool A block was spread
4247 protected function spreadBlock() {
4248 wfDebug( __METHOD__
. "()\n" );
4250 if ( $this->mId
== 0 ) {
4254 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4255 if ( !$userblock ) {
4259 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4263 * Get whether the user is explicitly blocked from account creation.
4264 * @return bool|AbstractBlock
4266 public function isBlockedFromCreateAccount() {
4267 $this->getBlockedStatus();
4268 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4269 return $this->mBlock
;
4272 # T15611: if the IP address the user is trying to create an account from is
4273 # blocked with createaccount disabled, prevent new account creation there even
4274 # when the user is logged in
4275 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4276 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4277 null, $this->getRequest()->getIP()
4280 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4281 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4282 ?
$this->mBlockedFromCreateAccount
4287 * Get whether the user is blocked from using Special:Emailuser.
4290 public function isBlockedFromEmailuser() {
4291 $this->getBlockedStatus();
4292 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4296 * Get whether the user is blocked from using Special:Upload
4301 public function isBlockedFromUpload() {
4302 $this->getBlockedStatus();
4303 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4307 * Get whether the user is allowed to create an account.
4310 public function isAllowedToCreateAccount() {
4311 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4315 * Get this user's personal page title.
4317 * @return Title User's personal page title
4319 public function getUserPage() {
4320 return Title
::makeTitle( NS_USER
, $this->getName() );
4324 * Get this user's talk page title.
4326 * @return Title User's talk page title
4328 public function getTalkPage() {
4329 $title = $this->getUserPage();
4330 return $title->getTalkPage();
4334 * Determine whether the user is a newbie. Newbies are either
4335 * anonymous IPs, or the most recently created accounts.
4338 public function isNewbie() {
4339 return !$this->isAllowed( 'autoconfirmed' );
4343 * Check to see if the given clear-text password is one of the accepted passwords
4344 * @deprecated since 1.27, use AuthManager instead
4345 * @param string $password User password
4346 * @return bool True if the given password is correct, otherwise False
4348 public function checkPassword( $password ) {
4349 wfDeprecated( __METHOD__
, '1.27' );
4351 $manager = AuthManager
::singleton();
4352 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4353 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4355 'username' => $this->getName(),
4356 'password' => $password,
4359 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4360 switch ( $res->status
) {
4361 case AuthenticationResponse
::PASS
:
4363 case AuthenticationResponse
::FAIL
:
4364 // Hope it's not a PreAuthenticationProvider that failed...
4365 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4366 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4369 throw new BadMethodCallException(
4370 'AuthManager returned a response unsupported by ' . __METHOD__
4376 * Check if the given clear-text password matches the temporary password
4377 * sent by e-mail for password reset operations.
4379 * @deprecated since 1.27, use AuthManager instead
4380 * @param string $plaintext
4381 * @return bool True if matches, false otherwise
4383 public function checkTemporaryPassword( $plaintext ) {
4384 wfDeprecated( __METHOD__
, '1.27' );
4385 // Can't check the temporary password individually.
4386 return $this->checkPassword( $plaintext );
4390 * Initialize (if necessary) and return a session token value
4391 * which can be used in edit forms to show that the user's
4392 * login credentials aren't being hijacked with a foreign form
4396 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4397 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4398 * @return MediaWiki\Session\Token The new edit token
4400 public function getEditTokenObject( $salt = '', $request = null ) {
4401 if ( $this->isAnon() ) {
4402 return new LoggedOutEditToken();
4406 $request = $this->getRequest();
4408 return $request->getSession()->getToken( $salt );
4412 * Initialize (if necessary) and return a session token value
4413 * which can be used in edit forms to show that the user's
4414 * login credentials aren't being hijacked with a foreign form
4417 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4420 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4421 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4422 * @return string The new edit token
4424 public function getEditToken( $salt = '', $request = null ) {
4425 return $this->getEditTokenObject( $salt, $request )->toString();
4429 * Check given value against the token value stored in the session.
4430 * A match should confirm that the form was submitted from the
4431 * user's own login session, not a form submission from a third-party
4434 * @param string $val Input value to compare
4435 * @param string|array $salt Optional function-specific data for hashing
4436 * @param WebRequest|null $request Object to use or null to use $wgRequest
4437 * @param int|null $maxage Fail tokens older than this, in seconds
4438 * @return bool Whether the token matches
4440 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4441 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4445 * Check given value against the token value stored in the session,
4446 * ignoring the suffix.
4448 * @param string $val Input value to compare
4449 * @param string|array $salt Optional function-specific data for hashing
4450 * @param WebRequest|null $request Object to use or null to use $wgRequest
4451 * @param int|null $maxage Fail tokens older than this, in seconds
4452 * @return bool Whether the token matches
4454 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4455 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4456 return $this->matchEditToken( $val, $salt, $request, $maxage );
4460 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4461 * mail to the user's given address.
4463 * @param string $type Message to send, either "created", "changed" or "set"
4466 public function sendConfirmationMail( $type = 'created' ) {
4468 $expiration = null; // gets passed-by-ref and defined in next line.
4469 $token = $this->confirmationToken( $expiration );
4470 $url = $this->confirmationTokenUrl( $token );
4471 $invalidateURL = $this->invalidationTokenUrl( $token );
4472 $this->saveSettings();
4474 if ( $type == 'created' ||
$type === false ) {
4475 $message = 'confirmemail_body';
4477 } elseif ( $type === true ) {
4478 $message = 'confirmemail_body_changed';
4481 // Messages: confirmemail_body_changed, confirmemail_body_set
4482 $message = 'confirmemail_body_' . $type;
4486 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4487 'body' => wfMessage( $message,
4488 $this->getRequest()->getIP(),
4491 $wgLang->userTimeAndDate( $expiration, $this ),
4493 $wgLang->userDate( $expiration, $this ),
4494 $wgLang->userTime( $expiration, $this ) )->text(),
4500 'ip' => $this->getRequest()->getIP(),
4501 'confirmURL' => $url,
4502 'invalidateURL' => $invalidateURL,
4503 'expiration' => $expiration
4506 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4507 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4511 * Send an e-mail to this user's account. Does not check for
4512 * confirmed status or validity.
4514 * @param string $subject Message subject
4515 * @param string $body Message body
4516 * @param User|null $from Optional sending user; if unspecified, default
4517 * $wgPasswordSender will be used.
4518 * @param MailAddress|null $replyto Reply-To address
4521 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4522 global $wgPasswordSender;
4524 if ( $from instanceof User
) {
4525 $sender = MailAddress
::newFromUser( $from );
4527 $sender = new MailAddress( $wgPasswordSender,
4528 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4530 $to = MailAddress
::newFromUser( $this );
4532 return UserMailer
::send( $to, $sender, $subject, $body, [
4533 'replyTo' => $replyto,
4538 * Generate, store, and return a new e-mail confirmation code.
4539 * A hash (unsalted, since it's used as a key) is stored.
4541 * @note Call saveSettings() after calling this function to commit
4542 * this change to the database.
4544 * @param string &$expiration Accepts the expiration time
4545 * @return string New token
4547 protected function confirmationToken( &$expiration ) {
4548 global $wgUserEmailConfirmationTokenExpiry;
4550 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4551 $expiration = wfTimestamp( TS_MW
, $expires );
4553 $token = MWCryptRand
::generateHex( 32 );
4554 $hash = md5( $token );
4555 $this->mEmailToken
= $hash;
4556 $this->mEmailTokenExpires
= $expiration;
4561 * Return a URL the user can use to confirm their email address.
4562 * @param string $token Accepts the email confirmation token
4563 * @return string New token URL
4565 protected function confirmationTokenUrl( $token ) {
4566 return $this->getTokenUrl( 'ConfirmEmail', $token );
4570 * Return a URL the user can use to invalidate their email address.
4571 * @param string $token Accepts the email confirmation token
4572 * @return string New token URL
4574 protected function invalidationTokenUrl( $token ) {
4575 return $this->getTokenUrl( 'InvalidateEmail', $token );
4579 * Internal function to format the e-mail validation/invalidation URLs.
4580 * This uses a quickie hack to use the
4581 * hardcoded English names of the Special: pages, for ASCII safety.
4583 * @note Since these URLs get dropped directly into emails, using the
4584 * short English names avoids insanely long URL-encoded links, which
4585 * also sometimes can get corrupted in some browsers/mailers
4586 * (T8957 with Gmail and Internet Explorer).
4588 * @param string $page Special page
4589 * @param string $token
4590 * @return string Formatted URL
4592 protected function getTokenUrl( $page, $token ) {
4593 // Hack to bypass localization of 'Special:'
4594 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4595 return $title->getCanonicalURL();
4599 * Mark the e-mail address confirmed.
4601 * @note Call saveSettings() after calling this function to commit the change.
4605 public function confirmEmail() {
4606 // Check if it's already confirmed, so we don't touch the database
4607 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4608 if ( !$this->isEmailConfirmed() ) {
4609 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4610 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4616 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4617 * address if it was already confirmed.
4619 * @note Call saveSettings() after calling this function to commit the change.
4620 * @return bool Returns true
4622 public function invalidateEmail() {
4624 $this->mEmailToken
= null;
4625 $this->mEmailTokenExpires
= null;
4626 $this->setEmailAuthenticationTimestamp( null );
4628 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4633 * Set the e-mail authentication timestamp.
4634 * @param string $timestamp TS_MW timestamp
4636 public function setEmailAuthenticationTimestamp( $timestamp ) {
4638 $this->mEmailAuthenticated
= $timestamp;
4639 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4643 * Is this user allowed to send e-mails within limits of current
4644 * site configuration?
4647 public function canSendEmail() {
4648 global $wgEnableEmail, $wgEnableUserEmail;
4649 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4652 $canSend = $this->isEmailConfirmed();
4653 // Avoid PHP 7.1 warning of passing $this by reference
4655 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4660 * Is this user allowed to receive e-mails within limits of current
4661 * site configuration?
4664 public function canReceiveEmail() {
4665 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4669 * Is this user's e-mail address valid-looking and confirmed within
4670 * limits of the current site configuration?
4672 * @note If $wgEmailAuthentication is on, this may require the user to have
4673 * confirmed their address by returning a code or using a password
4674 * sent to the address from the wiki.
4678 public function isEmailConfirmed() {
4679 global $wgEmailAuthentication;
4681 // Avoid PHP 7.1 warning of passing $this by reference
4684 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4685 if ( $this->isAnon() ) {
4688 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4691 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4701 * Check whether there is an outstanding request for e-mail confirmation.
4704 public function isEmailConfirmationPending() {
4705 global $wgEmailAuthentication;
4706 return $wgEmailAuthentication &&
4707 !$this->isEmailConfirmed() &&
4708 $this->mEmailToken
&&
4709 $this->mEmailTokenExpires
> wfTimestamp();
4713 * Get the timestamp of account creation.
4715 * @return string|bool|null Timestamp of account creation, false for
4716 * non-existent/anonymous user accounts, or null if existing account
4717 * but information is not in database.
4719 public function getRegistration() {
4720 if ( $this->isAnon() ) {
4724 return $this->mRegistration
;
4728 * Get the timestamp of the first edit
4730 * @return string|bool Timestamp of first edit, or false for
4731 * non-existent/anonymous user accounts.
4733 public function getFirstEditTimestamp() {
4734 return $this->getEditTimestamp( true );
4738 * Get the timestamp of the latest edit
4741 * @return string|bool Timestamp of first edit, or false for
4742 * non-existent/anonymous user accounts.
4744 public function getLatestEditTimestamp() {
4745 return $this->getEditTimestamp( false );
4749 * Get the timestamp of the first or latest edit
4751 * @param bool $first True for the first edit, false for the latest one
4752 * @return string|bool Timestamp of first or latest edit, or false for
4753 * non-existent/anonymous user accounts.
4755 private function getEditTimestamp( $first ) {
4756 if ( $this->getId() == 0 ) {
4757 return false; // anons
4759 $dbr = wfGetDB( DB_REPLICA
);
4760 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4761 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4762 ?
'revactor_timestamp' : 'rev_timestamp';
4763 $sortOrder = $first ?
'ASC' : 'DESC';
4764 $time = $dbr->selectField(
4765 [ 'revision' ] +
$actorWhere['tables'],
4767 [ $actorWhere['conds'] ],
4769 [ 'ORDER BY' => "$tsField $sortOrder" ],
4770 $actorWhere['joins']
4773 return false; // no edits
4775 return wfTimestamp( TS_MW
, $time );
4779 * Get the permissions associated with a given list of groups
4781 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4782 * ->getGroupPermissions() instead
4784 * @param array $groups Array of Strings List of internal group names
4785 * @return array Array of Strings List of permission key names for given groups combined
4787 public static function getGroupPermissions( $groups ) {
4788 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4792 * Get all the groups who have a given permission
4794 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4795 * ->getGroupsWithPermission() instead
4797 * @param string $role Role to check
4798 * @return array Array of Strings List of internal group names with the given permission
4800 public static function getGroupsWithPermission( $role ) {
4801 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4805 * Check, if the given group has the given permission
4807 * If you're wanting to check whether all users have a permission, use
4808 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4811 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4812 * ->groupHasPermission(..) instead
4815 * @param string $group Group to check
4816 * @param string $role Role to check
4819 public static function groupHasPermission( $group, $role ) {
4820 return MediaWikiServices
::getInstance()->getPermissionManager()
4821 ->groupHasPermission( $group, $role );
4825 * Check if all users may be assumed to have the given permission
4827 * We generally assume so if the right is granted to '*' and isn't revoked
4828 * on any group. It doesn't attempt to take grants or other extension
4829 * limitations on rights into account in the general case, though, as that
4830 * would require it to always return false and defeat the purpose.
4831 * Specifically, session-based rights restrictions (such as OAuth or bot
4832 * passwords) are applied based on the current session.
4834 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4835 * ->isEveryoneAllowed() instead
4837 * @param string $right Right to check
4842 public static function isEveryoneAllowed( $right ) {
4843 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4847 * Return the set of defined explicit groups.
4848 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4849 * are not included, as they are defined automatically, not in the database.
4850 * @return array Array of internal group names
4852 public static function getAllGroups() {
4853 global $wgGroupPermissions, $wgRevokePermissions;
4854 return array_values( array_diff(
4855 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4856 self
::getImplicitGroups()
4861 * Get a list of all available permissions.
4863 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4864 * ->getAllPermissions() instead
4866 * @return string[] Array of permission names
4868 public static function getAllRights() {
4869 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4873 * Get a list of implicit groups
4874 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4876 * @return array Array of Strings Array of internal group names
4878 public static function getImplicitGroups() {
4879 global $wgImplicitGroups;
4880 return $wgImplicitGroups;
4884 * Returns an array of the groups that a particular group can add/remove.
4886 * @param string $group The group to check for whether it can add/remove
4887 * @return array [ 'add' => [ addablegroups ],
4888 * 'remove' => [ removablegroups ],
4889 * 'add-self' => [ addablegroups to self ],
4890 * 'remove-self' => [ removable groups from self ] ]
4892 public static function changeableByGroup( $group ) {
4893 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4902 if ( empty( $wgAddGroups[$group] ) ) {
4903 // Don't add anything to $groups
4904 } elseif ( $wgAddGroups[$group] === true ) {
4905 // You get everything
4906 $groups['add'] = self
::getAllGroups();
4907 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4908 $groups['add'] = $wgAddGroups[$group];
4911 // Same thing for remove
4912 if ( empty( $wgRemoveGroups[$group] ) ) {
4914 } elseif ( $wgRemoveGroups[$group] === true ) {
4915 $groups['remove'] = self
::getAllGroups();
4916 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4917 $groups['remove'] = $wgRemoveGroups[$group];
4920 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4921 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4922 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4923 if ( is_int( $key ) ) {
4924 $wgGroupsAddToSelf['user'][] = $value;
4929 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4930 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4931 if ( is_int( $key ) ) {
4932 $wgGroupsRemoveFromSelf['user'][] = $value;
4937 // Now figure out what groups the user can add to him/herself
4938 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4940 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4941 // No idea WHY this would be used, but it's there
4942 $groups['add-self'] = self
::getAllGroups();
4943 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4944 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4947 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4949 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4950 $groups['remove-self'] = self
::getAllGroups();
4951 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4952 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4959 * Returns an array of groups that this user can add and remove
4960 * @return array [ 'add' => [ addablegroups ],
4961 * 'remove' => [ removablegroups ],
4962 * 'add-self' => [ addablegroups to self ],
4963 * 'remove-self' => [ removable groups from self ] ]
4965 public function changeableGroups() {
4966 if ( $this->isAllowed( 'userrights' ) ) {
4967 // This group gives the right to modify everything (reverse-
4968 // compatibility with old "userrights lets you change
4970 // Using array_merge to make the groups reindexed
4971 $all = array_merge( self
::getAllGroups() );
4980 // Okay, it's not so simple, we will have to go through the arrays
4987 $addergroups = $this->getEffectiveGroups();
4989 foreach ( $addergroups as $addergroup ) {
4990 $groups = array_merge_recursive(
4991 $groups, $this->changeableByGroup( $addergroup )
4993 $groups['add'] = array_unique( $groups['add'] );
4994 $groups['remove'] = array_unique( $groups['remove'] );
4995 $groups['add-self'] = array_unique( $groups['add-self'] );
4996 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5002 * Schedule a deferred update to update the user's edit count
5004 public function incEditCount() {
5005 if ( $this->isAnon() ) {
5009 DeferredUpdates
::addUpdate(
5010 new UserEditCountUpdate( $this, 1 ),
5011 DeferredUpdates
::POSTSEND
5016 * This method should not be called outside User/UserEditCountUpdate
5020 public function setEditCountInternal( $count ) {
5021 $this->mEditCount
= $count;
5025 * Initialize user_editcount from data out of the revision table
5027 * @internal This method should not be called outside User/UserEditCountUpdate
5028 * @param IDatabase $dbr Replica database
5029 * @return int Number of edits
5031 public function initEditCountInternal( IDatabase
$dbr ) {
5032 // Pull from a replica DB to be less cruel to servers
5033 // Accuracy isn't the point anyway here
5034 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5035 $count = (int)$dbr->selectField(
5036 [ 'revision' ] +
$actorWhere['tables'],
5038 [ $actorWhere['conds'] ],
5041 $actorWhere['joins']
5044 $dbw = wfGetDB( DB_MASTER
);
5047 [ 'user_editcount' => $count ],
5049 'user_id' => $this->getId(),
5050 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5059 * Get the description of a given right
5062 * @param string $right Right to query
5063 * @return string Localized description of the right
5065 public static function getRightDescription( $right ) {
5066 $key = "right-$right";
5067 $msg = wfMessage( $key );
5068 return $msg->isDisabled() ?
$right : $msg->text();
5072 * Get the name of a given grant
5075 * @param string $grant Grant to query
5076 * @return string Localized name of the grant
5078 public static function getGrantName( $grant ) {
5079 $key = "grant-$grant";
5080 $msg = wfMessage( $key );
5081 return $msg->isDisabled() ?
$grant : $msg->text();
5085 * Add a newuser log entry for this user.
5086 * Before 1.19 the return value was always true.
5088 * @deprecated since 1.27, AuthManager handles logging
5089 * @param string|bool $action Account creation type.
5090 * - String, one of the following values:
5091 * - 'create' for an anonymous user creating an account for himself.
5092 * This will force the action's performer to be the created user itself,
5093 * no matter the value of $wgUser
5094 * - 'create2' for a logged in user creating an account for someone else
5095 * - 'byemail' when the created user will receive its password by e-mail
5096 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5097 * - Boolean means whether the account was created by e-mail (deprecated):
5098 * - true will be converted to 'byemail'
5099 * - false will be converted to 'create' if this object is the same as
5100 * $wgUser and to 'create2' otherwise
5101 * @param string $reason User supplied reason
5104 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5105 return true; // disabled
5109 * Add an autocreate newuser log entry for this user
5110 * Used by things like CentralAuth and perhaps other authplugins.
5111 * Consider calling addNewUserLogEntry() directly instead.
5113 * @deprecated since 1.27, AuthManager handles logging
5116 public function addNewUserLogEntryAutoCreate() {
5117 $this->addNewUserLogEntry( 'autocreate' );
5123 * Load the user options either from cache, the database or an array
5125 * @param array|null $data Rows for the current user out of the user_properties table
5127 protected function loadOptions( $data = null ) {
5130 if ( $this->mOptionsLoaded
) {
5134 $this->mOptions
= self
::getDefaultOptions();
5136 if ( !$this->getId() ) {
5137 // For unlogged-in users, load language/variant options from request.
5138 // There's no need to do it for logged-in users: they can set preferences,
5139 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5140 // so don't override user's choice (especially when the user chooses site default).
5141 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5142 $this->mOptions
['variant'] = $variant;
5143 $this->mOptions
['language'] = $variant;
5144 $this->mOptionsLoaded
= true;
5148 // Maybe load from the object
5149 if ( !is_null( $this->mOptionOverrides
) ) {
5150 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5151 foreach ( $this->mOptionOverrides
as $key => $value ) {
5152 $this->mOptions
[$key] = $value;
5155 if ( !is_array( $data ) ) {
5156 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5157 // Load from database
5158 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5159 ?
wfGetDB( DB_MASTER
)
5160 : wfGetDB( DB_REPLICA
);
5162 $res = $dbr->select(
5164 [ 'up_property', 'up_value' ],
5165 [ 'up_user' => $this->getId() ],
5169 $this->mOptionOverrides
= [];
5171 foreach ( $res as $row ) {
5172 // Convert '0' to 0. PHP's boolean conversion considers them both
5173 // false, but e.g. JavaScript considers the former as true.
5174 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5175 // and convert all values here.
5176 if ( $row->up_value
=== '0' ) {
5179 $data[$row->up_property
] = $row->up_value
;
5183 foreach ( $data as $property => $value ) {
5184 $this->mOptionOverrides
[$property] = $value;
5185 $this->mOptions
[$property] = $value;
5189 // Replace deprecated language codes
5190 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5191 $this->mOptions
['language']
5194 $this->mOptionsLoaded
= true;
5196 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5200 * Saves the non-default options for this user, as previously set e.g. via
5201 * setOption(), in the database's "user_properties" (preferences) table.
5202 * Usually used via saveSettings().
5204 protected function saveOptions() {
5205 $this->loadOptions();
5207 // Not using getOptions(), to keep hidden preferences in database
5208 $saveOptions = $this->mOptions
;
5210 // Allow hooks to abort, for instance to save to a global profile.
5211 // Reset options to default state before saving.
5212 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5216 $userId = $this->getId();
5218 $insert_rows = []; // all the new preference rows
5219 foreach ( $saveOptions as $key => $value ) {
5220 // Don't bother storing default values
5221 $defaultOption = self
::getDefaultOption( $key );
5222 if ( ( $defaultOption === null && $value !== false && $value !== null )
5223 ||
$value != $defaultOption
5226 'up_user' => $userId,
5227 'up_property' => $key,
5228 'up_value' => $value,
5233 $dbw = wfGetDB( DB_MASTER
);
5235 $res = $dbw->select( 'user_properties',
5236 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5238 // Find prior rows that need to be removed or updated. These rows will
5239 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5241 foreach ( $res as $row ) {
5242 if ( !isset( $saveOptions[$row->up_property
] )
5243 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5245 $keysDelete[] = $row->up_property
;
5249 if ( count( $keysDelete ) ) {
5250 // Do the DELETE by PRIMARY KEY for prior rows.
5251 // In the past a very large portion of calls to this function are for setting
5252 // 'rememberpassword' for new accounts (a preference that has since been removed).
5253 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5254 // caused gap locks on [max user ID,+infinity) which caused high contention since
5255 // updates would pile up on each other as they are for higher (newer) user IDs.
5256 // It might not be necessary these days, but it shouldn't hurt either.
5257 $dbw->delete( 'user_properties',
5258 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5260 // Insert the new preference rows
5261 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5265 * Return the list of user fields that should be selected to create
5266 * a new user object.
5267 * @deprecated since 1.31, use self::getQueryInfo() instead.
5270 public static function selectFields() {
5271 wfDeprecated( __METHOD__
, '1.31' );
5279 'user_email_authenticated',
5281 'user_email_token_expires',
5282 'user_registration',
5288 * Return the tables, fields, and join conditions to be selected to create
5289 * a new user object.
5291 * @return array With three keys:
5292 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5293 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5294 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5296 public static function getQueryInfo() {
5297 global $wgActorTableSchemaMigrationStage;
5300 'tables' => [ 'user' ],
5308 'user_email_authenticated',
5310 'user_email_token_expires',
5311 'user_registration',
5317 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5318 // but it does little harm and might be needed for write callers loading a User.
5319 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5320 $ret['tables']['user_actor'] = 'actor';
5321 $ret['fields'][] = 'user_actor.actor_id';
5322 $ret['joins']['user_actor'] = [
5323 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5324 [ 'user_actor.actor_user = user_id' ]
5332 * Factory function for fatal permission-denied errors
5335 * @param string $permission User right required
5338 static function newFatalPermissionDeniedStatus( $permission ) {
5342 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5343 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5347 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5350 return Status
::newFatal( 'badaccess-group0' );
5354 * Get a new instance of this user that was loaded from the master via a locking read
5356 * Use this instead of the main context User when updating that user. This avoids races
5357 * where that user was loaded from a replica DB or even the master but without proper locks.
5359 * @return User|null Returns null if the user was not found in the DB
5362 public function getInstanceForUpdate() {
5363 if ( !$this->getId() ) {
5364 return null; // anon
5367 $user = self
::newFromId( $this->getId() );
5368 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5376 * Checks if two user objects point to the same user.
5378 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5379 * @param UserIdentity $user
5382 public function equals( UserIdentity
$user ) {
5383 // XXX it's not clear whether central ID providers are supposed to obey this
5384 return $this->getName() === $user->getName();
5388 * Checks if usertalk is allowed
5392 public function isAllowUsertalk() {
5393 return $this->mAllowUsertalk
;