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\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\AuthenticationResponse
;
28 use MediaWiki\Auth\AuthenticationRequest
;
29 use MediaWiki\User\UserIdentity
;
30 use MediaWiki\Logger\LoggerFactory
;
31 use Wikimedia\Assert\Assert
;
33 use Wikimedia\ScopedCallback
;
34 use Wikimedia\Rdbms\Database
;
35 use Wikimedia\Rdbms\DBExpectedError
;
36 use Wikimedia\Rdbms\IDatabase
;
39 * The User object encapsulates all of the user-specific settings (user_id,
40 * name, rights, email address, options, last login time). Client
41 * classes use the getXXX() functions to access these fields. These functions
42 * do all the work of determining whether the user is logged in,
43 * whether the requested option can be satisfied from cookies or
44 * whether a database query is needed. Most of the settings needed
45 * for rendering normal pages are set in the cookie to minimize use
48 class User
implements IDBAccessObject
, UserIdentity
{
51 * Number of characters required for the user_token field.
53 const TOKEN_LENGTH
= 32;
56 * An invalid string value for the user_token field.
58 const INVALID_TOKEN
= '*** INVALID ***';
61 * Version number to tag cached versions of serialized User objects. Should be increased when
62 * {@link $mCacheVars} or one of it's members changes.
67 * Exclude user options that are set to their default value.
70 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
75 const CHECK_USER_RIGHTS
= true;
80 const IGNORE_USER_RIGHTS
= false;
83 * Array of Strings List of member variables which are saved to the
84 * shared cache (memcached). Any operation which changes the
85 * corresponding database fields must call a cache-clearing function.
88 protected static $mCacheVars = [
96 'mEmailAuthenticated',
103 // user_properties table
110 * Array of Strings Core rights.
111 * Each of these should have a corresponding message of the form
115 protected static $mCoreRights = [
163 'move-categorypages',
164 'move-rootuserpages',
168 'override-export-depth',
190 'userrights-interwiki',
198 * String Cached results of getAllRights()
200 protected static $mAllRights = false;
202 /** Cache variables */
215 /** @var string TS_MW timestamp from the DB */
217 /** @var string TS_MW timestamp from cache */
218 protected $mQuickTouched;
222 public $mEmailAuthenticated;
224 protected $mEmailToken;
226 protected $mEmailTokenExpires;
228 protected $mRegistration;
230 protected $mEditCount;
231 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
232 protected $mGroupMemberships;
234 protected $mOptionOverrides;
238 * Bool Whether the cache variables have been loaded.
241 public $mOptionsLoaded;
244 * Array with already loaded items or true if all items have been loaded.
246 protected $mLoadedItems = [];
250 * String Initialization data source if mLoadedItems!==true. May be one of:
251 * - 'defaults' anonymous user initialised from class defaults
252 * - 'name' initialise from mName
253 * - 'id' initialise from mId
254 * - 'actor' initialise from mActorId
255 * - 'session' log in from session if possible
257 * Use the User::newFrom*() family of functions to set this.
262 * Lazy-initialized variables, invalidated with clearInstanceCache
266 protected $mDatePreference;
274 protected $mBlockreason;
276 protected $mEffectiveGroups;
278 protected $mImplicitGroups;
280 protected $mFormerGroups;
282 protected $mGlobalBlock;
290 /** @var WebRequest */
297 protected $mAllowUsertalk;
300 private $mBlockedFromCreateAccount = false;
302 /** @var int User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self
::READ_NORMAL
;
305 public static $idCacheByName = [];
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
313 * @see newFromActorId()
314 * @see newFromConfirmationCode()
315 * @see newFromSession()
318 public function __construct() {
319 $this->clearInstanceCache( 'defaults' );
325 public function __toString() {
326 return (string)$this->getName();
330 * Test if it's safe to load this User object.
332 * You should typically check this before using $wgUser or
333 * RequestContext::getUser in a method that might be called before the
334 * system has been fully initialized. If the object is unsafe, you should
335 * use an anonymous user:
337 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
343 public function isSafeToLoad() {
344 global $wgFullyInitialised;
346 // The user is safe to load if:
347 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
348 // * mLoadedItems === true (already loaded)
349 // * mFrom !== 'session' (sessions not involved at all)
351 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
352 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
356 * Load the user table data for this object from the source given by mFrom.
358 * @param int $flags User::READ_* constant bitfield
360 public function load( $flags = self
::READ_NORMAL
) {
361 global $wgFullyInitialised;
363 if ( $this->mLoadedItems
=== true ) {
367 // Set it now to avoid infinite recursion in accessors
368 $oldLoadedItems = $this->mLoadedItems
;
369 $this->mLoadedItems
= true;
370 $this->queryFlagsUsed
= $flags;
372 // If this is called too early, things are likely to break.
373 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
374 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
375 ->warning( 'User::loadFromSession called before the end of Setup.php', [
376 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
378 $this->loadDefaults();
379 $this->mLoadedItems
= $oldLoadedItems;
383 switch ( $this->mFrom
) {
385 $this->loadDefaults();
388 // Make sure this thread sees its own changes
389 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
390 if ( $lb->hasOrMadeRecentMasterChanges() ) {
391 $flags |
= self
::READ_LATEST
;
392 $this->queryFlagsUsed
= $flags;
395 $this->mId
= self
::idFromName( $this->mName
, $flags );
397 // Nonexistent user placeholder object
398 $this->loadDefaults( $this->mName
);
400 $this->loadFromId( $flags );
404 // Make sure this thread sees its own changes, if the ID isn't 0
405 if ( $this->mId
!= 0 ) {
406 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
407 if ( $lb->hasOrMadeRecentMasterChanges() ) {
408 $flags |
= self
::READ_LATEST
;
409 $this->queryFlagsUsed
= $flags;
413 $this->loadFromId( $flags );
416 // Make sure this thread sees its own changes
417 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
418 if ( $lb->hasOrMadeRecentMasterChanges() ) {
419 $flags |
= self
::READ_LATEST
;
420 $this->queryFlagsUsed
= $flags;
423 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
424 $row = wfGetDB( $index )->selectRow(
426 [ 'actor_user', 'actor_name' ],
427 [ 'actor_id' => $this->mActorId
],
434 $this->loadDefaults();
435 } elseif ( $row->actor_user
) {
436 $this->mId
= $row->actor_user
;
437 $this->loadFromId( $flags );
439 $this->loadDefaults( $row->actor_name
);
443 if ( !$this->loadFromSession() ) {
444 // Loading from session failed. Load defaults.
445 $this->loadDefaults();
447 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
450 throw new UnexpectedValueException(
451 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
456 * Load user table data, given mId has already been set.
457 * @param int $flags User::READ_* constant bitfield
458 * @return bool False if the ID does not exist, true otherwise
460 public function loadFromId( $flags = self
::READ_NORMAL
) {
461 if ( $this->mId
== 0 ) {
462 // Anonymous users are not in the database (don't need cache)
463 $this->loadDefaults();
467 // Try cache (unless this needs data from the master DB).
468 // NOTE: if this thread called saveSettings(), the cache was cleared.
469 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
471 if ( !$this->loadFromDatabase( $flags ) ) {
472 // Can't load from ID
476 $this->loadFromCache();
479 $this->mLoadedItems
= true;
480 $this->queryFlagsUsed
= $flags;
487 * @param string $wikiId
490 public static function purge( $wikiId, $userId ) {
491 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
492 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
493 $cache->delete( $key );
498 * @param WANObjectCache $cache
501 protected function getCacheKey( WANObjectCache
$cache ) {
502 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
504 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
508 * @param WANObjectCache $cache
512 public function getMutableCacheKeys( WANObjectCache
$cache ) {
513 $id = $this->getId();
515 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
519 * Load user data from shared cache, given mId has already been set.
524 protected function loadFromCache() {
525 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
526 $data = $cache->getWithSetCallback(
527 $this->getCacheKey( $cache ),
529 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
530 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
531 wfDebug( "User: cache miss for user {$this->mId}\n" );
533 $this->loadFromDatabase( self
::READ_NORMAL
);
535 $this->loadOptions();
538 foreach ( self
::$mCacheVars as $name ) {
539 $data[$name] = $this->$name;
542 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
544 // if a user group membership is about to expire, the cache needs to
545 // expire at that time (T163691)
546 foreach ( $this->mGroupMemberships
as $ugm ) {
547 if ( $ugm->getExpiry() ) {
548 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
549 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
550 $ttl = $secondsUntilExpiry;
557 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
560 // Restore from cache
561 foreach ( self
::$mCacheVars as $name ) {
562 $this->$name = $data[$name];
568 /** @name newFrom*() static factory methods */
572 * Static factory method for creation from username.
574 * This is slightly less efficient than newFromId(), so use newFromId() if
575 * you have both an ID and a name handy.
577 * @param string $name Username, validated by Title::newFromText()
578 * @param string|bool $validate Validate username. Takes the same parameters as
579 * User::getCanonicalName(), except that true is accepted as an alias
580 * for 'valid', for BC.
582 * @return User|bool User object, or false if the username is invalid
583 * (e.g. if it contains illegal characters or is an IP address). If the
584 * username is not present in the database, the result will be a user object
585 * with a name, zero user ID and default settings.
587 public static function newFromName( $name, $validate = 'valid' ) {
588 if ( $validate === true ) {
591 $name = self
::getCanonicalName( $name, $validate );
592 if ( $name === false ) {
596 // Create unloaded user object
600 $u->setItemLoaded( 'name' );
606 * Static factory method for creation from a given user ID.
608 * @param int $id Valid user ID
609 * @return User The corresponding User object
611 public static function newFromId( $id ) {
615 $u->setItemLoaded( 'id' );
620 * Static factory method for creation from a given actor ID.
623 * @param int $id Valid actor ID
624 * @return User The corresponding User object
626 public static function newFromActorId( $id ) {
627 global $wgActorTableSchemaMigrationStage;
629 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
630 // but it does little harm and might be needed for write callers loading a User.
631 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
632 throw new BadMethodCallException(
633 'Cannot use ' . __METHOD__
634 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
641 $u->setItemLoaded( 'actor' );
646 * Returns a User object corresponding to the given UserIdentity.
650 * @param UserIdentity $identity
654 public static function newFromIdentity( UserIdentity
$identity ) {
655 if ( $identity instanceof User
) {
659 return self
::newFromAnyId(
660 $identity->getId() === 0 ?
null : $identity->getId(),
661 $identity->getName() === '' ?
null : $identity->getName(),
662 $identity->getActorId() === 0 ?
null : $identity->getActorId()
667 * Static factory method for creation from an ID, name, and/or actor ID
669 * This does not check that the ID, name, and actor ID all correspond to
673 * @param int|null $userId User ID, if known
674 * @param string|null $userName User name, if known
675 * @param int|null $actorId Actor ID, if known
676 * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none
679 public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) {
680 global $wgActorTableSchemaMigrationStage;
682 // Stop-gap solution for the problem described in T222212.
683 // Force the User ID and Actor ID to zero for users loaded from the database
684 // of another wiki, to prevent subtle data corruption and confusing failure modes.
685 if ( $wikiId !== false ) {
691 $user->mFrom
= 'defaults';
693 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
694 // but it does little harm and might be needed for write callers loading a User.
695 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
696 $user->mActorId
= (int)$actorId;
697 if ( $user->mActorId
!== 0 ) {
698 $user->mFrom
= 'actor';
700 $user->setItemLoaded( 'actor' );
703 if ( $userName !== null && $userName !== '' ) {
704 $user->mName
= $userName;
705 $user->mFrom
= 'name';
706 $user->setItemLoaded( 'name' );
709 if ( $userId !== null ) {
710 $user->mId
= (int)$userId;
711 if ( $user->mId
!== 0 ) {
714 $user->setItemLoaded( 'id' );
717 if ( $user->mFrom
=== 'defaults' ) {
718 throw new InvalidArgumentException(
719 'Cannot create a user with no name, no ID, and no actor ID'
727 * Factory method to fetch whichever user has a given email confirmation code.
728 * This code is generated when an account is created or its e-mail address
731 * If the code is invalid or has expired, returns NULL.
733 * @param string $code Confirmation code
734 * @param int $flags User::READ_* bitfield
737 public static function newFromConfirmationCode( $code, $flags = 0 ) {
738 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
739 ?
wfGetDB( DB_MASTER
)
740 : wfGetDB( DB_REPLICA
);
742 $id = $db->selectField(
746 'user_email_token' => md5( $code ),
747 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
751 return $id ? self
::newFromId( $id ) : null;
755 * Create a new user object using data from session. If the login
756 * credentials are invalid, the result is an anonymous user.
758 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
761 public static function newFromSession( WebRequest
$request = null ) {
763 $user->mFrom
= 'session';
764 $user->mRequest
= $request;
769 * Create a new user object from a user row.
770 * The row should have the following fields from the user table in it:
771 * - either user_name or user_id to load further data if needed (or both)
773 * - all other fields (email, etc.)
774 * It is useless to provide the remaining fields if either user_id,
775 * user_name and user_real_name are not provided because the whole row
776 * will be loaded once more from the database when accessing them.
778 * @param stdClass $row A row from the user table
779 * @param array|null $data Further data to load into the object
780 * (see User::loadFromRow for valid keys)
783 public static function newFromRow( $row, $data = null ) {
785 $user->loadFromRow( $row, $data );
790 * Static factory method for creation of a "system" user from username.
792 * A "system" user is an account that's used to attribute logged actions
793 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
794 * might include the 'Maintenance script' or 'Conversion script' accounts
795 * used by various scripts in the maintenance/ directory or accounts such
796 * as 'MediaWiki message delivery' used by the MassMessage extension.
798 * This can optionally create the user if it doesn't exist, and "steal" the
799 * account if it does exist.
801 * "Stealing" an existing user is intended to make it impossible for normal
802 * authentication processes to use the account, effectively disabling the
803 * account for normal use:
804 * - Email is invalidated, to prevent account recovery by emailing a
805 * temporary password and to disassociate the account from the existing
807 * - The token is set to a magic invalid value, to kill existing sessions
808 * and to prevent $this->setToken() calls from resetting the token to a
810 * - SessionManager is instructed to prevent new sessions for the user, to
811 * do things like deauthorizing OAuth consumers.
812 * - AuthManager is instructed to revoke access, to invalidate or remove
813 * passwords and other credentials.
815 * @param string $name Username
816 * @param array $options Options are:
817 * - validate: As for User::getCanonicalName(), default 'valid'
818 * - create: Whether to create the user if it doesn't already exist, default true
819 * - steal: Whether to "disable" the account for normal use if it already
820 * exists, default false
824 public static function newSystemUser( $name, $options = [] ) {
826 'validate' => 'valid',
831 $name = self
::getCanonicalName( $name, $options['validate'] );
832 if ( $name === false ) {
836 $dbr = wfGetDB( DB_REPLICA
);
837 $userQuery = self
::getQueryInfo();
838 $row = $dbr->selectRow(
839 $userQuery['tables'],
840 $userQuery['fields'],
841 [ 'user_name' => $name ],
847 // Try the master database...
848 $dbw = wfGetDB( DB_MASTER
);
849 $row = $dbw->selectRow(
850 $userQuery['tables'],
851 $userQuery['fields'],
852 [ 'user_name' => $name ],
860 // No user. Create it?
861 return $options['create']
862 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
866 $user = self
::newFromRow( $row );
868 // A user is considered to exist as a non-system user if it can
869 // authenticate, or has an email set, or has a non-invalid token.
870 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
871 AuthManager
::singleton()->userCanAuthenticate( $name )
873 // User exists. Steal it?
874 if ( !$options['steal'] ) {
878 AuthManager
::singleton()->revokeAccessForUser( $name );
880 $user->invalidateEmail();
881 $user->mToken
= self
::INVALID_TOKEN
;
882 $user->saveSettings();
883 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
892 * Get the username corresponding to a given user ID
893 * @param int $id User ID
894 * @return string|bool The corresponding username
896 public static function whoIs( $id ) {
897 return UserCache
::singleton()->getProp( $id, 'name' );
901 * Get the real name of a user given their user ID
903 * @param int $id User ID
904 * @return string|bool The corresponding user's real name
906 public static function whoIsReal( $id ) {
907 return UserCache
::singleton()->getProp( $id, 'real_name' );
911 * Get database id given a user name
912 * @param string $name Username
913 * @param int $flags User::READ_* constant bitfield
914 * @return int|null The corresponding user's ID, or null if user is nonexistent
916 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
917 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
918 $name = (string)$name;
919 $nt = Title
::makeTitleSafe( NS_USER
, $name );
920 if ( is_null( $nt ) ) {
925 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
926 return self
::$idCacheByName[$name];
929 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
930 $db = wfGetDB( $index );
935 [ 'user_name' => $nt->getText() ],
940 if ( $s === false ) {
943 $result = (int)$s->user_id
;
946 self
::$idCacheByName[$name] = $result;
948 if ( count( self
::$idCacheByName ) > 1000 ) {
949 self
::$idCacheByName = [];
956 * Reset the cache used in idFromName(). For use in tests.
958 public static function resetIdByNameCache() {
959 self
::$idCacheByName = [];
963 * Does the string match an anonymous IP address?
965 * This function exists for username validation, in order to reject
966 * usernames which are similar in form to IP addresses. Strings such
967 * as 300.300.300.300 will return true because it looks like an IP
968 * address, despite not being strictly valid.
970 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
971 * address because the usemod software would "cloak" anonymous IP
972 * addresses like this, if we allowed accounts like this to be created
973 * new users could get the old edits of these anonymous users.
975 * @param string $name Name to match
978 public static function isIP( $name ) {
979 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
980 || IP
::isIPv6( $name );
984 * Is the user an IP range?
989 public function isIPRange() {
990 return IP
::isValidRange( $this->mName
);
994 * Is the input a valid username?
996 * Checks if the input is a valid username, we don't want an empty string,
997 * an IP address, anything that contains slashes (would mess up subpages),
998 * is longer than the maximum allowed username size or doesn't begin with
1001 * @param string $name Name to match
1004 public static function isValidUserName( $name ) {
1005 global $wgMaxNameChars;
1008 || self
::isIP( $name )
1009 ||
strpos( $name, '/' ) !== false
1010 ||
strlen( $name ) > $wgMaxNameChars
1011 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
1016 // Ensure that the name can't be misresolved as a different title,
1017 // such as with extra namespace keys at the start.
1018 $parsed = Title
::newFromText( $name );
1019 if ( is_null( $parsed )
1020 ||
$parsed->getNamespace()
1021 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1025 // Check an additional blacklist of troublemaker characters.
1026 // Should these be merged into the title char list?
1027 $unicodeBlacklist = '/[' .
1028 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1029 '\x{00a0}' . # non-breaking space
1030 '\x{2000}-\x{200f}' . # various whitespace
1031 '\x{2028}-\x{202f}' . # breaks and control chars
1032 '\x{3000}' . # ideographic space
1033 '\x{e000}-\x{f8ff}' . # private use
1035 if ( preg_match( $unicodeBlacklist, $name ) ) {
1043 * Usernames which fail to pass this function will be blocked
1044 * from user login and new account registrations, but may be used
1045 * internally by batch processes.
1047 * If an account already exists in this form, login will be blocked
1048 * by a failure to pass this function.
1050 * @param string $name Name to match
1053 public static function isUsableName( $name ) {
1054 global $wgReservedUsernames;
1055 // Must be a valid username, obviously ;)
1056 if ( !self
::isValidUserName( $name ) ) {
1060 static $reservedUsernames = false;
1061 if ( !$reservedUsernames ) {
1062 $reservedUsernames = $wgReservedUsernames;
1063 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1066 // Certain names may be reserved for batch processes.
1067 foreach ( $reservedUsernames as $reserved ) {
1068 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1069 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1071 if ( $reserved == $name ) {
1079 * Return the users who are members of the given group(s). In case of multiple groups,
1080 * users who are members of at least one of them are returned.
1082 * @param string|array $groups A single group name or an array of group names
1083 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1084 * records; larger values are ignored.
1085 * @param int|null $after ID the user to start after
1086 * @return UserArrayFromResult
1088 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1089 if ( $groups === [] ) {
1090 return UserArrayFromResult
::newFromIDs( [] );
1093 $groups = array_unique( (array)$groups );
1094 $limit = min( 5000, $limit );
1096 $conds = [ 'ug_group' => $groups ];
1097 if ( $after !== null ) {
1098 $conds[] = 'ug_user > ' . (int)$after;
1101 $dbr = wfGetDB( DB_REPLICA
);
1102 $ids = $dbr->selectFieldValues(
1109 'ORDER BY' => 'ug_user',
1113 return UserArray
::newFromIDs( $ids );
1117 * Usernames which fail to pass this function will be blocked
1118 * from new account registrations, but may be used internally
1119 * either by batch processes or by user accounts which have
1120 * already been created.
1122 * Additional blacklisting may be added here rather than in
1123 * isValidUserName() to avoid disrupting existing accounts.
1125 * @param string $name String to match
1128 public static function isCreatableName( $name ) {
1129 global $wgInvalidUsernameCharacters;
1131 // Ensure that the username isn't longer than 235 bytes, so that
1132 // (at least for the builtin skins) user javascript and css files
1133 // will work. (T25080)
1134 if ( strlen( $name ) > 235 ) {
1135 wfDebugLog( 'username', __METHOD__
.
1136 ": '$name' invalid due to length" );
1140 // Preg yells if you try to give it an empty string
1141 if ( $wgInvalidUsernameCharacters !== '' &&
1142 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1144 wfDebugLog( 'username', __METHOD__
.
1145 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1149 return self
::isUsableName( $name );
1153 * Is the input a valid password for this user?
1155 * @param string $password Desired password
1158 public function isValidPassword( $password ) {
1159 // simple boolean wrapper for checkPasswordValidity
1160 return $this->checkPasswordValidity( $password )->isGood();
1164 * Given unvalidated password input, return error message on failure.
1166 * @param string $password Desired password
1167 * @return bool|string|array True on success, string or array of error message on failure
1168 * @deprecated since 1.33, use checkPasswordValidity
1170 public function getPasswordValidity( $password ) {
1171 wfDeprecated( __METHOD__
, '1.33' );
1173 $result = $this->checkPasswordValidity( $password );
1174 if ( $result->isGood() ) {
1179 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1180 $messages[] = $error['message'];
1182 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1183 $messages[] = $warning['message'];
1185 if ( count( $messages ) === 1 ) {
1186 return $messages[0];
1193 * Check if this is a valid password for this user
1195 * Returns a Status object with a set of messages describing
1196 * problems with the password. If the return status is fatal,
1197 * the action should be refused and the password should not be
1198 * checked at all (this is mainly meant for DoS mitigation).
1199 * If the return value is OK but not good, the password can be checked,
1200 * but the user should not be able to set their password to this.
1201 * The value of the returned Status object will be an array which
1202 * can have the following fields:
1203 * - forceChange (bool): if set to true, the user should not be
1204 * allowed to log with this password unless they change it during
1205 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1206 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1207 * a password change on login.
1209 * @param string $password Desired password
1213 public function checkPasswordValidity( $password ) {
1214 global $wgPasswordPolicy;
1216 $upp = new UserPasswordPolicy(
1217 $wgPasswordPolicy['policies'],
1218 $wgPasswordPolicy['checks']
1221 $status = Status
::newGood( [] );
1222 $result = false; // init $result to false for the internal checks
1224 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1225 $status->error( $result );
1229 if ( $result === false ) {
1230 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1234 if ( $result === true ) {
1238 $status->error( $result );
1239 return $status; // the isValidPassword hook set a string $result and returned true
1243 * Given unvalidated user input, return a canonical username, or false if
1244 * the username is invalid.
1245 * @param string $name User input
1246 * @param string|bool $validate Type of validation to use:
1247 * - false No validation
1248 * - 'valid' Valid for batch processes
1249 * - 'usable' Valid for batch processes and login
1250 * - 'creatable' Valid for batch processes, login and account creation
1252 * @throws InvalidArgumentException
1253 * @return bool|string
1255 public static function getCanonicalName( $name, $validate = 'valid' ) {
1256 // Force usernames to capital
1257 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1259 # Reject names containing '#'; these will be cleaned up
1260 # with title normalisation, but then it's too late to
1262 if ( strpos( $name, '#' ) !== false ) {
1266 // Clean up name according to title rules,
1267 // but only when validation is requested (T14654)
1268 $t = ( $validate !== false ) ?
1269 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1270 // Check for invalid titles
1271 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1275 $name = $t->getText();
1277 switch ( $validate ) {
1281 if ( !self
::isValidUserName( $name ) ) {
1286 if ( !self
::isUsableName( $name ) ) {
1291 if ( !self
::isCreatableName( $name ) ) {
1296 throw new InvalidArgumentException(
1297 'Invalid parameter value for $validate in ' . __METHOD__
);
1303 * Set cached properties to default.
1305 * @note This no longer clears uncached lazy-initialised properties;
1306 * the constructor does that instead.
1308 * @param string|bool $name
1310 public function loadDefaults( $name = false ) {
1312 $this->mName
= $name;
1313 $this->mActorId
= null;
1314 $this->mRealName
= '';
1316 $this->mOptionOverrides
= null;
1317 $this->mOptionsLoaded
= false;
1319 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1320 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1321 if ( $loggedOut !== 0 ) {
1322 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1324 $this->mTouched
= '1'; # Allow any pages to be cached
1327 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1328 $this->mEmailAuthenticated
= null;
1329 $this->mEmailToken
= '';
1330 $this->mEmailTokenExpires
= null;
1331 $this->mRegistration
= wfTimestamp( TS_MW
);
1332 $this->mGroupMemberships
= [];
1334 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1338 * Return whether an item has been loaded.
1340 * @param string $item Item to check. Current possibilities:
1344 * @param string $all 'all' to check if the whole object has been loaded
1345 * or any other string to check if only the item is available (e.g.
1349 public function isItemLoaded( $item, $all = 'all' ) {
1350 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1351 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1355 * Set that an item has been loaded
1357 * @param string $item
1359 protected function setItemLoaded( $item ) {
1360 if ( is_array( $this->mLoadedItems
) ) {
1361 $this->mLoadedItems
[$item] = true;
1366 * Load user data from the session.
1368 * @return bool True if the user is logged in, false otherwise.
1370 private function loadFromSession() {
1373 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1374 if ( $result !== null ) {
1378 // MediaWiki\Session\Session already did the necessary authentication of the user
1379 // returned here, so just use it if applicable.
1380 $session = $this->getRequest()->getSession();
1381 $user = $session->getUser();
1382 if ( $user->isLoggedIn() ) {
1383 $this->loadFromUserObject( $user );
1384 if ( $user->getBlock() ) {
1385 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1386 // every session load, because an autoblocked editor might not edit again from the same
1387 // IP address after being blocked.
1388 $this->trackBlockWithCookie();
1391 // Other code expects these to be set in the session, so set them.
1392 $session->set( 'wsUserID', $this->getId() );
1393 $session->set( 'wsUserName', $this->getName() );
1394 $session->set( 'wsToken', $this->getToken() );
1403 * Set the 'BlockID' cookie depending on block type and user authentication status.
1405 public function trackBlockWithCookie() {
1406 $block = $this->getBlock();
1408 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null
1409 && $block->shouldTrackWithCookie( $this->isAnon() )
1411 $block->setCookie( $this->getRequest()->response() );
1416 * Load user and user_group data from the database.
1417 * $this->mId must be set, this is how the user is identified.
1419 * @param int $flags User::READ_* constant bitfield
1420 * @return bool True if the user exists, false if the user is anonymous
1422 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1424 $this->mId
= intval( $this->mId
);
1426 if ( !$this->mId
) {
1427 // Anonymous users are not in the database
1428 $this->loadDefaults();
1432 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1433 $db = wfGetDB( $index );
1435 $userQuery = self
::getQueryInfo();
1436 $s = $db->selectRow(
1437 $userQuery['tables'],
1438 $userQuery['fields'],
1439 [ 'user_id' => $this->mId
],
1445 $this->queryFlagsUsed
= $flags;
1446 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1448 if ( $s !== false ) {
1449 // Initialise user table data
1450 $this->loadFromRow( $s );
1451 $this->mGroupMemberships
= null; // deferred
1452 $this->getEditCount(); // revalidation for nulls
1458 $this->loadDefaults();
1464 * Initialize this object from a row from the user table.
1466 * @param stdClass $row Row from the user table to load.
1467 * @param array|null $data Further user data to load into the object
1469 * user_groups Array of arrays or stdClass result rows out of the user_groups
1470 * table. Previously you were supposed to pass an array of strings
1471 * here, but we also need expiry info nowadays, so an array of
1472 * strings is ignored.
1473 * user_properties Array with properties out of the user_properties table
1475 protected function loadFromRow( $row, $data = null ) {
1476 global $wgActorTableSchemaMigrationStage;
1478 if ( !is_object( $row ) ) {
1479 throw new InvalidArgumentException( '$row must be an object' );
1484 $this->mGroupMemberships
= null; // deferred
1486 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1487 // but it does little harm and might be needed for write callers loading a User.
1488 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1489 if ( isset( $row->actor_id
) ) {
1490 $this->mActorId
= (int)$row->actor_id
;
1491 if ( $this->mActorId
!== 0 ) {
1492 $this->mFrom
= 'actor';
1494 $this->setItemLoaded( 'actor' );
1500 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1501 $this->mName
= $row->user_name
;
1502 $this->mFrom
= 'name';
1503 $this->setItemLoaded( 'name' );
1508 if ( isset( $row->user_real_name
) ) {
1509 $this->mRealName
= $row->user_real_name
;
1510 $this->setItemLoaded( 'realname' );
1515 if ( isset( $row->user_id
) ) {
1516 $this->mId
= intval( $row->user_id
);
1517 if ( $this->mId
!== 0 ) {
1518 $this->mFrom
= 'id';
1520 $this->setItemLoaded( 'id' );
1525 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1526 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1529 if ( isset( $row->user_editcount
) ) {
1530 $this->mEditCount
= $row->user_editcount
;
1535 if ( isset( $row->user_touched
) ) {
1536 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1541 if ( isset( $row->user_token
) ) {
1542 // The definition for the column is binary(32), so trim the NULs
1543 // that appends. The previous definition was char(32), so trim
1545 $this->mToken
= rtrim( $row->user_token
, " \0" );
1546 if ( $this->mToken
=== '' ) {
1547 $this->mToken
= null;
1553 if ( isset( $row->user_email
) ) {
1554 $this->mEmail
= $row->user_email
;
1555 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1556 $this->mEmailToken
= $row->user_email_token
;
1557 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1558 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1564 $this->mLoadedItems
= true;
1567 if ( is_array( $data ) ) {
1568 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1569 if ( $data['user_groups'] === [] ) {
1570 $this->mGroupMemberships
= [];
1572 $firstGroup = reset( $data['user_groups'] );
1573 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1574 $this->mGroupMemberships
= [];
1575 foreach ( $data['user_groups'] as $row ) {
1576 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1577 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1582 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1583 $this->loadOptions( $data['user_properties'] );
1589 * Load the data for this user object from another user object.
1593 protected function loadFromUserObject( $user ) {
1595 foreach ( self
::$mCacheVars as $var ) {
1596 $this->$var = $user->$var;
1601 * Load the groups from the database if they aren't already loaded.
1603 private function loadGroups() {
1604 if ( is_null( $this->mGroupMemberships
) ) {
1605 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1606 ?
wfGetDB( DB_MASTER
)
1607 : wfGetDB( DB_REPLICA
);
1608 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1614 * Add the user to the group if he/she meets given criteria.
1616 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1617 * possible to remove manually via Special:UserRights. In such case it
1618 * will not be re-added automatically. The user will also not lose the
1619 * group if they no longer meet the criteria.
1621 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1623 * @return array Array of groups the user has been promoted to.
1625 * @see $wgAutopromoteOnce
1627 public function addAutopromoteOnceGroups( $event ) {
1628 global $wgAutopromoteOnceLogInRC;
1630 if ( wfReadOnly() ||
!$this->getId() ) {
1634 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1635 if ( $toPromote === [] ) {
1639 if ( !$this->checkAndSetTouched() ) {
1640 return []; // raced out (bug T48834)
1643 $oldGroups = $this->getGroups(); // previous groups
1644 $oldUGMs = $this->getGroupMemberships();
1645 foreach ( $toPromote as $group ) {
1646 $this->addGroup( $group );
1648 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1649 $newUGMs = $this->getGroupMemberships();
1651 // update groups in external authentication database
1652 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1654 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1655 $logEntry->setPerformer( $this );
1656 $logEntry->setTarget( $this->getUserPage() );
1657 $logEntry->setParameters( [
1658 '4::oldgroups' => $oldGroups,
1659 '5::newgroups' => $newGroups,
1661 $logid = $logEntry->insert();
1662 if ( $wgAutopromoteOnceLogInRC ) {
1663 $logEntry->publish( $logid );
1670 * Builds update conditions. Additional conditions may be added to $conditions to
1671 * protected against race conditions using a compare-and-set (CAS) mechanism
1672 * based on comparing $this->mTouched with the user_touched field.
1674 * @param IDatabase $db
1675 * @param array $conditions WHERE conditions for use with Database::update
1676 * @return array WHERE conditions for use with Database::update
1678 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1679 if ( $this->mTouched
) {
1680 // CAS check: only update if the row wasn't changed sicne it was loaded.
1681 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1688 * Bump user_touched if it didn't change since this object was loaded
1690 * On success, the mTouched field is updated.
1691 * The user serialization cache is always cleared.
1693 * @return bool Whether user_touched was actually updated
1696 protected function checkAndSetTouched() {
1699 if ( !$this->mId
) {
1700 return false; // anon
1703 // Get a new user_touched that is higher than the old one
1704 $newTouched = $this->newTouchedTimestamp();
1706 $dbw = wfGetDB( DB_MASTER
);
1707 $dbw->update( 'user',
1708 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1709 $this->makeUpdateConditions( $dbw, [
1710 'user_id' => $this->mId
,
1714 $success = ( $dbw->affectedRows() > 0 );
1717 $this->mTouched
= $newTouched;
1718 $this->clearSharedCache( 'changed' );
1720 // Clears on failure too since that is desired if the cache is stale
1721 $this->clearSharedCache( 'refresh' );
1728 * Clear various cached data stored in this object. The cache of the user table
1729 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1731 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1732 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1734 public function clearInstanceCache( $reloadFrom = false ) {
1735 $this->mNewtalk
= -1;
1736 $this->mDatePreference
= null;
1737 $this->mBlockedby
= -1; # Unset
1738 $this->mHash
= false;
1739 $this->mRights
= null;
1740 $this->mEffectiveGroups
= null;
1741 $this->mImplicitGroups
= null;
1742 $this->mGroupMemberships
= null;
1743 $this->mOptions
= null;
1744 $this->mOptionsLoaded
= false;
1745 $this->mEditCount
= null;
1747 if ( $reloadFrom ) {
1748 $this->mLoadedItems
= [];
1749 $this->mFrom
= $reloadFrom;
1753 /** @var array|null */
1754 private static $defOpt = null;
1755 /** @var string|null */
1756 private static $defOptLang = null;
1759 * Reset the process cache of default user options. This is only necessary
1760 * if the wiki configuration has changed since defaults were calculated,
1761 * and as such should only be performed inside the testing suite that
1762 * regularly changes wiki configuration.
1764 public static function resetGetDefaultOptionsForTestsOnly() {
1765 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1766 self
::$defOpt = null;
1767 self
::$defOptLang = null;
1771 * Combine the language default options with any site-specific options
1772 * and add the default language variants.
1774 * @return array Array of String options
1776 public static function getDefaultOptions() {
1777 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1779 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1780 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1781 // The content language does not change (and should not change) mid-request, but the
1782 // unit tests change it anyway, and expect this method to return values relevant to the
1783 // current content language.
1784 return self
::$defOpt;
1787 self
::$defOpt = $wgDefaultUserOptions;
1788 // Default language setting
1789 self
::$defOptLang = $contLang->getCode();
1790 self
::$defOpt['language'] = self
::$defOptLang;
1791 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1792 if ( $langCode === $contLang->getCode() ) {
1793 self
::$defOpt['variant'] = $langCode;
1795 self
::$defOpt["variant-$langCode"] = $langCode;
1799 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1800 // since extensions may change the set of searchable namespaces depending
1801 // on user groups/permissions.
1802 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1803 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1805 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1807 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1809 return self
::$defOpt;
1813 * Get a given default option value.
1815 * @param string $opt Name of option to retrieve
1816 * @return string Default option value
1818 public static function getDefaultOption( $opt ) {
1819 $defOpts = self
::getDefaultOptions();
1820 return $defOpts[$opt] ??
null;
1824 * Get blocking information
1826 * TODO: Move this into the BlockManager, along with block-related properties.
1828 * @param bool $fromReplica Whether to check the replica DB first.
1829 * To improve performance, non-critical checks are done against replica DBs.
1830 * Check when actually saving should be done against master.
1832 private function getBlockedStatus( $fromReplica = true ) {
1833 if ( $this->mBlockedby
!= -1 ) {
1837 wfDebug( __METHOD__
. ": checking...\n" );
1839 // Initialize data...
1840 // Otherwise something ends up stomping on $this->mBlockedby when
1841 // things get lazy-loaded later, causing false positive block hits
1842 // due to -1 !== 0. Probably session-related... Nothing should be
1843 // overwriting mBlockedby, surely?
1846 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1851 if ( $block instanceof Block
) {
1852 wfDebug( __METHOD__
. ": Found block.\n" );
1853 $this->mBlock
= $block;
1854 $this->mBlockedby
= $block->getByName();
1855 $this->mBlockreason
= $block->getReason();
1856 $this->mHideName
= $block->getHideName();
1857 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1859 $this->mBlock
= null;
1860 $this->mBlockedby
= '';
1861 $this->mBlockreason
= '';
1862 $this->mHideName
= 0;
1863 $this->mAllowUsertalk
= false;
1866 // Avoid PHP 7.1 warning of passing $this by reference
1869 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1873 * Whether the given IP is in a DNS blacklist.
1875 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1876 * @param string $ip IP to check
1877 * @param bool $checkWhitelist Whether to check the whitelist first
1878 * @return bool True if blacklisted.
1880 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1881 return MediaWikiServices
::getInstance()->getBlockManager()
1882 ->isDnsBlacklisted( $ip, $checkWhitelist );
1886 * Whether the given IP is in a given DNS blacklist.
1888 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1889 * @param string $ip IP to check
1890 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1891 * @return bool True if blacklisted.
1893 public function inDnsBlacklist( $ip, $bases ) {
1894 wfDeprecated( __METHOD__
, '1.34' );
1897 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1898 if ( IP
::isIPv4( $ip ) ) {
1899 // Reverse IP, T23255
1900 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1902 foreach ( (array)$bases as $base ) {
1904 // If we have an access key, use that too (ProjectHoneypot, etc.)
1906 if ( is_array( $base ) ) {
1907 if ( count( $base ) >= 2 ) {
1908 // Access key is 1, base URL is 0
1909 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1911 $host = "$ipReversed.{$base[0]}";
1913 $basename = $base[0];
1915 $host = "$ipReversed.$base";
1919 $ipList = gethostbynamel( $host );
1922 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1927 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1935 * Check if an IP address is in the local proxy list
1937 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1941 public static function isLocallyBlockedProxy( $ip ) {
1942 wfDeprecated( __METHOD__
, '1.34' );
1944 global $wgProxyList;
1946 if ( !$wgProxyList ) {
1950 if ( !is_array( $wgProxyList ) ) {
1951 // Load values from the specified file
1952 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1955 $resultProxyList = [];
1956 $deprecatedIPEntries = [];
1958 // backward compatibility: move all ip addresses in keys to values
1959 foreach ( $wgProxyList as $key => $value ) {
1960 $keyIsIP = IP
::isIPAddress( $key );
1961 $valueIsIP = IP
::isIPAddress( $value );
1962 if ( $keyIsIP && !$valueIsIP ) {
1963 $deprecatedIPEntries[] = $key;
1964 $resultProxyList[] = $key;
1965 } elseif ( $keyIsIP && $valueIsIP ) {
1966 $deprecatedIPEntries[] = $key;
1967 $resultProxyList[] = $key;
1968 $resultProxyList[] = $value;
1970 $resultProxyList[] = $value;
1974 if ( $deprecatedIPEntries ) {
1976 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1977 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1980 $proxyListIPSet = new IPSet( $resultProxyList );
1981 return $proxyListIPSet->match( $ip );
1985 * Is this user subject to rate limiting?
1987 * @return bool True if rate limited
1989 public function isPingLimitable() {
1990 global $wgRateLimitsExcludedIPs;
1991 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1992 // No other good way currently to disable rate limits
1993 // for specific IPs. :P
1994 // But this is a crappy hack and should die.
1997 return !$this->isAllowed( 'noratelimit' );
2001 * Primitive rate limits: enforce maximum actions per time period
2002 * to put a brake on flooding.
2004 * The method generates both a generic profiling point and a per action one
2005 * (suffix being "-$action".
2007 * @note When using a shared cache like memcached, IP-address
2008 * last-hit counters will be shared across wikis.
2010 * @param string $action Action to enforce; 'edit' if unspecified
2011 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2012 * @return bool True if a rate limiter was tripped
2014 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2015 // Avoid PHP 7.1 warning of passing $this by reference
2017 // Call the 'PingLimiter' hook
2019 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2023 global $wgRateLimits;
2024 if ( !isset( $wgRateLimits[$action] ) ) {
2028 $limits = array_merge(
2029 [ '&can-bypass' => true ],
2030 $wgRateLimits[$action]
2033 // Some groups shouldn't trigger the ping limiter, ever
2034 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2039 $id = $this->getId();
2041 $isNewbie = $this->isNewbie();
2042 $cache = ObjectCache
::getLocalClusterInstance();
2046 if ( isset( $limits['anon'] ) ) {
2047 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2049 } elseif ( isset( $limits['user'] ) ) {
2050 // limits for logged-in users
2051 $userLimit = $limits['user'];
2054 // limits for anons and for newbie logged-in users
2057 if ( isset( $limits['ip'] ) ) {
2058 $ip = $this->getRequest()->getIP();
2059 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2061 // subnet-based limits
2062 if ( isset( $limits['subnet'] ) ) {
2063 $ip = $this->getRequest()->getIP();
2064 $subnet = IP
::getSubnet( $ip );
2065 if ( $subnet !== false ) {
2066 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2071 // Check for group-specific permissions
2072 // If more than one group applies, use the group with the highest limit ratio (max/period)
2073 foreach ( $this->getGroups() as $group ) {
2074 if ( isset( $limits[$group] ) ) {
2075 if ( $userLimit === false
2076 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2078 $userLimit = $limits[$group];
2083 // limits for newbie logged-in users (override all the normal user limits)
2084 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2085 $userLimit = $limits['newbie'];
2088 // Set the user limit key
2089 if ( $userLimit !== false ) {
2090 // phan is confused because &can-bypass's value is a bool, so it assumes
2091 // that $userLimit is also a bool here.
2092 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2093 list( $max, $period ) = $userLimit;
2094 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2095 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2098 // ip-based limits for all ping-limitable users
2099 if ( isset( $limits['ip-all'] ) ) {
2100 $ip = $this->getRequest()->getIP();
2101 // ignore if user limit is more permissive
2102 if ( $isNewbie ||
$userLimit === false
2103 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2104 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2108 // subnet-based limits for all ping-limitable users
2109 if ( isset( $limits['subnet-all'] ) ) {
2110 $ip = $this->getRequest()->getIP();
2111 $subnet = IP
::getSubnet( $ip );
2112 if ( $subnet !== false ) {
2113 // ignore if user limit is more permissive
2114 if ( $isNewbie ||
$userLimit === false
2115 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2116 > $userLimit[0] / $userLimit[1] ) {
2117 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2123 foreach ( $keys as $key => $limit ) {
2124 // phan is confused because &can-bypass's value is a bool, so it assumes
2125 // that $userLimit is also a bool here.
2126 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2127 list( $max, $period ) = $limit;
2128 $summary = "(limit $max in {$period}s)";
2129 $count = $cache->get( $key );
2132 if ( $count >= $max ) {
2133 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2134 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2137 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2140 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2141 if ( $incrBy > 0 ) {
2142 $cache->add( $key, 0, intval( $period ) ); // first ping
2145 if ( $incrBy > 0 ) {
2146 $cache->incr( $key, $incrBy );
2154 * Check if user is blocked
2156 * @deprecated since 1.34, use User::getBlock() or
2157 * PermissionManager::isBlockedFrom() or
2158 * PermissionManager::userCan() instead.
2160 * @param bool $fromReplica Whether to check the replica DB instead of
2161 * the master. Hacked from false due to horrible probs on site.
2162 * @return bool True if blocked, false otherwise
2164 public function isBlocked( $fromReplica = true ) {
2165 return $this->getBlock( $fromReplica ) instanceof Block
&&
2166 $this->getBlock()->appliesToRight( 'edit' );
2170 * Get the block affecting the user, or null if the user is not blocked
2172 * @param bool $fromReplica Whether to check the replica DB instead of the master
2173 * @return Block|null
2175 public function getBlock( $fromReplica = true ) {
2176 $this->getBlockedStatus( $fromReplica );
2177 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2181 * Check if user is blocked from editing a particular article
2183 * @param Title $title Title to check
2184 * @param bool $fromReplica Whether to check the replica DB instead of the master
2186 * @throws MWException
2188 * @deprecated since 1.33,
2189 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2192 public function isBlockedFrom( $title, $fromReplica = false ) {
2193 return MediaWikiServices
::getInstance()->getPermissionManager()
2194 ->isBlockedFrom( $this, $title, $fromReplica );
2198 * If user is blocked, return the name of the user who placed the block
2199 * @return string Name of blocker
2201 public function blockedBy() {
2202 $this->getBlockedStatus();
2203 return $this->mBlockedby
;
2207 * If user is blocked, return the specified reason for the block
2208 * @return string Blocking reason
2210 public function blockedFor() {
2211 $this->getBlockedStatus();
2212 return $this->mBlockreason
;
2216 * If user is blocked, return the ID for the block
2217 * @return int Block ID
2219 public function getBlockId() {
2220 $this->getBlockedStatus();
2221 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2225 * Check if user is blocked on all wikis.
2226 * Do not use for actual edit permission checks!
2227 * This is intended for quick UI checks.
2229 * @param string $ip IP address, uses current client if none given
2230 * @return bool True if blocked, false otherwise
2232 public function isBlockedGlobally( $ip = '' ) {
2233 return $this->getGlobalBlock( $ip ) instanceof Block
;
2237 * Check if user is blocked on all wikis.
2238 * Do not use for actual edit permission checks!
2239 * This is intended for quick UI checks.
2241 * @param string $ip IP address, uses current client if none given
2242 * @return Block|null Block object if blocked, null otherwise
2243 * @throws FatalError
2244 * @throws MWException
2246 public function getGlobalBlock( $ip = '' ) {
2247 if ( $this->mGlobalBlock
!== null ) {
2248 return $this->mGlobalBlock ?
: null;
2250 // User is already an IP?
2251 if ( IP
::isIPAddress( $this->getName() ) ) {
2252 $ip = $this->getName();
2254 $ip = $this->getRequest()->getIP();
2256 // Avoid PHP 7.1 warning of passing $this by reference
2260 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2262 if ( $blocked && $block === null ) {
2263 // back-compat: UserIsBlockedGlobally didn't have $block param first
2264 $block = new Block( [
2266 'systemBlock' => 'global-block'
2270 $this->mGlobalBlock
= $blocked ?
$block : false;
2271 return $this->mGlobalBlock ?
: null;
2275 * Check if user account is locked
2277 * @return bool True if locked, false otherwise
2279 public function isLocked() {
2280 if ( $this->mLocked
!== null ) {
2281 return $this->mLocked
;
2284 $this->mLocked
= false;
2285 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2286 return $this->mLocked
;
2290 * Check if user account is hidden
2292 * @return bool True if hidden, false otherwise
2294 public function isHidden() {
2295 if ( $this->mHideName
!== null ) {
2296 return (bool)$this->mHideName
;
2298 $this->getBlockedStatus();
2299 if ( !$this->mHideName
) {
2301 $this->mHideName
= false;
2302 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2304 return (bool)$this->mHideName
;
2308 * Get the user's ID.
2309 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2311 public function getId() {
2312 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2313 // Special case, we know the user is anonymous
2317 if ( !$this->isItemLoaded( 'id' ) ) {
2318 // Don't load if this was initialized from an ID
2322 return (int)$this->mId
;
2326 * Set the user and reload all fields according to a given ID
2327 * @param int $v User ID to reload
2329 public function setId( $v ) {
2331 $this->clearInstanceCache( 'id' );
2335 * Get the user name, or the IP of an anonymous user
2336 * @return string User's name or IP address
2338 public function getName() {
2339 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2340 // Special case optimisation
2341 return $this->mName
;
2345 if ( $this->mName
=== false ) {
2347 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2350 return $this->mName
;
2354 * Set the user name.
2356 * This does not reload fields from the database according to the given
2357 * name. Rather, it is used to create a temporary "nonexistent user" for
2358 * later addition to the database. It can also be used to set the IP
2359 * address for an anonymous user to something other than the current
2362 * @note User::newFromName() has roughly the same function, when the named user
2364 * @param string $str New user name to set
2366 public function setName( $str ) {
2368 $this->mName
= $str;
2372 * Get the user's actor ID.
2374 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2375 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2377 public function getActorId( IDatabase
$dbw = null ) {
2378 global $wgActorTableSchemaMigrationStage;
2380 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2381 // but it does little harm and might be needed for write callers loading a User.
2382 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2386 if ( !$this->isItemLoaded( 'actor' ) ) {
2390 // Currently $this->mActorId might be null if $this was loaded from a
2391 // cache entry that was written when $wgActorTableSchemaMigrationStage
2392 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2393 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2394 // has been removed), that condition may be removed.
2395 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2397 'actor_user' => $this->getId() ?
: null,
2398 'actor_name' => (string)$this->getName(),
2401 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2402 throw new CannotCreateActorException(
2403 'Cannot create an actor for a usable name that is not an existing user'
2406 if ( $q['actor_name'] === '' ) {
2407 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2409 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2410 if ( $dbw->affectedRows() ) {
2411 $this->mActorId
= (int)$dbw->insertId();
2414 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2415 $this->mActorId
= (int)$dbw->selectField(
2420 [ 'LOCK IN SHARE MODE' ]
2422 if ( !$this->mActorId
) {
2423 throw new CannotCreateActorException(
2424 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2428 $this->invalidateCache();
2430 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2431 $db = wfGetDB( $index );
2432 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2434 $this->setItemLoaded( 'actor' );
2437 return (int)$this->mActorId
;
2441 * Get the user's name escaped by underscores.
2442 * @return string Username escaped by underscores.
2444 public function getTitleKey() {
2445 return str_replace( ' ', '_', $this->getName() );
2449 * Check if the user has new messages.
2450 * @return bool True if the user has new messages
2452 public function getNewtalk() {
2455 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2456 if ( $this->mNewtalk
=== -1 ) {
2457 $this->mNewtalk
= false; # reset talk page status
2459 // Check memcached separately for anons, who have no
2460 // entire User object stored in there.
2461 if ( !$this->mId
) {
2462 global $wgDisableAnonTalk;
2463 if ( $wgDisableAnonTalk ) {
2464 // Anon newtalk disabled by configuration.
2465 $this->mNewtalk
= false;
2467 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2470 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2474 return (bool)$this->mNewtalk
;
2478 * Return the data needed to construct links for new talk page message
2479 * alerts. If there are new messages, this will return an associative array
2480 * with the following data:
2481 * wiki: The database name of the wiki
2482 * link: Root-relative link to the user's talk page
2483 * rev: The last talk page revision that the user has seen or null. This
2484 * is useful for building diff links.
2485 * If there are no new messages, it returns an empty array.
2486 * @note This function was designed to accomodate multiple talk pages, but
2487 * currently only returns a single link and revision.
2490 public function getNewMessageLinks() {
2491 // Avoid PHP 7.1 warning of passing $this by reference
2494 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2498 if ( !$this->getNewtalk() ) {
2501 $utp = $this->getTalkPage();
2502 $dbr = wfGetDB( DB_REPLICA
);
2503 // Get the "last viewed rev" timestamp from the oldest message notification
2504 $timestamp = $dbr->selectField( 'user_newtalk',
2505 'MIN(user_last_timestamp)',
2506 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2508 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2511 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2512 'link' => $utp->getLocalURL(),
2519 * Get the revision ID for the last talk page revision viewed by the talk
2521 * @return int|null Revision ID or null
2523 public function getNewMessageRevisionId() {
2524 $newMessageRevisionId = null;
2525 $newMessageLinks = $this->getNewMessageLinks();
2527 // Note: getNewMessageLinks() never returns more than a single link
2528 // and it is always for the same wiki, but we double-check here in
2529 // case that changes some time in the future.
2530 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2531 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2532 && $newMessageLinks[0]['rev']
2534 /** @var Revision $newMessageRevision */
2535 $newMessageRevision = $newMessageLinks[0]['rev'];
2536 $newMessageRevisionId = $newMessageRevision->getId();
2539 return $newMessageRevisionId;
2543 * Internal uncached check for new messages
2546 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2547 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2548 * @return bool True if the user has new messages
2550 protected function checkNewtalk( $field, $id ) {
2551 $dbr = wfGetDB( DB_REPLICA
);
2553 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2555 return $ok !== false;
2559 * Add or update the new messages flag
2560 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2561 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2562 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2563 * @return bool True if successful, false otherwise
2565 protected function updateNewtalk( $field, $id, $curRev = null ) {
2566 // Get timestamp of the talk page revision prior to the current one
2567 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2568 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2569 // Mark the user as having new messages since this revision
2570 $dbw = wfGetDB( DB_MASTER
);
2571 $dbw->insert( 'user_newtalk',
2572 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2575 if ( $dbw->affectedRows() ) {
2576 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2580 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2585 * Clear the new messages flag for the given user
2586 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2587 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2588 * @return bool True if successful, false otherwise
2590 protected function deleteNewtalk( $field, $id ) {
2591 $dbw = wfGetDB( DB_MASTER
);
2592 $dbw->delete( 'user_newtalk',
2595 if ( $dbw->affectedRows() ) {
2596 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2600 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2605 * Update the 'You have new messages!' status.
2606 * @param bool $val Whether the user has new messages
2607 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2608 * page. Ignored if null or !$val.
2610 public function setNewtalk( $val, $curRev = null ) {
2611 if ( wfReadOnly() ) {
2616 $this->mNewtalk
= $val;
2618 if ( $this->isAnon() ) {
2620 $id = $this->getName();
2623 $id = $this->getId();
2627 $changed = $this->updateNewtalk( $field, $id, $curRev );
2629 $changed = $this->deleteNewtalk( $field, $id );
2633 $this->invalidateCache();
2638 * Generate a current or new-future timestamp to be stored in the
2639 * user_touched field when we update things.
2641 * @return string Timestamp in TS_MW format
2643 private function newTouchedTimestamp() {
2645 if ( $this->mTouched
) {
2646 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2649 return wfTimestamp( TS_MW
, $time );
2653 * Clear user data from memcached
2655 * Use after applying updates to the database; caller's
2656 * responsibility to update user_touched if appropriate.
2658 * Called implicitly from invalidateCache() and saveSettings().
2660 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2662 public function clearSharedCache( $mode = 'refresh' ) {
2663 if ( !$this->getId() ) {
2667 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2668 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2669 $key = $this->getCacheKey( $cache );
2671 if ( $mode === 'refresh' ) {
2672 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2674 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2675 function () use ( $cache, $key ) {
2676 $cache->delete( $key );
2684 * Immediately touch the user data cache for this account
2686 * Calls touch() and removes account data from memcached
2688 public function invalidateCache() {
2690 $this->clearSharedCache( 'changed' );
2694 * Update the "touched" timestamp for the user
2696 * This is useful on various login/logout events when making sure that
2697 * a browser or proxy that has multiple tenants does not suffer cache
2698 * pollution where the new user sees the old users content. The value
2699 * of getTouched() is checked when determining 304 vs 200 responses.
2700 * Unlike invalidateCache(), this preserves the User object cache and
2701 * avoids database writes.
2705 public function touch() {
2706 $id = $this->getId();
2708 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2709 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2710 $cache->touchCheckKey( $key );
2711 $this->mQuickTouched
= null;
2716 * Validate the cache for this account.
2717 * @param string $timestamp A timestamp in TS_MW format
2720 public function validateCache( $timestamp ) {
2721 return ( $timestamp >= $this->getTouched() );
2725 * Get the user touched timestamp
2727 * Use this value only to validate caches via inequalities
2728 * such as in the case of HTTP If-Modified-Since response logic
2730 * @return string TS_MW Timestamp
2732 public function getTouched() {
2736 if ( $this->mQuickTouched
=== null ) {
2737 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2738 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2740 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2743 return max( $this->mTouched
, $this->mQuickTouched
);
2746 return $this->mTouched
;
2750 * Get the user_touched timestamp field (time of last DB updates)
2751 * @return string TS_MW Timestamp
2754 public function getDBTouched() {
2757 return $this->mTouched
;
2761 * Set the password and reset the random token.
2762 * Calls through to authentication plugin if necessary;
2763 * will have no effect if the auth plugin refuses to
2764 * pass the change through or if the legal password
2767 * As a special case, setting the password to null
2768 * wipes it, so the account cannot be logged in until
2769 * a new password is set, for instance via e-mail.
2771 * @deprecated since 1.27, use AuthManager instead
2772 * @param string $str New password to set
2773 * @throws PasswordError On failure
2776 public function setPassword( $str ) {
2777 wfDeprecated( __METHOD__
, '1.27' );
2778 return $this->setPasswordInternal( $str );
2782 * Set the password and reset the random token unconditionally.
2784 * @deprecated since 1.27, use AuthManager instead
2785 * @param string|null $str New password to set or null to set an invalid
2786 * password hash meaning that the user will not be able to log in
2787 * through the web interface.
2789 public function setInternalPassword( $str ) {
2790 wfDeprecated( __METHOD__
, '1.27' );
2791 $this->setPasswordInternal( $str );
2795 * Actually set the password and such
2796 * @since 1.27 cannot set a password for a user not in the database
2797 * @param string|null $str New password to set or null to set an invalid
2798 * password hash meaning that the user will not be able to log in
2799 * through the web interface.
2800 * @return bool Success
2802 private function setPasswordInternal( $str ) {
2803 $manager = AuthManager
::singleton();
2805 // If the user doesn't exist yet, fail
2806 if ( !$manager->userExists( $this->getName() ) ) {
2807 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2810 $status = $this->changeAuthenticationData( [
2811 'username' => $this->getName(),
2815 if ( !$status->isGood() ) {
2816 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2817 ->info( __METHOD__
. ': Password change rejected: '
2818 . $status->getWikiText( null, null, 'en' ) );
2822 $this->setOption( 'watchlisttoken', false );
2823 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2829 * Changes credentials of the user.
2831 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2832 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2833 * e.g. when no provider handled the change.
2835 * @param array $data A set of authentication data in fieldname => value format. This is the
2836 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2840 public function changeAuthenticationData( array $data ) {
2841 $manager = AuthManager
::singleton();
2842 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2843 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2845 $status = Status
::newGood( 'ignored' );
2846 foreach ( $reqs as $req ) {
2847 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2849 if ( $status->getValue() === 'ignored' ) {
2850 $status->warning( 'authenticationdatachange-ignored' );
2853 if ( $status->isGood() ) {
2854 foreach ( $reqs as $req ) {
2855 $manager->changeAuthenticationData( $req );
2862 * Get the user's current token.
2863 * @param bool $forceCreation Force the generation of a new token if the
2864 * user doesn't have one (default=true for backwards compatibility).
2865 * @return string|null Token
2867 public function getToken( $forceCreation = true ) {
2868 global $wgAuthenticationTokenVersion;
2871 if ( !$this->mToken
&& $forceCreation ) {
2875 if ( !$this->mToken
) {
2876 // The user doesn't have a token, return null to indicate that.
2880 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2881 // We return a random value here so existing token checks are very
2883 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2886 if ( $wgAuthenticationTokenVersion === null ) {
2887 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2888 return $this->mToken
;
2891 // $wgAuthenticationTokenVersion in use, so hmac it.
2892 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2894 // The raw hash can be overly long. Shorten it up.
2895 $len = max( 32, self
::TOKEN_LENGTH
);
2896 if ( strlen( $ret ) < $len ) {
2897 // Should never happen, even md5 is 128 bits
2898 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2901 return substr( $ret, -$len );
2905 * Set the random token (used for persistent authentication)
2906 * Called from loadDefaults() among other places.
2908 * @param string|bool $token If specified, set the token to this value
2910 public function setToken( $token = false ) {
2912 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2913 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2914 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2915 } elseif ( !$token ) {
2916 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2918 $this->mToken
= $token;
2923 * Set the password for a password reminder or new account email
2925 * @deprecated Removed in 1.27. Use PasswordReset instead.
2926 * @param string $str New password to set or null to set an invalid
2927 * password hash meaning that the user will not be able to use it
2928 * @param bool $throttle If true, reset the throttle timestamp to the present
2930 public function setNewpassword( $str, $throttle = true ) {
2931 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2935 * Get the user's e-mail address
2936 * @return string User's email address
2938 public function getEmail() {
2940 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2941 return $this->mEmail
;
2945 * Get the timestamp of the user's e-mail authentication
2946 * @return string TS_MW timestamp
2948 public function getEmailAuthenticationTimestamp() {
2950 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2951 return $this->mEmailAuthenticated
;
2955 * Set the user's e-mail address
2956 * @param string $str New e-mail address
2958 public function setEmail( $str ) {
2960 if ( $str == $this->mEmail
) {
2963 $this->invalidateEmail();
2964 $this->mEmail
= $str;
2965 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2969 * Set the user's e-mail address and a confirmation mail if needed.
2972 * @param string $str New e-mail address
2975 public function setEmailWithConfirmation( $str ) {
2976 global $wgEnableEmail, $wgEmailAuthentication;
2978 if ( !$wgEnableEmail ) {
2979 return Status
::newFatal( 'emaildisabled' );
2982 $oldaddr = $this->getEmail();
2983 if ( $str === $oldaddr ) {
2984 return Status
::newGood( true );
2987 $type = $oldaddr != '' ?
'changed' : 'set';
2988 $notificationResult = null;
2990 if ( $wgEmailAuthentication && $type === 'changed' ) {
2991 // Send the user an email notifying the user of the change in registered
2992 // email address on their previous email address
2993 $change = $str != '' ?
'changed' : 'removed';
2994 $notificationResult = $this->sendMail(
2995 wfMessage( 'notificationemail_subject_' . $change )->text(),
2996 wfMessage( 'notificationemail_body_' . $change,
2997 $this->getRequest()->getIP(),
3003 $this->setEmail( $str );
3005 if ( $str !== '' && $wgEmailAuthentication ) {
3006 // Send a confirmation request to the new address if needed
3007 $result = $this->sendConfirmationMail( $type );
3009 if ( $notificationResult !== null ) {
3010 $result->merge( $notificationResult );
3013 if ( $result->isGood() ) {
3014 // Say to the caller that a confirmation and notification mail has been sent
3015 $result->value
= 'eauth';
3018 $result = Status
::newGood( true );
3025 * Get the user's real name
3026 * @return string User's real name
3028 public function getRealName() {
3029 if ( !$this->isItemLoaded( 'realname' ) ) {
3033 return $this->mRealName
;
3037 * Set the user's real name
3038 * @param string $str New real name
3040 public function setRealName( $str ) {
3042 $this->mRealName
= $str;
3046 * Get the user's current setting for a given option.
3048 * @param string $oname The option to check
3049 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3050 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3051 * @return string|array|int|null User's current value for the option
3052 * @see getBoolOption()
3053 * @see getIntOption()
3055 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3056 global $wgHiddenPrefs;
3057 $this->loadOptions();
3059 # We want 'disabled' preferences to always behave as the default value for
3060 # users, even if they have set the option explicitly in their settings (ie they
3061 # set it, and then it was disabled removing their ability to change it). But
3062 # we don't want to erase the preferences in the database in case the preference
3063 # is re-enabled again. So don't touch $mOptions, just override the returned value
3064 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3065 return self
::getDefaultOption( $oname );
3068 if ( array_key_exists( $oname, $this->mOptions
) ) {
3069 return $this->mOptions
[$oname];
3072 return $defaultOverride;
3076 * Get all user's options
3078 * @param int $flags Bitwise combination of:
3079 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3080 * to the default value. (Since 1.25)
3083 public function getOptions( $flags = 0 ) {
3084 global $wgHiddenPrefs;
3085 $this->loadOptions();
3086 $options = $this->mOptions
;
3088 # We want 'disabled' preferences to always behave as the default value for
3089 # users, even if they have set the option explicitly in their settings (ie they
3090 # set it, and then it was disabled removing their ability to change it). But
3091 # we don't want to erase the preferences in the database in case the preference
3092 # is re-enabled again. So don't touch $mOptions, just override the returned value
3093 foreach ( $wgHiddenPrefs as $pref ) {
3094 $default = self
::getDefaultOption( $pref );
3095 if ( $default !== null ) {
3096 $options[$pref] = $default;
3100 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3101 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3108 * Get the user's current setting for a given option, as a boolean value.
3110 * @param string $oname The option to check
3111 * @return bool User's current value for the option
3114 public function getBoolOption( $oname ) {
3115 return (bool)$this->getOption( $oname );
3119 * Get the user's current setting for a given option, as an integer value.
3121 * @param string $oname The option to check
3122 * @param int $defaultOverride A default value returned if the option does not exist
3123 * @return int User's current value for the option
3126 public function getIntOption( $oname, $defaultOverride = 0 ) {
3127 $val = $this->getOption( $oname );
3129 $val = $defaultOverride;
3131 return intval( $val );
3135 * Set the given option for a user.
3137 * You need to call saveSettings() to actually write to the database.
3139 * @param string $oname The option to set
3140 * @param mixed $val New value to set
3142 public function setOption( $oname, $val ) {
3143 $this->loadOptions();
3145 // Explicitly NULL values should refer to defaults
3146 if ( is_null( $val ) ) {
3147 $val = self
::getDefaultOption( $oname );
3150 $this->mOptions
[$oname] = $val;
3154 * Get a token stored in the preferences (like the watchlist one),
3155 * resetting it if it's empty (and saving changes).
3157 * @param string $oname The option name to retrieve the token from
3158 * @return string|bool User's current value for the option, or false if this option is disabled.
3159 * @see resetTokenFromOption()
3161 * @deprecated since 1.26 Applications should use the OAuth extension
3163 public function getTokenFromOption( $oname ) {
3164 global $wgHiddenPrefs;
3166 $id = $this->getId();
3167 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3171 $token = $this->getOption( $oname );
3173 // Default to a value based on the user token to avoid space
3174 // wasted on storing tokens for all users. When this option
3175 // is set manually by the user, only then is it stored.
3176 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3183 * Reset a token stored in the preferences (like the watchlist one).
3184 * *Does not* save user's preferences (similarly to setOption()).
3186 * @param string $oname The option name to reset the token in
3187 * @return string|bool New token value, or false if this option is disabled.
3188 * @see getTokenFromOption()
3191 public function resetTokenFromOption( $oname ) {
3192 global $wgHiddenPrefs;
3193 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3197 $token = MWCryptRand
::generateHex( 40 );
3198 $this->setOption( $oname, $token );
3203 * Return a list of the types of user options currently returned by
3204 * User::getOptionKinds().
3206 * Currently, the option kinds are:
3207 * - 'registered' - preferences which are registered in core MediaWiki or
3208 * by extensions using the UserGetDefaultOptions hook.
3209 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3210 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3211 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3212 * be used by user scripts.
3213 * - 'special' - "preferences" that are not accessible via User::getOptions
3214 * or User::setOptions.
3215 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3216 * These are usually legacy options, removed in newer versions.
3218 * The API (and possibly others) use this function to determine the possible
3219 * option types for validation purposes, so make sure to update this when a
3220 * new option kind is added.
3222 * @see User::getOptionKinds
3223 * @return array Option kinds
3225 public static function listOptionKinds() {
3228 'registered-multiselect',
3229 'registered-checkmatrix',
3237 * Return an associative array mapping preferences keys to the kind of a preference they're
3238 * used for. Different kinds are handled differently when setting or reading preferences.
3240 * See User::listOptionKinds for the list of valid option types that can be provided.
3242 * @see User::listOptionKinds
3243 * @param IContextSource $context
3244 * @param array|null $options Assoc. array with options keys to check as keys.
3245 * Defaults to $this->mOptions.
3246 * @return array The key => kind mapping data
3248 public function getOptionKinds( IContextSource
$context, $options = null ) {
3249 $this->loadOptions();
3250 if ( $options === null ) {
3251 $options = $this->mOptions
;
3254 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3255 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3258 // Pull out the "special" options, so they don't get converted as
3259 // multiselect or checkmatrix.
3260 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3261 foreach ( $specialOptions as $name => $value ) {
3262 unset( $prefs[$name] );
3265 // Multiselect and checkmatrix options are stored in the database with
3266 // one key per option, each having a boolean value. Extract those keys.
3267 $multiselectOptions = [];
3268 foreach ( $prefs as $name => $info ) {
3269 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3270 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3271 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3272 $prefix = $info['prefix'] ??
$name;
3274 foreach ( $opts as $value ) {
3275 $multiselectOptions["$prefix$value"] = true;
3278 unset( $prefs[$name] );
3281 $checkmatrixOptions = [];
3282 foreach ( $prefs as $name => $info ) {
3283 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3284 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3285 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3286 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3287 $prefix = $info['prefix'] ??
$name;
3289 foreach ( $columns as $column ) {
3290 foreach ( $rows as $row ) {
3291 $checkmatrixOptions["$prefix$column-$row"] = true;
3295 unset( $prefs[$name] );
3299 // $value is ignored
3300 foreach ( $options as $key => $value ) {
3301 if ( isset( $prefs[$key] ) ) {
3302 $mapping[$key] = 'registered';
3303 } elseif ( isset( $multiselectOptions[$key] ) ) {
3304 $mapping[$key] = 'registered-multiselect';
3305 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3306 $mapping[$key] = 'registered-checkmatrix';
3307 } elseif ( isset( $specialOptions[$key] ) ) {
3308 $mapping[$key] = 'special';
3309 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3310 $mapping[$key] = 'userjs';
3312 $mapping[$key] = 'unused';
3320 * Reset certain (or all) options to the site defaults
3322 * The optional parameter determines which kinds of preferences will be reset.
3323 * Supported values are everything that can be reported by getOptionKinds()
3324 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3326 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3327 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3328 * for backwards-compatibility.
3329 * @param IContextSource|null $context Context source used when $resetKinds
3330 * does not contain 'all', passed to getOptionKinds().
3331 * Defaults to RequestContext::getMain() when null.
3333 public function resetOptions(
3334 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3335 IContextSource
$context = null
3338 $defaultOptions = self
::getDefaultOptions();
3340 if ( !is_array( $resetKinds ) ) {
3341 $resetKinds = [ $resetKinds ];
3344 if ( in_array( 'all', $resetKinds ) ) {
3345 $newOptions = $defaultOptions;
3347 if ( $context === null ) {
3348 $context = RequestContext
::getMain();
3351 $optionKinds = $this->getOptionKinds( $context );
3352 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3355 // Use default values for the options that should be deleted, and
3356 // copy old values for the ones that shouldn't.
3357 foreach ( $this->mOptions
as $key => $value ) {
3358 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3359 if ( array_key_exists( $key, $defaultOptions ) ) {
3360 $newOptions[$key] = $defaultOptions[$key];
3363 $newOptions[$key] = $value;
3368 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3370 $this->mOptions
= $newOptions;
3371 $this->mOptionsLoaded
= true;
3375 * Get the user's preferred date format.
3376 * @return string User's preferred date format
3378 public function getDatePreference() {
3379 // Important migration for old data rows
3380 if ( is_null( $this->mDatePreference
) ) {
3382 $value = $this->getOption( 'date' );
3383 $map = $wgLang->getDatePreferenceMigrationMap();
3384 if ( isset( $map[$value] ) ) {
3385 $value = $map[$value];
3387 $this->mDatePreference
= $value;
3389 return $this->mDatePreference
;
3393 * Determine based on the wiki configuration and the user's options,
3394 * whether this user must be over HTTPS no matter what.
3398 public function requiresHTTPS() {
3399 global $wgSecureLogin;
3400 if ( !$wgSecureLogin ) {
3404 $https = $this->getBoolOption( 'prefershttps' );
3405 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3407 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3414 * Get the user preferred stub threshold
3418 public function getStubThreshold() {
3419 global $wgMaxArticleSize; # Maximum article size, in Kb
3420 $threshold = $this->getIntOption( 'stubthreshold' );
3421 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3422 // If they have set an impossible value, disable the preference
3423 // so we can use the parser cache again.
3430 * Get the permissions this user has.
3431 * @return string[] permission names
3433 public function getRights() {
3434 if ( is_null( $this->mRights
) ) {
3435 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3436 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3438 // Deny any rights denied by the user's session, unless this
3439 // endpoint has no sessions.
3440 if ( !defined( 'MW_NO_SESSION' ) ) {
3441 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3442 if ( $allowedRights !== null ) {
3443 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3447 Hooks
::run( 'UserGetRightsRemove', [ $this, &$this->mRights
] );
3448 // Force reindexation of rights when a hook has unset one of them
3449 $this->mRights
= array_values( array_unique( $this->mRights
) );
3451 // If block disables login, we should also remove any
3452 // extra rights blocked users might have, in case the
3453 // blocked user has a pre-existing session (T129738).
3454 // This is checked here for cases where people only call
3455 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3456 // to give a better error message in the common case.
3457 $config = RequestContext
::getMain()->getConfig();
3458 // @TODO Partial blocks should not prevent the user from logging in.
3459 // see: https://phabricator.wikimedia.org/T208895
3461 $this->isLoggedIn() &&
3462 $config->get( 'BlockDisablesLogin' ) &&
3466 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3469 return $this->mRights
;
3473 * Get the list of explicit group memberships this user has.
3474 * The implicit * and user groups are not included.
3476 * @return string[] Array of internal group names (sorted since 1.33)
3478 public function getGroups() {
3480 $this->loadGroups();
3481 return array_keys( $this->mGroupMemberships
);
3485 * Get the list of explicit group memberships this user has, stored as
3486 * UserGroupMembership objects. Implicit groups are not included.
3488 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3491 public function getGroupMemberships() {
3493 $this->loadGroups();
3494 return $this->mGroupMemberships
;
3498 * Get the list of implicit group memberships this user has.
3499 * This includes all explicit groups, plus 'user' if logged in,
3500 * '*' for all accounts, and autopromoted groups
3501 * @param bool $recache Whether to avoid the cache
3502 * @return array Array of String internal group names
3504 public function getEffectiveGroups( $recache = false ) {
3505 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3506 $this->mEffectiveGroups
= array_unique( array_merge(
3507 $this->getGroups(), // explicit groups
3508 $this->getAutomaticGroups( $recache ) // implicit groups
3510 // Avoid PHP 7.1 warning of passing $this by reference
3512 // Hook for additional groups
3513 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3514 // Force reindexation of groups when a hook has unset one of them
3515 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3517 return $this->mEffectiveGroups
;
3521 * Get the list of implicit group memberships this user has.
3522 * This includes 'user' if logged in, '*' for all accounts,
3523 * and autopromoted groups
3524 * @param bool $recache Whether to avoid the cache
3525 * @return array Array of String internal group names
3527 public function getAutomaticGroups( $recache = false ) {
3528 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3529 $this->mImplicitGroups
= [ '*' ];
3530 if ( $this->getId() ) {
3531 $this->mImplicitGroups
[] = 'user';
3533 $this->mImplicitGroups
= array_unique( array_merge(
3534 $this->mImplicitGroups
,
3535 Autopromote
::getAutopromoteGroups( $this )
3539 // Assure data consistency with rights/groups,
3540 // as getEffectiveGroups() depends on this function
3541 $this->mEffectiveGroups
= null;
3544 return $this->mImplicitGroups
;
3548 * Returns the groups the user has belonged to.
3550 * The user may still belong to the returned groups. Compare with getGroups().
3552 * The function will not return groups the user had belonged to before MW 1.17
3554 * @return array Names of the groups the user has belonged to.
3556 public function getFormerGroups() {
3559 if ( is_null( $this->mFormerGroups
) ) {
3560 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3561 ?
wfGetDB( DB_MASTER
)
3562 : wfGetDB( DB_REPLICA
);
3563 $res = $db->select( 'user_former_groups',
3565 [ 'ufg_user' => $this->mId
],
3567 $this->mFormerGroups
= [];
3568 foreach ( $res as $row ) {
3569 $this->mFormerGroups
[] = $row->ufg_group
;
3573 return $this->mFormerGroups
;
3577 * Get the user's edit count.
3578 * @return int|null Null for anonymous users
3580 public function getEditCount() {
3581 if ( !$this->getId() ) {
3585 if ( $this->mEditCount
=== null ) {
3586 /* Populate the count, if it has not been populated yet */
3587 $dbr = wfGetDB( DB_REPLICA
);
3588 // check if the user_editcount field has been initialized
3589 $count = $dbr->selectField(
3590 'user', 'user_editcount',
3591 [ 'user_id' => $this->mId
],
3595 if ( $count === null ) {
3596 // it has not been initialized. do so.
3597 $count = $this->initEditCountInternal();
3599 $this->mEditCount
= $count;
3601 return (int)$this->mEditCount
;
3605 * Add the user to the given group. This takes immediate effect.
3606 * If the user is already in the group, the expiry time will be updated to the new
3607 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3610 * @param string $group Name of the group to add
3611 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3612 * wfTimestamp(), or null if the group assignment should not expire
3615 public function addGroup( $group, $expiry = null ) {
3617 $this->loadGroups();
3620 $expiry = wfTimestamp( TS_MW
, $expiry );
3623 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3627 // create the new UserGroupMembership and put it in the DB
3628 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3629 if ( !$ugm->insert( true ) ) {
3633 $this->mGroupMemberships
[$group] = $ugm;
3635 // Refresh the groups caches, and clear the rights cache so it will be
3636 // refreshed on the next call to $this->getRights().
3637 $this->getEffectiveGroups( true );
3638 $this->mRights
= null;
3640 $this->invalidateCache();
3646 * Remove the user from the given group.
3647 * This takes immediate effect.
3648 * @param string $group Name of the group to remove
3651 public function removeGroup( $group ) {
3654 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3658 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3659 // delete the membership entry
3660 if ( !$ugm ||
!$ugm->delete() ) {
3664 $this->loadGroups();
3665 unset( $this->mGroupMemberships
[$group] );
3667 // Refresh the groups caches, and clear the rights cache so it will be
3668 // refreshed on the next call to $this->getRights().
3669 $this->getEffectiveGroups( true );
3670 $this->mRights
= null;
3672 $this->invalidateCache();
3678 * Get whether the user is logged in
3681 public function isLoggedIn() {
3682 return $this->getId() != 0;
3686 * Get whether the user is anonymous
3689 public function isAnon() {
3690 return !$this->isLoggedIn();
3694 * @return bool Whether this user is flagged as being a bot role account
3697 public function isBot() {
3698 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3703 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3709 * Check if user is allowed to access a feature / make an action
3711 * @param string $permissions,... Permissions to test
3712 * @return bool True if user is allowed to perform *any* of the given actions
3714 public function isAllowedAny() {
3715 $permissions = func_get_args();
3716 foreach ( $permissions as $permission ) {
3717 if ( $this->isAllowed( $permission ) ) {
3726 * @param string $permissions,... Permissions to test
3727 * @return bool True if the user is allowed to perform *all* of the given actions
3729 public function isAllowedAll() {
3730 $permissions = func_get_args();
3731 foreach ( $permissions as $permission ) {
3732 if ( !$this->isAllowed( $permission ) ) {
3740 * Internal mechanics of testing a permission
3741 * @param string $action
3744 public function isAllowed( $action = '' ) {
3745 if ( $action === '' ) {
3746 return true; // In the spirit of DWIM
3748 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3749 // by misconfiguration: 0 == 'foo'
3750 return in_array( $action, $this->getRights(), true );
3754 * Check whether to enable recent changes patrol features for this user
3755 * @return bool True or false
3757 public function useRCPatrol() {
3758 global $wgUseRCPatrol;
3759 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3763 * Check whether to enable new pages patrol features for this user
3764 * @return bool True or false
3766 public function useNPPatrol() {
3767 global $wgUseRCPatrol, $wgUseNPPatrol;
3769 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3770 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3775 * Check whether to enable new files patrol features for this user
3776 * @return bool True or false
3778 public function useFilePatrol() {
3779 global $wgUseRCPatrol, $wgUseFilePatrol;
3781 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3782 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3787 * Get the WebRequest object to use with this object
3789 * @return WebRequest
3791 public function getRequest() {
3792 if ( $this->mRequest
) {
3793 return $this->mRequest
;
3801 * Check the watched status of an article.
3802 * @since 1.22 $checkRights parameter added
3803 * @param Title $title Title of the article to look at
3804 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3805 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3808 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3809 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3810 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3817 * @since 1.22 $checkRights parameter added
3818 * @param Title $title Title of the article to look at
3819 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3820 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3822 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3823 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3824 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3826 [ $title->getSubjectPage(), $title->getTalkPage() ]
3829 $this->invalidateCache();
3833 * Stop watching an article.
3834 * @since 1.22 $checkRights parameter added
3835 * @param Title $title Title of the article to look at
3836 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3837 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3839 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3840 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3841 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3842 $store->removeWatch( $this, $title->getSubjectPage() );
3843 $store->removeWatch( $this, $title->getTalkPage() );
3845 $this->invalidateCache();
3849 * Clear the user's notification timestamp for the given title.
3850 * If e-notif e-mails are on, they will receive notification mails on
3851 * the next change of the page if it's watched etc.
3852 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3853 * @param Title &$title Title of the article to look at
3854 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3856 public function clearNotification( &$title, $oldid = 0 ) {
3857 global $wgUseEnotif, $wgShowUpdatedMarker;
3859 // Do nothing if the database is locked to writes
3860 if ( wfReadOnly() ) {
3864 // Do nothing if not allowed to edit the watchlist
3865 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3869 // If we're working on user's talk page, we should update the talk page message indicator
3870 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3871 // Avoid PHP 7.1 warning of passing $this by reference
3873 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3877 // Try to update the DB post-send and only if needed...
3878 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3879 if ( !$this->getNewtalk() ) {
3880 return; // no notifications to clear
3883 // Delete the last notifications (they stack up)
3884 $this->setNewtalk( false );
3886 // If there is a new, unseen, revision, use its timestamp
3888 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3891 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3896 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3900 if ( $this->isAnon() ) {
3901 // Nothing else to do...
3905 // Only update the timestamp if the page is being watched.
3906 // The query to find out if it is watched is cached both in memcached and per-invocation,
3907 // and when it does have to be executed, it can be on a replica DB
3908 // If this is the user's newtalk page, we always update the timestamp
3910 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3914 MediaWikiServices
::getInstance()->getWatchedItemStore()
3915 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3919 * Resets all of the given user's page-change notification timestamps.
3920 * If e-notif e-mails are on, they will receive notification mails on
3921 * the next change of any watched page.
3922 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3924 public function clearAllNotifications() {
3925 global $wgUseEnotif, $wgShowUpdatedMarker;
3926 // Do nothing if not allowed to edit the watchlist
3927 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3931 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3932 $this->setNewtalk( false );
3936 $id = $this->getId();
3941 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3942 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3944 // We also need to clear here the "you have new message" notification for the own
3945 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3949 * Compute experienced level based on edit count and registration date.
3951 * @return string 'newcomer', 'learner', or 'experienced'
3953 public function getExperienceLevel() {
3954 global $wgLearnerEdits,
3955 $wgExperiencedUserEdits,
3956 $wgLearnerMemberSince,
3957 $wgExperiencedUserMemberSince;
3959 if ( $this->isAnon() ) {
3963 $editCount = $this->getEditCount();
3964 $registration = $this->getRegistration();
3966 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3967 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3969 if ( $editCount < $wgLearnerEdits ||
3970 $registration > $learnerRegistration ) {
3974 if ( $editCount > $wgExperiencedUserEdits &&
3975 $registration <= $experiencedRegistration
3977 return 'experienced';
3984 * Persist this user's session (e.g. set cookies)
3986 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3988 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3989 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3991 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3993 if ( $this->mId
== 0 ) {
3997 $session = $this->getRequest()->getSession();
3998 if ( $request && $session->getRequest() !== $request ) {
3999 $session = $session->sessionWithRequest( $request );
4001 $delay = $session->delaySave();
4003 if ( !$session->getUser()->equals( $this ) ) {
4004 if ( !$session->canSetUser() ) {
4005 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4006 ->warning( __METHOD__
.
4007 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4011 $session->setUser( $this );
4014 $session->setRememberUser( $rememberMe );
4015 if ( $secure !== null ) {
4016 $session->setForceHTTPS( $secure );
4019 $session->persist();
4021 ScopedCallback
::consume( $delay );
4025 * Log this user out.
4027 public function logout() {
4028 // Avoid PHP 7.1 warning of passing $this by reference
4030 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4036 * Clear the user's session, and reset the instance cache.
4039 public function doLogout() {
4040 $session = $this->getRequest()->getSession();
4041 if ( !$session->canSetUser() ) {
4042 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4043 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4044 $error = 'immutable';
4045 } elseif ( !$session->getUser()->equals( $this ) ) {
4046 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4047 ->warning( __METHOD__
.
4048 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4050 // But we still may as well make this user object anon
4051 $this->clearInstanceCache( 'defaults' );
4052 $error = 'wronguser';
4054 $this->clearInstanceCache( 'defaults' );
4055 $delay = $session->delaySave();
4056 $session->unpersist(); // Clear cookies (T127436)
4057 $session->setLoggedOutTimestamp( time() );
4058 $session->setUser( new User
);
4059 $session->set( 'wsUserID', 0 ); // Other code expects this
4060 $session->resetAllTokens();
4061 ScopedCallback
::consume( $delay );
4064 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4065 'event' => 'logout',
4066 'successful' => $error === false,
4067 'status' => $error ?
: 'success',
4072 * Save this user's settings into the database.
4073 * @todo Only rarely do all these fields need to be set!
4075 public function saveSettings() {
4076 if ( wfReadOnly() ) {
4077 // @TODO: caller should deal with this instead!
4078 // This should really just be an exception.
4079 MWExceptionHandler
::logException( new DBExpectedError(
4081 "Could not update user with ID '{$this->mId}'; DB is read-only."
4087 if ( $this->mId
== 0 ) {
4091 // Get a new user_touched that is higher than the old one.
4092 // This will be used for a CAS check as a last-resort safety
4093 // check against race conditions and replica DB lag.
4094 $newTouched = $this->newTouchedTimestamp();
4096 $dbw = wfGetDB( DB_MASTER
);
4097 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
4098 global $wgActorTableSchemaMigrationStage;
4100 $dbw->update( 'user',
4102 'user_name' => $this->mName
,
4103 'user_real_name' => $this->mRealName
,
4104 'user_email' => $this->mEmail
,
4105 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4106 'user_touched' => $dbw->timestamp( $newTouched ),
4107 'user_token' => strval( $this->mToken
),
4108 'user_email_token' => $this->mEmailToken
,
4109 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4110 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4111 'user_id' => $this->mId
,
4115 if ( !$dbw->affectedRows() ) {
4116 // Maybe the problem was a missed cache update; clear it to be safe
4117 $this->clearSharedCache( 'refresh' );
4118 // User was changed in the meantime or loaded with stale data
4119 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4120 LoggerFactory
::getInstance( 'preferences' )->warning(
4121 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4122 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4124 throw new MWException( "CAS update failed on user_touched. " .
4125 "The version of the user to be saved is older than the current version."
4129 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4132 [ 'actor_name' => $this->mName
],
4133 [ 'actor_user' => $this->mId
],
4139 $this->mTouched
= $newTouched;
4140 $this->saveOptions();
4142 Hooks
::run( 'UserSaveSettings', [ $this ] );
4143 $this->clearSharedCache( 'changed' );
4144 $this->getUserPage()->purgeSquid();
4148 * If only this user's username is known, and it exists, return the user ID.
4150 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4153 public function idForName( $flags = 0 ) {
4154 $s = trim( $this->getName() );
4159 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4160 ?
wfGetDB( DB_MASTER
)
4161 : wfGetDB( DB_REPLICA
);
4163 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4164 ?
[ 'LOCK IN SHARE MODE' ]
4167 $id = $db->selectField( 'user',
4168 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4174 * Add a user to the database, return the user object
4176 * @param string $name Username to add
4177 * @param array $params Array of Strings Non-default parameters to save to
4178 * the database as user_* fields:
4179 * - email: The user's email address.
4180 * - email_authenticated: The email authentication timestamp.
4181 * - real_name: The user's real name.
4182 * - options: An associative array of non-default options.
4183 * - token: Random authentication token. Do not set.
4184 * - registration: Registration timestamp. Do not set.
4186 * @return User|null User object, or null if the username already exists.
4188 public static function createNew( $name, $params = [] ) {
4189 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4190 if ( isset( $params[$field] ) ) {
4191 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4192 unset( $params[$field] );
4198 $user->setToken(); // init token
4199 if ( isset( $params['options'] ) ) {
4200 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4201 unset( $params['options'] );
4203 $dbw = wfGetDB( DB_MASTER
);
4205 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4208 'user_name' => $name,
4209 'user_password' => $noPass,
4210 'user_newpassword' => $noPass,
4211 'user_email' => $user->mEmail
,
4212 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4213 'user_real_name' => $user->mRealName
,
4214 'user_token' => strval( $user->mToken
),
4215 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4216 'user_editcount' => 0,
4217 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4219 foreach ( $params as $name => $value ) {
4220 $fields["user_$name"] = $value;
4223 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4224 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4225 if ( $dbw->affectedRows() ) {
4226 $newUser = self
::newFromId( $dbw->insertId() );
4227 $newUser->mName
= $fields['user_name'];
4228 $newUser->updateActorId( $dbw );
4229 // Load the user from master to avoid replica lag
4230 $newUser->load( self
::READ_LATEST
);
4239 * Add this existing user object to the database. If the user already
4240 * exists, a fatal status object is returned, and the user object is
4241 * initialised with the data from the database.
4243 * Previously, this function generated a DB error due to a key conflict
4244 * if the user already existed. Many extension callers use this function
4245 * in code along the lines of:
4247 * $user = User::newFromName( $name );
4248 * if ( !$user->isLoggedIn() ) {
4249 * $user->addToDatabase();
4251 * // do something with $user...
4253 * However, this was vulnerable to a race condition (T18020). By
4254 * initialising the user object if the user exists, we aim to support this
4255 * calling sequence as far as possible.
4257 * Note that if the user exists, this function will acquire a write lock,
4258 * so it is still advisable to make the call conditional on isLoggedIn(),
4259 * and to commit the transaction after calling.
4261 * @throws MWException
4264 public function addToDatabase() {
4266 if ( !$this->mToken
) {
4267 $this->setToken(); // init token
4270 if ( !is_string( $this->mName
) ) {
4271 throw new RuntimeException( "User name field is not set." );
4274 $this->mTouched
= $this->newTouchedTimestamp();
4276 $dbw = wfGetDB( DB_MASTER
);
4277 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4278 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4279 $dbw->insert( 'user',
4281 'user_name' => $this->mName
,
4282 'user_password' => $noPass,
4283 'user_newpassword' => $noPass,
4284 'user_email' => $this->mEmail
,
4285 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4286 'user_real_name' => $this->mRealName
,
4287 'user_token' => strval( $this->mToken
),
4288 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4289 'user_editcount' => 0,
4290 'user_touched' => $dbw->timestamp( $this->mTouched
),
4294 if ( !$dbw->affectedRows() ) {
4295 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4296 $this->mId
= $dbw->selectField(
4299 [ 'user_name' => $this->mName
],
4301 [ 'LOCK IN SHARE MODE' ]
4304 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4308 throw new MWException( $fname . ": hit a key conflict attempting " .
4309 "to insert user '{$this->mName}' row, but it was not present in select!" );
4311 return Status
::newFatal( 'userexists' );
4313 $this->mId
= $dbw->insertId();
4314 self
::$idCacheByName[$this->mName
] = $this->mId
;
4315 $this->updateActorId( $dbw );
4317 return Status
::newGood();
4319 if ( !$status->isGood() ) {
4323 // Clear instance cache other than user table data and actor, which is already accurate
4324 $this->clearInstanceCache();
4326 $this->saveOptions();
4327 return Status
::newGood();
4331 * Update the actor ID after an insert
4332 * @param IDatabase $dbw Writable database handle
4334 private function updateActorId( IDatabase
$dbw ) {
4335 global $wgActorTableSchemaMigrationStage;
4337 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4340 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4343 $this->mActorId
= (int)$dbw->insertId();
4348 * If this user is logged-in and blocked,
4349 * block any IP address they've successfully logged in from.
4350 * @return bool A block was spread
4352 public function spreadAnyEditBlock() {
4353 if ( $this->isLoggedIn() && $this->getBlock() ) {
4354 return $this->spreadBlock();
4361 * If this (non-anonymous) user is blocked,
4362 * block the IP address they've successfully logged in from.
4363 * @return bool A block was spread
4365 protected function spreadBlock() {
4366 wfDebug( __METHOD__
. "()\n" );
4368 if ( $this->mId
== 0 ) {
4372 $userblock = Block
::newFromTarget( $this->getName() );
4373 if ( !$userblock ) {
4377 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4381 * Get whether the user is explicitly blocked from account creation.
4382 * @return bool|Block
4384 public function isBlockedFromCreateAccount() {
4385 $this->getBlockedStatus();
4386 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4387 return $this->mBlock
;
4390 # T15611: if the IP address the user is trying to create an account from is
4391 # blocked with createaccount disabled, prevent new account creation there even
4392 # when the user is logged in
4393 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4394 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4396 return $this->mBlockedFromCreateAccount
instanceof Block
4397 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4398 ?
$this->mBlockedFromCreateAccount
4403 * Get whether the user is blocked from using Special:Emailuser.
4406 public function isBlockedFromEmailuser() {
4407 $this->getBlockedStatus();
4408 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4412 * Get whether the user is blocked from using Special:Upload
4417 public function isBlockedFromUpload() {
4418 $this->getBlockedStatus();
4419 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4423 * Get whether the user is allowed to create an account.
4426 public function isAllowedToCreateAccount() {
4427 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4431 * Get this user's personal page title.
4433 * @return Title User's personal page title
4435 public function getUserPage() {
4436 return Title
::makeTitle( NS_USER
, $this->getName() );
4440 * Get this user's talk page title.
4442 * @return Title User's talk page title
4444 public function getTalkPage() {
4445 $title = $this->getUserPage();
4446 return $title->getTalkPage();
4450 * Determine whether the user is a newbie. Newbies are either
4451 * anonymous IPs, or the most recently created accounts.
4454 public function isNewbie() {
4455 return !$this->isAllowed( 'autoconfirmed' );
4459 * Check to see if the given clear-text password is one of the accepted passwords
4460 * @deprecated since 1.27, use AuthManager instead
4461 * @param string $password User password
4462 * @return bool True if the given password is correct, otherwise False
4464 public function checkPassword( $password ) {
4465 wfDeprecated( __METHOD__
, '1.27' );
4467 $manager = AuthManager
::singleton();
4468 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4469 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4471 'username' => $this->getName(),
4472 'password' => $password,
4475 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4476 switch ( $res->status
) {
4477 case AuthenticationResponse
::PASS
:
4479 case AuthenticationResponse
::FAIL
:
4480 // Hope it's not a PreAuthenticationProvider that failed...
4481 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4482 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4485 throw new BadMethodCallException(
4486 'AuthManager returned a response unsupported by ' . __METHOD__
4492 * Check if the given clear-text password matches the temporary password
4493 * sent by e-mail for password reset operations.
4495 * @deprecated since 1.27, use AuthManager instead
4496 * @param string $plaintext
4497 * @return bool True if matches, false otherwise
4499 public function checkTemporaryPassword( $plaintext ) {
4500 wfDeprecated( __METHOD__
, '1.27' );
4501 // Can't check the temporary password individually.
4502 return $this->checkPassword( $plaintext );
4506 * Initialize (if necessary) and return a session token value
4507 * which can be used in edit forms to show that the user's
4508 * login credentials aren't being hijacked with a foreign form
4512 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4513 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4514 * @return MediaWiki\Session\Token The new edit token
4516 public function getEditTokenObject( $salt = '', $request = null ) {
4517 if ( $this->isAnon() ) {
4518 return new LoggedOutEditToken();
4522 $request = $this->getRequest();
4524 return $request->getSession()->getToken( $salt );
4528 * Initialize (if necessary) and return a session token value
4529 * which can be used in edit forms to show that the user's
4530 * login credentials aren't being hijacked with a foreign form
4533 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4536 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4537 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4538 * @return string The new edit token
4540 public function getEditToken( $salt = '', $request = null ) {
4541 return $this->getEditTokenObject( $salt, $request )->toString();
4545 * Check given value against the token value stored in the session.
4546 * A match should confirm that the form was submitted from the
4547 * user's own login session, not a form submission from a third-party
4550 * @param string $val Input value to compare
4551 * @param string|array $salt Optional function-specific data for hashing
4552 * @param WebRequest|null $request Object to use or null to use $wgRequest
4553 * @param int|null $maxage Fail tokens older than this, in seconds
4554 * @return bool Whether the token matches
4556 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4557 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4561 * Check given value against the token value stored in the session,
4562 * ignoring the suffix.
4564 * @param string $val Input value to compare
4565 * @param string|array $salt Optional function-specific data for hashing
4566 * @param WebRequest|null $request Object to use or null to use $wgRequest
4567 * @param int|null $maxage Fail tokens older than this, in seconds
4568 * @return bool Whether the token matches
4570 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4571 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4572 return $this->matchEditToken( $val, $salt, $request, $maxage );
4576 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4577 * mail to the user's given address.
4579 * @param string $type Message to send, either "created", "changed" or "set"
4582 public function sendConfirmationMail( $type = 'created' ) {
4584 $expiration = null; // gets passed-by-ref and defined in next line.
4585 $token = $this->confirmationToken( $expiration );
4586 $url = $this->confirmationTokenUrl( $token );
4587 $invalidateURL = $this->invalidationTokenUrl( $token );
4588 $this->saveSettings();
4590 if ( $type == 'created' ||
$type === false ) {
4591 $message = 'confirmemail_body';
4593 } elseif ( $type === true ) {
4594 $message = 'confirmemail_body_changed';
4597 // Messages: confirmemail_body_changed, confirmemail_body_set
4598 $message = 'confirmemail_body_' . $type;
4602 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4603 'body' => wfMessage( $message,
4604 $this->getRequest()->getIP(),
4607 $wgLang->userTimeAndDate( $expiration, $this ),
4609 $wgLang->userDate( $expiration, $this ),
4610 $wgLang->userTime( $expiration, $this ) )->text(),
4616 'ip' => $this->getRequest()->getIP(),
4617 'confirmURL' => $url,
4618 'invalidateURL' => $invalidateURL,
4619 'expiration' => $expiration
4622 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4623 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4627 * Send an e-mail to this user's account. Does not check for
4628 * confirmed status or validity.
4630 * @param string $subject Message subject
4631 * @param string $body Message body
4632 * @param User|null $from Optional sending user; if unspecified, default
4633 * $wgPasswordSender will be used.
4634 * @param MailAddress|null $replyto Reply-To address
4637 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4638 global $wgPasswordSender;
4640 if ( $from instanceof User
) {
4641 $sender = MailAddress
::newFromUser( $from );
4643 $sender = new MailAddress( $wgPasswordSender,
4644 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4646 $to = MailAddress
::newFromUser( $this );
4648 return UserMailer
::send( $to, $sender, $subject, $body, [
4649 'replyTo' => $replyto,
4654 * Generate, store, and return a new e-mail confirmation code.
4655 * A hash (unsalted, since it's used as a key) is stored.
4657 * @note Call saveSettings() after calling this function to commit
4658 * this change to the database.
4660 * @param string &$expiration Accepts the expiration time
4661 * @return string New token
4663 protected function confirmationToken( &$expiration ) {
4664 global $wgUserEmailConfirmationTokenExpiry;
4666 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4667 $expiration = wfTimestamp( TS_MW
, $expires );
4669 $token = MWCryptRand
::generateHex( 32 );
4670 $hash = md5( $token );
4671 $this->mEmailToken
= $hash;
4672 $this->mEmailTokenExpires
= $expiration;
4677 * Return a URL the user can use to confirm their email address.
4678 * @param string $token Accepts the email confirmation token
4679 * @return string New token URL
4681 protected function confirmationTokenUrl( $token ) {
4682 return $this->getTokenUrl( 'ConfirmEmail', $token );
4686 * Return a URL the user can use to invalidate their email address.
4687 * @param string $token Accepts the email confirmation token
4688 * @return string New token URL
4690 protected function invalidationTokenUrl( $token ) {
4691 return $this->getTokenUrl( 'InvalidateEmail', $token );
4695 * Internal function to format the e-mail validation/invalidation URLs.
4696 * This uses a quickie hack to use the
4697 * hardcoded English names of the Special: pages, for ASCII safety.
4699 * @note Since these URLs get dropped directly into emails, using the
4700 * short English names avoids insanely long URL-encoded links, which
4701 * also sometimes can get corrupted in some browsers/mailers
4702 * (T8957 with Gmail and Internet Explorer).
4704 * @param string $page Special page
4705 * @param string $token
4706 * @return string Formatted URL
4708 protected function getTokenUrl( $page, $token ) {
4709 // Hack to bypass localization of 'Special:'
4710 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4711 return $title->getCanonicalURL();
4715 * Mark the e-mail address confirmed.
4717 * @note Call saveSettings() after calling this function to commit the change.
4721 public function confirmEmail() {
4722 // Check if it's already confirmed, so we don't touch the database
4723 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4724 if ( !$this->isEmailConfirmed() ) {
4725 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4726 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4732 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4733 * address if it was already confirmed.
4735 * @note Call saveSettings() after calling this function to commit the change.
4736 * @return bool Returns true
4738 public function invalidateEmail() {
4740 $this->mEmailToken
= null;
4741 $this->mEmailTokenExpires
= null;
4742 $this->setEmailAuthenticationTimestamp( null );
4744 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4749 * Set the e-mail authentication timestamp.
4750 * @param string $timestamp TS_MW timestamp
4752 public function setEmailAuthenticationTimestamp( $timestamp ) {
4754 $this->mEmailAuthenticated
= $timestamp;
4755 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4759 * Is this user allowed to send e-mails within limits of current
4760 * site configuration?
4763 public function canSendEmail() {
4764 global $wgEnableEmail, $wgEnableUserEmail;
4765 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4768 $canSend = $this->isEmailConfirmed();
4769 // Avoid PHP 7.1 warning of passing $this by reference
4771 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4776 * Is this user allowed to receive e-mails within limits of current
4777 * site configuration?
4780 public function canReceiveEmail() {
4781 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4785 * Is this user's e-mail address valid-looking and confirmed within
4786 * limits of the current site configuration?
4788 * @note If $wgEmailAuthentication is on, this may require the user to have
4789 * confirmed their address by returning a code or using a password
4790 * sent to the address from the wiki.
4794 public function isEmailConfirmed() {
4795 global $wgEmailAuthentication;
4797 // Avoid PHP 7.1 warning of passing $this by reference
4800 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4801 if ( $this->isAnon() ) {
4804 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4807 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4817 * Check whether there is an outstanding request for e-mail confirmation.
4820 public function isEmailConfirmationPending() {
4821 global $wgEmailAuthentication;
4822 return $wgEmailAuthentication &&
4823 !$this->isEmailConfirmed() &&
4824 $this->mEmailToken
&&
4825 $this->mEmailTokenExpires
> wfTimestamp();
4829 * Get the timestamp of account creation.
4831 * @return string|bool|null Timestamp of account creation, false for
4832 * non-existent/anonymous user accounts, or null if existing account
4833 * but information is not in database.
4835 public function getRegistration() {
4836 if ( $this->isAnon() ) {
4840 return $this->mRegistration
;
4844 * Get the timestamp of the first edit
4846 * @return string|bool Timestamp of first edit, or false for
4847 * non-existent/anonymous user accounts.
4849 public function getFirstEditTimestamp() {
4850 return $this->getEditTimestamp( true );
4854 * Get the timestamp of the latest edit
4857 * @return string|bool Timestamp of first edit, or false for
4858 * non-existent/anonymous user accounts.
4860 public function getLatestEditTimestamp() {
4861 return $this->getEditTimestamp( false );
4865 * Get the timestamp of the first or latest edit
4867 * @param bool $first True for the first edit, false for the latest one
4868 * @return string|bool Timestamp of first or latest edit, or false for
4869 * non-existent/anonymous user accounts.
4871 private function getEditTimestamp( $first ) {
4872 if ( $this->getId() == 0 ) {
4873 return false; // anons
4875 $dbr = wfGetDB( DB_REPLICA
);
4876 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4877 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4878 ?
'revactor_timestamp' : 'rev_timestamp';
4879 $sortOrder = $first ?
'ASC' : 'DESC';
4880 $time = $dbr->selectField(
4881 [ 'revision' ] +
$actorWhere['tables'],
4883 [ $actorWhere['conds'] ],
4885 [ 'ORDER BY' => "$tsField $sortOrder" ],
4886 $actorWhere['joins']
4889 return false; // no edits
4891 return wfTimestamp( TS_MW
, $time );
4895 * Get the permissions associated with a given list of groups
4897 * @param array $groups Array of Strings List of internal group names
4898 * @return array Array of Strings List of permission key names for given groups combined
4900 public static function getGroupPermissions( $groups ) {
4901 global $wgGroupPermissions, $wgRevokePermissions;
4903 // grant every granted permission first
4904 foreach ( $groups as $group ) {
4905 if ( isset( $wgGroupPermissions[$group] ) ) {
4906 $rights = array_merge( $rights,
4907 // array_filter removes empty items
4908 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4911 // now revoke the revoked permissions
4912 foreach ( $groups as $group ) {
4913 if ( isset( $wgRevokePermissions[$group] ) ) {
4914 $rights = array_diff( $rights,
4915 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4918 return array_unique( $rights );
4922 * Get all the groups who have a given permission
4924 * @param string $role Role to check
4925 * @return array Array of Strings List of internal group names with the given permission
4927 public static function getGroupsWithPermission( $role ) {
4928 global $wgGroupPermissions;
4929 $allowedGroups = [];
4930 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4931 if ( self
::groupHasPermission( $group, $role ) ) {
4932 $allowedGroups[] = $group;
4935 return $allowedGroups;
4939 * Check, if the given group has the given permission
4941 * If you're wanting to check whether all users have a permission, use
4942 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4946 * @param string $group Group to check
4947 * @param string $role Role to check
4950 public static function groupHasPermission( $group, $role ) {
4951 global $wgGroupPermissions, $wgRevokePermissions;
4952 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4953 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4957 * Check if all users may be assumed to have the given permission
4959 * We generally assume so if the right is granted to '*' and isn't revoked
4960 * on any group. It doesn't attempt to take grants or other extension
4961 * limitations on rights into account in the general case, though, as that
4962 * would require it to always return false and defeat the purpose.
4963 * Specifically, session-based rights restrictions (such as OAuth or bot
4964 * passwords) are applied based on the current session.
4967 * @param string $right Right to check
4970 public static function isEveryoneAllowed( $right ) {
4971 global $wgGroupPermissions, $wgRevokePermissions;
4974 // Use the cached results, except in unit tests which rely on
4975 // being able change the permission mid-request
4976 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4977 return $cache[$right];
4980 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4981 $cache[$right] = false;
4985 // If it's revoked anywhere, then everyone doesn't have it
4986 foreach ( $wgRevokePermissions as $rights ) {
4987 if ( isset( $rights[$right] ) && $rights[$right] ) {
4988 $cache[$right] = false;
4993 // Remove any rights that aren't allowed to the global-session user,
4994 // unless there are no sessions for this endpoint.
4995 if ( !defined( 'MW_NO_SESSION' ) ) {
4996 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4997 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4998 $cache[$right] = false;
5003 // Allow extensions to say false
5004 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5005 $cache[$right] = false;
5009 $cache[$right] = true;
5014 * Return the set of defined explicit groups.
5015 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5016 * are not included, as they are defined automatically, not in the database.
5017 * @return array Array of internal group names
5019 public static function getAllGroups() {
5020 global $wgGroupPermissions, $wgRevokePermissions;
5021 return array_values( array_diff(
5022 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5023 self
::getImplicitGroups()
5028 * Get a list of all available permissions.
5029 * @return string[] Array of permission names
5031 public static function getAllRights() {
5032 if ( self
::$mAllRights === false ) {
5033 global $wgAvailableRights;
5034 if ( count( $wgAvailableRights ) ) {
5035 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5037 self
::$mAllRights = self
::$mCoreRights;
5039 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5041 return self
::$mAllRights;
5045 * Get a list of implicit groups
5046 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
5048 * @return array Array of Strings Array of internal group names
5050 public static function getImplicitGroups() {
5051 global $wgImplicitGroups;
5052 return $wgImplicitGroups;
5056 * Returns an array of the groups that a particular group can add/remove.
5058 * @param string $group The group to check for whether it can add/remove
5059 * @return array Array( 'add' => array( addablegroups ),
5060 * 'remove' => array( removablegroups ),
5061 * 'add-self' => array( addablegroups to self),
5062 * 'remove-self' => array( removable groups from self) )
5064 public static function changeableByGroup( $group ) {
5065 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5074 if ( empty( $wgAddGroups[$group] ) ) {
5075 // Don't add anything to $groups
5076 } elseif ( $wgAddGroups[$group] === true ) {
5077 // You get everything
5078 $groups['add'] = self
::getAllGroups();
5079 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5080 $groups['add'] = $wgAddGroups[$group];
5083 // Same thing for remove
5084 if ( empty( $wgRemoveGroups[$group] ) ) {
5086 } elseif ( $wgRemoveGroups[$group] === true ) {
5087 $groups['remove'] = self
::getAllGroups();
5088 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5089 $groups['remove'] = $wgRemoveGroups[$group];
5092 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5093 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5094 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5095 if ( is_int( $key ) ) {
5096 $wgGroupsAddToSelf['user'][] = $value;
5101 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5102 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5103 if ( is_int( $key ) ) {
5104 $wgGroupsRemoveFromSelf['user'][] = $value;
5109 // Now figure out what groups the user can add to him/herself
5110 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5112 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5113 // No idea WHY this would be used, but it's there
5114 $groups['add-self'] = self
::getAllGroups();
5115 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5116 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5119 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5121 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5122 $groups['remove-self'] = self
::getAllGroups();
5123 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5124 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5131 * Returns an array of groups that this user can add and remove
5132 * @return array Array( 'add' => array( addablegroups ),
5133 * 'remove' => array( removablegroups ),
5134 * 'add-self' => array( addablegroups to self),
5135 * 'remove-self' => array( removable groups from self) )
5137 public function changeableGroups() {
5138 if ( $this->isAllowed( 'userrights' ) ) {
5139 // This group gives the right to modify everything (reverse-
5140 // compatibility with old "userrights lets you change
5142 // Using array_merge to make the groups reindexed
5143 $all = array_merge( self
::getAllGroups() );
5152 // Okay, it's not so simple, we will have to go through the arrays
5159 $addergroups = $this->getEffectiveGroups();
5161 foreach ( $addergroups as $addergroup ) {
5162 $groups = array_merge_recursive(
5163 $groups, $this->changeableByGroup( $addergroup )
5165 $groups['add'] = array_unique( $groups['add'] );
5166 $groups['remove'] = array_unique( $groups['remove'] );
5167 $groups['add-self'] = array_unique( $groups['add-self'] );
5168 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5174 * Schedule a deferred update to update the user's edit count
5176 public function incEditCount() {
5177 if ( $this->isAnon() ) {
5181 DeferredUpdates
::addUpdate(
5182 new UserEditCountUpdate( $this, 1 ),
5183 DeferredUpdates
::POSTSEND
5188 * This method should not be called outside User/UserEditCountUpdate
5192 public function setEditCountInternal( $count ) {
5193 $this->mEditCount
= $count;
5197 * Initialize user_editcount from data out of the revision table
5199 * This method should not be called outside User/UserEditCountUpdate
5201 * @return int Number of edits
5203 public function initEditCountInternal() {
5204 // Pull from a replica DB to be less cruel to servers
5205 // Accuracy isn't the point anyway here
5206 $dbr = wfGetDB( DB_REPLICA
);
5207 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5208 $count = (int)$dbr->selectField(
5209 [ 'revision' ] +
$actorWhere['tables'],
5211 [ $actorWhere['conds'] ],
5214 $actorWhere['joins']
5217 $dbw = wfGetDB( DB_MASTER
);
5220 [ 'user_editcount' => $count ],
5222 'user_id' => $this->getId(),
5223 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5232 * Get the description of a given right
5235 * @param string $right Right to query
5236 * @return string Localized description of the right
5238 public static function getRightDescription( $right ) {
5239 $key = "right-$right";
5240 $msg = wfMessage( $key );
5241 return $msg->isDisabled() ?
$right : $msg->text();
5245 * Get the name of a given grant
5248 * @param string $grant Grant to query
5249 * @return string Localized name of the grant
5251 public static function getGrantName( $grant ) {
5252 $key = "grant-$grant";
5253 $msg = wfMessage( $key );
5254 return $msg->isDisabled() ?
$grant : $msg->text();
5258 * Add a newuser log entry for this user.
5259 * Before 1.19 the return value was always true.
5261 * @deprecated since 1.27, AuthManager handles logging
5262 * @param string|bool $action Account creation type.
5263 * - String, one of the following values:
5264 * - 'create' for an anonymous user creating an account for himself.
5265 * This will force the action's performer to be the created user itself,
5266 * no matter the value of $wgUser
5267 * - 'create2' for a logged in user creating an account for someone else
5268 * - 'byemail' when the created user will receive its password by e-mail
5269 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5270 * - Boolean means whether the account was created by e-mail (deprecated):
5271 * - true will be converted to 'byemail'
5272 * - false will be converted to 'create' if this object is the same as
5273 * $wgUser and to 'create2' otherwise
5274 * @param string $reason User supplied reason
5277 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5278 return true; // disabled
5282 * Add an autocreate newuser log entry for this user
5283 * Used by things like CentralAuth and perhaps other authplugins.
5284 * Consider calling addNewUserLogEntry() directly instead.
5286 * @deprecated since 1.27, AuthManager handles logging
5289 public function addNewUserLogEntryAutoCreate() {
5290 $this->addNewUserLogEntry( 'autocreate' );
5296 * Load the user options either from cache, the database or an array
5298 * @param array|null $data Rows for the current user out of the user_properties table
5300 protected function loadOptions( $data = null ) {
5303 if ( $this->mOptionsLoaded
) {
5307 $this->mOptions
= self
::getDefaultOptions();
5309 if ( !$this->getId() ) {
5310 // For unlogged-in users, load language/variant options from request.
5311 // There's no need to do it for logged-in users: they can set preferences,
5312 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5313 // so don't override user's choice (especially when the user chooses site default).
5314 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5315 $this->mOptions
['variant'] = $variant;
5316 $this->mOptions
['language'] = $variant;
5317 $this->mOptionsLoaded
= true;
5321 // Maybe load from the object
5322 if ( !is_null( $this->mOptionOverrides
) ) {
5323 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5324 foreach ( $this->mOptionOverrides
as $key => $value ) {
5325 $this->mOptions
[$key] = $value;
5328 if ( !is_array( $data ) ) {
5329 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5330 // Load from database
5331 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5332 ?
wfGetDB( DB_MASTER
)
5333 : wfGetDB( DB_REPLICA
);
5335 $res = $dbr->select(
5337 [ 'up_property', 'up_value' ],
5338 [ 'up_user' => $this->getId() ],
5342 $this->mOptionOverrides
= [];
5344 foreach ( $res as $row ) {
5345 // Convert '0' to 0. PHP's boolean conversion considers them both
5346 // false, but e.g. JavaScript considers the former as true.
5347 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5348 // and convert all values here.
5349 if ( $row->up_value
=== '0' ) {
5352 $data[$row->up_property
] = $row->up_value
;
5356 foreach ( $data as $property => $value ) {
5357 $this->mOptionOverrides
[$property] = $value;
5358 $this->mOptions
[$property] = $value;
5362 // Replace deprecated language codes
5363 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5364 $this->mOptions
['language']
5367 $this->mOptionsLoaded
= true;
5369 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5373 * Saves the non-default options for this user, as previously set e.g. via
5374 * setOption(), in the database's "user_properties" (preferences) table.
5375 * Usually used via saveSettings().
5377 protected function saveOptions() {
5378 $this->loadOptions();
5380 // Not using getOptions(), to keep hidden preferences in database
5381 $saveOptions = $this->mOptions
;
5383 // Allow hooks to abort, for instance to save to a global profile.
5384 // Reset options to default state before saving.
5385 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5389 $userId = $this->getId();
5391 $insert_rows = []; // all the new preference rows
5392 foreach ( $saveOptions as $key => $value ) {
5393 // Don't bother storing default values
5394 $defaultOption = self
::getDefaultOption( $key );
5395 if ( ( $defaultOption === null && $value !== false && $value !== null )
5396 ||
$value != $defaultOption
5399 'up_user' => $userId,
5400 'up_property' => $key,
5401 'up_value' => $value,
5406 $dbw = wfGetDB( DB_MASTER
);
5408 $res = $dbw->select( 'user_properties',
5409 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5411 // Find prior rows that need to be removed or updated. These rows will
5412 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5414 foreach ( $res as $row ) {
5415 if ( !isset( $saveOptions[$row->up_property
] )
5416 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5418 $keysDelete[] = $row->up_property
;
5422 if ( count( $keysDelete ) ) {
5423 // Do the DELETE by PRIMARY KEY for prior rows.
5424 // In the past a very large portion of calls to this function are for setting
5425 // 'rememberpassword' for new accounts (a preference that has since been removed).
5426 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5427 // caused gap locks on [max user ID,+infinity) which caused high contention since
5428 // updates would pile up on each other as they are for higher (newer) user IDs.
5429 // It might not be necessary these days, but it shouldn't hurt either.
5430 $dbw->delete( 'user_properties',
5431 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5433 // Insert the new preference rows
5434 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5438 * Return the list of user fields that should be selected to create
5439 * a new user object.
5440 * @deprecated since 1.31, use self::getQueryInfo() instead.
5443 public static function selectFields() {
5444 wfDeprecated( __METHOD__
, '1.31' );
5452 'user_email_authenticated',
5454 'user_email_token_expires',
5455 'user_registration',
5461 * Return the tables, fields, and join conditions to be selected to create
5462 * a new user object.
5464 * @return array With three keys:
5465 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5466 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5467 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5469 public static function getQueryInfo() {
5470 global $wgActorTableSchemaMigrationStage;
5473 'tables' => [ 'user' ],
5481 'user_email_authenticated',
5483 'user_email_token_expires',
5484 'user_registration',
5490 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5491 // but it does little harm and might be needed for write callers loading a User.
5492 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5493 $ret['tables']['user_actor'] = 'actor';
5494 $ret['fields'][] = 'user_actor.actor_id';
5495 $ret['joins']['user_actor'] = [
5496 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5497 [ 'user_actor.actor_user = user_id' ]
5505 * Factory function for fatal permission-denied errors
5508 * @param string $permission User right required
5511 static function newFatalPermissionDeniedStatus( $permission ) {
5515 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5516 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5520 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5523 return Status
::newFatal( 'badaccess-group0' );
5527 * Get a new instance of this user that was loaded from the master via a locking read
5529 * Use this instead of the main context User when updating that user. This avoids races
5530 * where that user was loaded from a replica DB or even the master but without proper locks.
5532 * @return User|null Returns null if the user was not found in the DB
5535 public function getInstanceForUpdate() {
5536 if ( !$this->getId() ) {
5537 return null; // anon
5540 $user = self
::newFromId( $this->getId() );
5541 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5549 * Checks if two user objects point to the same user.
5551 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5552 * @param UserIdentity $user
5555 public function equals( UserIdentity
$user ) {
5556 // XXX it's not clear whether central ID providers are supposed to obey this
5557 return $this->getName() === $user->getName();
5561 * Checks if usertalk is allowed
5565 public function isAllowUsertalk() {
5566 return $this->mAllowUsertalk
;