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
;
32 use Wikimedia\ScopedCallback
;
33 use Wikimedia\Rdbms\Database
;
34 use Wikimedia\Rdbms\DBExpectedError
;
35 use Wikimedia\Rdbms\IDatabase
;
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
47 class User
implements IDBAccessObject
, UserIdentity
{
49 * @const int Number of characters in user_token field.
51 const TOKEN_LENGTH
= 32;
54 * @const string An invalid value for user_token
56 const INVALID_TOKEN
= '*** INVALID ***';
59 * Global constant made accessible as class constants so that autoloader
61 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
63 const EDIT_TOKEN_SUFFIX
= Token
::SUFFIX
;
66 * @const int Serialized record version.
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
79 const CHECK_USER_RIGHTS
= true;
84 const IGNORE_USER_RIGHTS
= false;
87 * Array of Strings List of member variables which are saved to the
88 * shared cache (memcached). Any operation which changes the
89 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
114 * Array of Strings Core rights.
115 * Each of these should have a corresponding message of the form
119 protected static $mCoreRights = [
167 'move-categorypages',
168 'move-rootuserpages',
172 'override-export-depth',
194 'userrights-interwiki',
202 * String Cached results of getAllRights()
204 protected static $mAllRights = false;
206 /** Cache variables */
219 /** @var string TS_MW timestamp from the DB */
221 /** @var string TS_MW timestamp from cache */
222 protected $mQuickTouched;
226 public $mEmailAuthenticated;
228 protected $mEmailToken;
230 protected $mEmailTokenExpires;
232 protected $mRegistration;
234 protected $mEditCount;
235 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
236 protected $mGroupMemberships;
238 protected $mOptionOverrides;
242 * Bool Whether the cache variables have been loaded.
245 public $mOptionsLoaded;
248 * Array with already loaded items or true if all items have been loaded.
250 protected $mLoadedItems = [];
254 * String Initialization data source if mLoadedItems!==true. May be one of:
255 * - 'defaults' anonymous user initialised from class defaults
256 * - 'name' initialise from mName
257 * - 'id' initialise from mId
258 * - 'actor' initialise from mActorId
259 * - 'session' log in from session if possible
261 * Use the User::newFrom*() family of functions to set this.
266 * Lazy-initialized variables, invalidated with clearInstanceCache
270 protected $mDatePreference;
278 protected $mBlockreason;
280 protected $mEffectiveGroups;
282 protected $mImplicitGroups;
284 protected $mFormerGroups;
286 protected $mGlobalBlock;
294 /** @var WebRequest */
301 protected $mAllowUsertalk;
304 private $mBlockedFromCreateAccount = false;
306 /** @var int User::READ_* constant bitfield used to load data */
307 protected $queryFlagsUsed = self
::READ_NORMAL
;
309 public static $idCacheByName = [];
312 * Lightweight constructor for an anonymous user.
313 * Use the User::newFrom* factory functions for other kinds of users.
317 * @see newFromActorId()
318 * @see newFromConfirmationCode()
319 * @see newFromSession()
322 public function __construct() {
323 $this->clearInstanceCache( 'defaults' );
329 public function __toString() {
330 return (string)$this->getName();
334 * Test if it's safe to load this User object.
336 * You should typically check this before using $wgUser or
337 * RequestContext::getUser in a method that might be called before the
338 * system has been fully initialized. If the object is unsafe, you should
339 * use an anonymous user:
341 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
347 public function isSafeToLoad() {
348 global $wgFullyInitialised;
350 // The user is safe to load if:
351 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
352 // * mLoadedItems === true (already loaded)
353 // * mFrom !== 'session' (sessions not involved at all)
355 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
356 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
360 * Load the user table data for this object from the source given by mFrom.
362 * @param int $flags User::READ_* constant bitfield
364 public function load( $flags = self
::READ_NORMAL
) {
365 global $wgFullyInitialised;
367 if ( $this->mLoadedItems
=== true ) {
371 // Set it now to avoid infinite recursion in accessors
372 $oldLoadedItems = $this->mLoadedItems
;
373 $this->mLoadedItems
= true;
374 $this->queryFlagsUsed
= $flags;
376 // If this is called too early, things are likely to break.
377 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
378 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
379 ->warning( 'User::loadFromSession called before the end of Setup.php', [
380 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
382 $this->loadDefaults();
383 $this->mLoadedItems
= $oldLoadedItems;
387 switch ( $this->mFrom
) {
389 $this->loadDefaults();
392 // Make sure this thread sees its own changes
393 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
394 if ( $lb->hasOrMadeRecentMasterChanges() ) {
395 $flags |
= self
::READ_LATEST
;
396 $this->queryFlagsUsed
= $flags;
399 $this->mId
= self
::idFromName( $this->mName
, $flags );
401 // Nonexistent user placeholder object
402 $this->loadDefaults( $this->mName
);
404 $this->loadFromId( $flags );
408 // Make sure this thread sees its own changes, if the ID isn't 0
409 if ( $this->mId
!= 0 ) {
410 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
411 if ( $lb->hasOrMadeRecentMasterChanges() ) {
412 $flags |
= self
::READ_LATEST
;
413 $this->queryFlagsUsed
= $flags;
417 $this->loadFromId( $flags );
420 // Make sure this thread sees its own changes
421 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
422 if ( $lb->hasOrMadeRecentMasterChanges() ) {
423 $flags |
= self
::READ_LATEST
;
424 $this->queryFlagsUsed
= $flags;
427 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
428 $row = wfGetDB( $index )->selectRow(
430 [ 'actor_user', 'actor_name' ],
431 [ 'actor_id' => $this->mActorId
],
438 $this->loadDefaults();
439 } elseif ( $row->actor_user
) {
440 $this->mId
= $row->actor_user
;
441 $this->loadFromId( $flags );
443 $this->loadDefaults( $row->actor_name
);
447 if ( !$this->loadFromSession() ) {
448 // Loading from session failed. Load defaults.
449 $this->loadDefaults();
451 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
454 throw new UnexpectedValueException(
455 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
460 * Load user table data, given mId has already been set.
461 * @param int $flags User::READ_* constant bitfield
462 * @return bool False if the ID does not exist, true otherwise
464 public function loadFromId( $flags = self
::READ_NORMAL
) {
465 if ( $this->mId
== 0 ) {
466 // Anonymous users are not in the database (don't need cache)
467 $this->loadDefaults();
471 // Try cache (unless this needs data from the master DB).
472 // NOTE: if this thread called saveSettings(), the cache was cleared.
473 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
475 if ( !$this->loadFromDatabase( $flags ) ) {
476 // Can't load from ID
480 $this->loadFromCache();
483 $this->mLoadedItems
= true;
484 $this->queryFlagsUsed
= $flags;
491 * @param string $wikiId
494 public static function purge( $wikiId, $userId ) {
495 $cache = ObjectCache
::getMainWANInstance();
496 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
497 $cache->delete( $key );
502 * @param WANObjectCache $cache
505 protected function getCacheKey( WANObjectCache
$cache ) {
506 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
510 * @param WANObjectCache $cache
514 public function getMutableCacheKeys( WANObjectCache
$cache ) {
515 $id = $this->getId();
517 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
521 * Load user data from shared cache, given mId has already been set.
526 protected function loadFromCache() {
527 $cache = ObjectCache
::getMainWANInstance();
528 $data = $cache->getWithSetCallback(
529 $this->getCacheKey( $cache ),
531 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
532 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
533 wfDebug( "User: cache miss for user {$this->mId}\n" );
535 $this->loadFromDatabase( self
::READ_NORMAL
);
537 $this->loadOptions();
540 foreach ( self
::$mCacheVars as $name ) {
541 $data[$name] = $this->$name;
544 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
546 // if a user group membership is about to expire, the cache needs to
547 // expire at that time (T163691)
548 foreach ( $this->mGroupMemberships
as $ugm ) {
549 if ( $ugm->getExpiry() ) {
550 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
551 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
552 $ttl = $secondsUntilExpiry;
559 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
562 // Restore from cache
563 foreach ( self
::$mCacheVars as $name ) {
564 $this->$name = $data[$name];
570 /** @name newFrom*() static factory methods */
574 * Static factory method for creation from username.
576 * This is slightly less efficient than newFromId(), so use newFromId() if
577 * you have both an ID and a name handy.
579 * @param string $name Username, validated by Title::newFromText()
580 * @param string|bool $validate Validate username. Takes the same parameters as
581 * User::getCanonicalName(), except that true is accepted as an alias
582 * for 'valid', for BC.
584 * @return User|bool User object, or false if the username is invalid
585 * (e.g. if it contains illegal characters or is an IP address). If the
586 * username is not present in the database, the result will be a user object
587 * with a name, zero user ID and default settings.
589 public static function newFromName( $name, $validate = 'valid' ) {
590 if ( $validate === true ) {
593 $name = self
::getCanonicalName( $name, $validate );
594 if ( $name === false ) {
597 // Create unloaded user object
601 $u->setItemLoaded( 'name' );
607 * Static factory method for creation from a given user ID.
609 * @param int $id Valid user ID
610 * @return User The corresponding User object
612 public static function newFromId( $id ) {
616 $u->setItemLoaded( 'id' );
621 * Static factory method for creation from a given actor ID.
624 * @param int $id Valid actor ID
625 * @return User The corresponding User object
627 public static function newFromActorId( $id ) {
628 global $wgActorTableSchemaMigrationStage;
630 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
631 throw new BadMethodCallException(
632 'Cannot use ' . __METHOD__
. ' when $wgActorTableSchemaMigrationStage is MIGRATION_OLD'
639 $u->setItemLoaded( 'actor' );
644 * Returns a User object corresponding to the given UserIdentity.
648 * @param UserIdentity $identity
652 public static function newFromIdentity( UserIdentity
$identity ) {
653 if ( $identity instanceof User
) {
657 return self
::newFromAnyId(
658 $identity->getId() === 0 ?
null : $identity->getId(),
659 $identity->getName() === '' ?
null : $identity->getName(),
660 $identity->getActorId() === 0 ?
null : $identity->getActorId()
665 * Static factory method for creation from an ID, name, and/or actor ID
667 * This does not check that the ID, name, and actor ID all correspond to
671 * @param int|null $userId User ID, if known
672 * @param string|null $userName User name, if known
673 * @param int|null $actorId Actor ID, if known
676 public static function newFromAnyId( $userId, $userName, $actorId ) {
677 global $wgActorTableSchemaMigrationStage;
680 $user->mFrom
= 'defaults';
682 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
&& $actorId !== null ) {
683 $user->mActorId
= (int)$actorId;
684 if ( $user->mActorId
!== 0 ) {
685 $user->mFrom
= 'actor';
687 $user->setItemLoaded( 'actor' );
690 if ( $userName !== null && $userName !== '' ) {
691 $user->mName
= $userName;
692 $user->mFrom
= 'name';
693 $user->setItemLoaded( 'name' );
696 if ( $userId !== null ) {
697 $user->mId
= (int)$userId;
698 if ( $user->mId
!== 0 ) {
701 $user->setItemLoaded( 'id' );
704 if ( $user->mFrom
=== 'defaults' ) {
705 throw new InvalidArgumentException(
706 'Cannot create a user with no name, no ID, and no actor ID'
714 * Factory method to fetch whichever user has a given email confirmation code.
715 * This code is generated when an account is created or its e-mail address
718 * If the code is invalid or has expired, returns NULL.
720 * @param string $code Confirmation code
721 * @param int $flags User::READ_* bitfield
724 public static function newFromConfirmationCode( $code, $flags = 0 ) {
725 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
726 ?
wfGetDB( DB_MASTER
)
727 : wfGetDB( DB_REPLICA
);
729 $id = $db->selectField(
733 'user_email_token' => md5( $code ),
734 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
738 return $id ? self
::newFromId( $id ) : null;
742 * Create a new user object using data from session. If the login
743 * credentials are invalid, the result is an anonymous user.
745 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
748 public static function newFromSession( WebRequest
$request = null ) {
750 $user->mFrom
= 'session';
751 $user->mRequest
= $request;
756 * Create a new user object from a user row.
757 * The row should have the following fields from the user table in it:
758 * - either user_name or user_id to load further data if needed (or both)
760 * - all other fields (email, etc.)
761 * It is useless to provide the remaining fields if either user_id,
762 * user_name and user_real_name are not provided because the whole row
763 * will be loaded once more from the database when accessing them.
765 * @param stdClass $row A row from the user table
766 * @param array|null $data Further data to load into the object
767 * (see User::loadFromRow for valid keys)
770 public static function newFromRow( $row, $data = null ) {
772 $user->loadFromRow( $row, $data );
777 * Static factory method for creation of a "system" user from username.
779 * A "system" user is an account that's used to attribute logged actions
780 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
781 * might include the 'Maintenance script' or 'Conversion script' accounts
782 * used by various scripts in the maintenance/ directory or accounts such
783 * as 'MediaWiki message delivery' used by the MassMessage extension.
785 * This can optionally create the user if it doesn't exist, and "steal" the
786 * account if it does exist.
788 * "Stealing" an existing user is intended to make it impossible for normal
789 * authentication processes to use the account, effectively disabling the
790 * account for normal use:
791 * - Email is invalidated, to prevent account recovery by emailing a
792 * temporary password and to disassociate the account from the existing
794 * - The token is set to a magic invalid value, to kill existing sessions
795 * and to prevent $this->setToken() calls from resetting the token to a
797 * - SessionManager is instructed to prevent new sessions for the user, to
798 * do things like deauthorizing OAuth consumers.
799 * - AuthManager is instructed to revoke access, to invalidate or remove
800 * passwords and other credentials.
802 * @param string $name Username
803 * @param array $options Options are:
804 * - validate: As for User::getCanonicalName(), default 'valid'
805 * - create: Whether to create the user if it doesn't already exist, default true
806 * - steal: Whether to "disable" the account for normal use if it already
807 * exists, default false
811 public static function newSystemUser( $name, $options = [] ) {
813 'validate' => 'valid',
818 $name = self
::getCanonicalName( $name, $options['validate'] );
819 if ( $name === false ) {
823 $dbr = wfGetDB( DB_REPLICA
);
824 $userQuery = self
::getQueryInfo();
825 $row = $dbr->selectRow(
826 $userQuery['tables'],
827 $userQuery['fields'],
828 [ 'user_name' => $name ],
834 // Try the master database...
835 $dbw = wfGetDB( DB_MASTER
);
836 $row = $dbw->selectRow(
837 $userQuery['tables'],
838 $userQuery['fields'],
839 [ 'user_name' => $name ],
847 // No user. Create it?
848 return $options['create']
849 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
853 $user = self
::newFromRow( $row );
855 // A user is considered to exist as a non-system user if it can
856 // authenticate, or has an email set, or has a non-invalid token.
857 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
858 AuthManager
::singleton()->userCanAuthenticate( $name )
860 // User exists. Steal it?
861 if ( !$options['steal'] ) {
865 AuthManager
::singleton()->revokeAccessForUser( $name );
867 $user->invalidateEmail();
868 $user->mToken
= self
::INVALID_TOKEN
;
869 $user->saveSettings();
870 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
879 * Get the username corresponding to a given user ID
880 * @param int $id User ID
881 * @return string|bool The corresponding username
883 public static function whoIs( $id ) {
884 return UserCache
::singleton()->getProp( $id, 'name' );
888 * Get the real name of a user given their user ID
890 * @param int $id User ID
891 * @return string|bool The corresponding user's real name
893 public static function whoIsReal( $id ) {
894 return UserCache
::singleton()->getProp( $id, 'real_name' );
898 * Get database id given a user name
899 * @param string $name Username
900 * @param int $flags User::READ_* constant bitfield
901 * @return int|null The corresponding user's ID, or null if user is nonexistent
903 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
904 $nt = Title
::makeTitleSafe( NS_USER
, $name );
905 if ( is_null( $nt ) ) {
910 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
911 return self
::$idCacheByName[$name];
914 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
915 $db = wfGetDB( $index );
920 [ 'user_name' => $nt->getText() ],
925 if ( $s === false ) {
928 $result = $s->user_id
;
931 self
::$idCacheByName[$name] = $result;
933 if ( count( self
::$idCacheByName ) > 1000 ) {
934 self
::$idCacheByName = [];
941 * Reset the cache used in idFromName(). For use in tests.
943 public static function resetIdByNameCache() {
944 self
::$idCacheByName = [];
948 * Does the string match an anonymous IP address?
950 * This function exists for username validation, in order to reject
951 * usernames which are similar in form to IP addresses. Strings such
952 * as 300.300.300.300 will return true because it looks like an IP
953 * address, despite not being strictly valid.
955 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
956 * address because the usemod software would "cloak" anonymous IP
957 * addresses like this, if we allowed accounts like this to be created
958 * new users could get the old edits of these anonymous users.
960 * @param string $name Name to match
963 public static function isIP( $name ) {
964 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
965 || IP
::isIPv6( $name );
969 * Is the user an IP range?
974 public function isIPRange() {
975 return IP
::isValidRange( $this->mName
);
979 * Is the input a valid username?
981 * Checks if the input is a valid username, we don't want an empty string,
982 * an IP address, anything that contains slashes (would mess up subpages),
983 * is longer than the maximum allowed username size or doesn't begin with
986 * @param string $name Name to match
989 public static function isValidUserName( $name ) {
990 global $wgMaxNameChars;
993 || self
::isIP( $name )
994 ||
strpos( $name, '/' ) !== false
995 ||
strlen( $name ) > $wgMaxNameChars
996 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
1001 // Ensure that the name can't be misresolved as a different title,
1002 // such as with extra namespace keys at the start.
1003 $parsed = Title
::newFromText( $name );
1004 if ( is_null( $parsed )
1005 ||
$parsed->getNamespace()
1006 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1010 // Check an additional blacklist of troublemaker characters.
1011 // Should these be merged into the title char list?
1012 $unicodeBlacklist = '/[' .
1013 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1014 '\x{00a0}' . # non-breaking space
1015 '\x{2000}-\x{200f}' . # various whitespace
1016 '\x{2028}-\x{202f}' . # breaks and control chars
1017 '\x{3000}' . # ideographic space
1018 '\x{e000}-\x{f8ff}' . # private use
1020 if ( preg_match( $unicodeBlacklist, $name ) ) {
1028 * Usernames which fail to pass this function will be blocked
1029 * from user login and new account registrations, but may be used
1030 * internally by batch processes.
1032 * If an account already exists in this form, login will be blocked
1033 * by a failure to pass this function.
1035 * @param string $name Name to match
1038 public static function isUsableName( $name ) {
1039 global $wgReservedUsernames;
1040 // Must be a valid username, obviously ;)
1041 if ( !self
::isValidUserName( $name ) ) {
1045 static $reservedUsernames = false;
1046 if ( !$reservedUsernames ) {
1047 $reservedUsernames = $wgReservedUsernames;
1048 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1051 // Certain names may be reserved for batch processes.
1052 foreach ( $reservedUsernames as $reserved ) {
1053 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1054 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1056 if ( $reserved == $name ) {
1064 * Return the users who are members of the given group(s). In case of multiple groups,
1065 * users who are members of at least one of them are returned.
1067 * @param string|array $groups A single group name or an array of group names
1068 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1069 * records; larger values are ignored.
1070 * @param int|null $after ID the user to start after
1071 * @return UserArrayFromResult
1073 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1074 if ( $groups === [] ) {
1075 return UserArrayFromResult
::newFromIDs( [] );
1078 $groups = array_unique( (array)$groups );
1079 $limit = min( 5000, $limit );
1081 $conds = [ 'ug_group' => $groups ];
1082 if ( $after !== null ) {
1083 $conds[] = 'ug_user > ' . (int)$after;
1086 $dbr = wfGetDB( DB_REPLICA
);
1087 $ids = $dbr->selectFieldValues(
1094 'ORDER BY' => 'ug_user',
1098 return UserArray
::newFromIDs( $ids );
1102 * Usernames which fail to pass this function will be blocked
1103 * from new account registrations, but may be used internally
1104 * either by batch processes or by user accounts which have
1105 * already been created.
1107 * Additional blacklisting may be added here rather than in
1108 * isValidUserName() to avoid disrupting existing accounts.
1110 * @param string $name String to match
1113 public static function isCreatableName( $name ) {
1114 global $wgInvalidUsernameCharacters;
1116 // Ensure that the username isn't longer than 235 bytes, so that
1117 // (at least for the builtin skins) user javascript and css files
1118 // will work. (T25080)
1119 if ( strlen( $name ) > 235 ) {
1120 wfDebugLog( 'username', __METHOD__
.
1121 ": '$name' invalid due to length" );
1125 // Preg yells if you try to give it an empty string
1126 if ( $wgInvalidUsernameCharacters !== '' ) {
1127 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
1128 wfDebugLog( 'username', __METHOD__
.
1129 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1134 return self
::isUsableName( $name );
1138 * Is the input a valid password for this user?
1140 * @param string $password Desired password
1143 public function isValidPassword( $password ) {
1144 // simple boolean wrapper for getPasswordValidity
1145 return $this->getPasswordValidity( $password ) === true;
1149 * Given unvalidated password input, return error message on failure.
1151 * @param string $password Desired password
1152 * @return bool|string|array True on success, string or array of error message on failure
1154 public function getPasswordValidity( $password ) {
1155 $result = $this->checkPasswordValidity( $password );
1156 if ( $result->isGood() ) {
1160 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
1161 $messages[] = $error['message'];
1163 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
1164 $messages[] = $warning['message'];
1166 if ( count( $messages ) === 1 ) {
1167 return $messages[0];
1174 * Check if this is a valid password for this user
1176 * Create a Status object based on the password's validity.
1177 * The Status should be set to fatal if the user should not
1178 * be allowed to log in, and should have any errors that
1179 * would block changing the password.
1181 * If the return value of this is not OK, the password
1182 * should not be checked. If the return value is not Good,
1183 * the password can be checked, but the user should not be
1184 * able to set their password to this.
1186 * @param string $password Desired password
1190 public function checkPasswordValidity( $password ) {
1191 global $wgPasswordPolicy;
1193 $upp = new UserPasswordPolicy(
1194 $wgPasswordPolicy['policies'],
1195 $wgPasswordPolicy['checks']
1198 $status = Status
::newGood();
1199 $result = false; // init $result to false for the internal checks
1201 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1202 $status->error( $result );
1206 if ( $result === false ) {
1207 $status->merge( $upp->checkUserPassword( $this, $password ) );
1209 } elseif ( $result === true ) {
1212 $status->error( $result );
1213 return $status; // the isValidPassword hook set a string $result and returned true
1218 * Given unvalidated user input, return a canonical username, or false if
1219 * the username is invalid.
1220 * @param string $name User input
1221 * @param string|bool $validate Type of validation to use:
1222 * - false No validation
1223 * - 'valid' Valid for batch processes
1224 * - 'usable' Valid for batch processes and login
1225 * - 'creatable' Valid for batch processes, login and account creation
1227 * @throws InvalidArgumentException
1228 * @return bool|string
1230 public static function getCanonicalName( $name, $validate = 'valid' ) {
1231 // Force usernames to capital
1232 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1234 # Reject names containing '#'; these will be cleaned up
1235 # with title normalisation, but then it's too late to
1237 if ( strpos( $name, '#' ) !== false ) {
1241 // Clean up name according to title rules,
1242 // but only when validation is requested (T14654)
1243 $t = ( $validate !== false ) ?
1244 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1245 // Check for invalid titles
1246 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1250 // Reject various classes of invalid names
1251 $name = AuthManager
::callLegacyAuthPlugin(
1252 'getCanonicalName', [ $t->getText() ], $t->getText()
1255 switch ( $validate ) {
1259 if ( !self
::isValidUserName( $name ) ) {
1264 if ( !self
::isUsableName( $name ) ) {
1269 if ( !self
::isCreatableName( $name ) ) {
1274 throw new InvalidArgumentException(
1275 'Invalid parameter value for $validate in ' . __METHOD__
);
1281 * Return a random password.
1283 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1284 * @return string New random password
1286 public static function randomPassword() {
1287 global $wgMinimalPasswordLength;
1288 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1292 * Set cached properties to default.
1294 * @note This no longer clears uncached lazy-initialised properties;
1295 * the constructor does that instead.
1297 * @param string|bool $name
1299 public function loadDefaults( $name = false ) {
1301 $this->mName
= $name;
1302 $this->mActorId
= null;
1303 $this->mRealName
= '';
1305 $this->mOptionOverrides
= null;
1306 $this->mOptionsLoaded
= false;
1308 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1309 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1310 if ( $loggedOut !== 0 ) {
1311 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1313 $this->mTouched
= '1'; # Allow any pages to be cached
1316 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1317 $this->mEmailAuthenticated
= null;
1318 $this->mEmailToken
= '';
1319 $this->mEmailTokenExpires
= null;
1320 $this->mRegistration
= wfTimestamp( TS_MW
);
1321 $this->mGroupMemberships
= [];
1323 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1327 * Return whether an item has been loaded.
1329 * @param string $item Item to check. Current possibilities:
1333 * @param string $all 'all' to check if the whole object has been loaded
1334 * or any other string to check if only the item is available (e.g.
1338 public function isItemLoaded( $item, $all = 'all' ) {
1339 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1340 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1344 * Set that an item has been loaded
1346 * @param string $item
1348 protected function setItemLoaded( $item ) {
1349 if ( is_array( $this->mLoadedItems
) ) {
1350 $this->mLoadedItems
[$item] = true;
1355 * Load user data from the session.
1357 * @return bool True if the user is logged in, false otherwise.
1359 private function loadFromSession() {
1362 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1363 if ( $result !== null ) {
1367 // MediaWiki\Session\Session already did the necessary authentication of the user
1368 // returned here, so just use it if applicable.
1369 $session = $this->getRequest()->getSession();
1370 $user = $session->getUser();
1371 if ( $user->isLoggedIn() ) {
1372 $this->loadFromUserObject( $user );
1373 if ( $user->isBlocked() ) {
1374 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1375 // every session load, because an autoblocked editor might not edit again from the same
1376 // IP address after being blocked.
1377 $this->trackBlockWithCookie();
1380 // Other code expects these to be set in the session, so set them.
1381 $session->set( 'wsUserID', $this->getId() );
1382 $session->set( 'wsUserName', $this->getName() );
1383 $session->set( 'wsToken', $this->getToken() );
1392 * Set the 'BlockID' cookie depending on block type and user authentication status.
1394 public function trackBlockWithCookie() {
1395 $block = $this->getBlock();
1396 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null ) {
1397 $config = RequestContext
::getMain()->getConfig();
1398 $shouldSetCookie = false;
1400 if ( $this->isAnon() && $config->get( 'CookieSetOnIpBlock' ) ) {
1401 // If user is logged-out, set a cookie to track the Block
1402 $shouldSetCookie = in_array( $block->getType(), [
1403 Block
::TYPE_IP
, Block
::TYPE_RANGE
1405 if ( $shouldSetCookie ) {
1406 $block->setCookie( $this->getRequest()->response() );
1408 // temporary measure the use of cookies on ip blocks
1409 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1410 $stats->increment( 'block.ipblock.setCookie.success' );
1412 } elseif ( $this->isLoggedIn() && $config->get( 'CookieSetOnAutoblock' ) ) {
1413 $shouldSetCookie = $block->getType() === Block
::TYPE_USER
&& $block->isAutoblocking();
1414 if ( $shouldSetCookie ) {
1415 $block->setCookie( $this->getRequest()->response() );
1422 * Load user and user_group data from the database.
1423 * $this->mId must be set, this is how the user is identified.
1425 * @param int $flags User::READ_* constant bitfield
1426 * @return bool True if the user exists, false if the user is anonymous
1428 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1430 $this->mId
= intval( $this->mId
);
1432 if ( !$this->mId
) {
1433 // Anonymous users are not in the database
1434 $this->loadDefaults();
1438 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1439 $db = wfGetDB( $index );
1441 $userQuery = self
::getQueryInfo();
1442 $s = $db->selectRow(
1443 $userQuery['tables'],
1444 $userQuery['fields'],
1445 [ 'user_id' => $this->mId
],
1451 $this->queryFlagsUsed
= $flags;
1452 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1454 if ( $s !== false ) {
1455 // Initialise user table data
1456 $this->loadFromRow( $s );
1457 $this->mGroupMemberships
= null; // deferred
1458 $this->getEditCount(); // revalidation for nulls
1463 $this->loadDefaults();
1469 * Initialize this object from a row from the user table.
1471 * @param stdClass $row Row from the user table to load.
1472 * @param array|null $data Further user data to load into the object
1474 * user_groups Array of arrays or stdClass result rows out of the user_groups
1475 * table. Previously you were supposed to pass an array of strings
1476 * here, but we also need expiry info nowadays, so an array of
1477 * strings is ignored.
1478 * user_properties Array with properties out of the user_properties table
1480 protected function loadFromRow( $row, $data = null ) {
1481 global $wgActorTableSchemaMigrationStage;
1483 if ( !is_object( $row ) ) {
1484 throw new InvalidArgumentException( '$row must be an object' );
1489 $this->mGroupMemberships
= null; // deferred
1491 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
1492 if ( isset( $row->actor_id
) ) {
1493 $this->mActorId
= (int)$row->actor_id
;
1494 if ( $this->mActorId
!== 0 ) {
1495 $this->mFrom
= 'actor';
1497 $this->setItemLoaded( 'actor' );
1503 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1504 $this->mName
= $row->user_name
;
1505 $this->mFrom
= 'name';
1506 $this->setItemLoaded( 'name' );
1511 if ( isset( $row->user_real_name
) ) {
1512 $this->mRealName
= $row->user_real_name
;
1513 $this->setItemLoaded( 'realname' );
1518 if ( isset( $row->user_id
) ) {
1519 $this->mId
= intval( $row->user_id
);
1520 if ( $this->mId
!== 0 ) {
1521 $this->mFrom
= 'id';
1523 $this->setItemLoaded( 'id' );
1528 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1529 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1532 if ( isset( $row->user_editcount
) ) {
1533 $this->mEditCount
= $row->user_editcount
;
1538 if ( isset( $row->user_touched
) ) {
1539 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1544 if ( isset( $row->user_token
) ) {
1545 // The definition for the column is binary(32), so trim the NULs
1546 // that appends. The previous definition was char(32), so trim
1548 $this->mToken
= rtrim( $row->user_token
, " \0" );
1549 if ( $this->mToken
=== '' ) {
1550 $this->mToken
= null;
1556 if ( isset( $row->user_email
) ) {
1557 $this->mEmail
= $row->user_email
;
1558 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1559 $this->mEmailToken
= $row->user_email_token
;
1560 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1561 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1567 $this->mLoadedItems
= true;
1570 if ( is_array( $data ) ) {
1571 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1572 if ( !count( $data['user_groups'] ) ) {
1573 $this->mGroupMemberships
= [];
1575 $firstGroup = reset( $data['user_groups'] );
1576 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1577 $this->mGroupMemberships
= [];
1578 foreach ( $data['user_groups'] as $row ) {
1579 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1580 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1585 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1586 $this->loadOptions( $data['user_properties'] );
1592 * Load the data for this user object from another user object.
1596 protected function loadFromUserObject( $user ) {
1598 foreach ( self
::$mCacheVars as $var ) {
1599 $this->$var = $user->$var;
1604 * Load the groups from the database if they aren't already loaded.
1606 private function loadGroups() {
1607 if ( is_null( $this->mGroupMemberships
) ) {
1608 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1609 ?
wfGetDB( DB_MASTER
)
1610 : wfGetDB( DB_REPLICA
);
1611 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1617 * Add the user to the group if he/she meets given criteria.
1619 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1620 * possible to remove manually via Special:UserRights. In such case it
1621 * will not be re-added automatically. The user will also not lose the
1622 * group if they no longer meet the criteria.
1624 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1626 * @return array Array of groups the user has been promoted to.
1628 * @see $wgAutopromoteOnce
1630 public function addAutopromoteOnceGroups( $event ) {
1631 global $wgAutopromoteOnceLogInRC;
1633 if ( wfReadOnly() ||
!$this->getId() ) {
1637 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1638 if ( !count( $toPromote ) ) {
1642 if ( !$this->checkAndSetTouched() ) {
1643 return []; // raced out (bug T48834)
1646 $oldGroups = $this->getGroups(); // previous groups
1647 $oldUGMs = $this->getGroupMemberships();
1648 foreach ( $toPromote as $group ) {
1649 $this->addGroup( $group );
1651 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1652 $newUGMs = $this->getGroupMemberships();
1654 // update groups in external authentication database
1655 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1656 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1658 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1659 $logEntry->setPerformer( $this );
1660 $logEntry->setTarget( $this->getUserPage() );
1661 $logEntry->setParameters( [
1662 '4::oldgroups' => $oldGroups,
1663 '5::newgroups' => $newGroups,
1665 $logid = $logEntry->insert();
1666 if ( $wgAutopromoteOnceLogInRC ) {
1667 $logEntry->publish( $logid );
1674 * Builds update conditions. Additional conditions may be added to $conditions to
1675 * protected against race conditions using a compare-and-set (CAS) mechanism
1676 * based on comparing $this->mTouched with the user_touched field.
1678 * @param Database $db
1679 * @param array $conditions WHERE conditions for use with Database::update
1680 * @return array WHERE conditions for use with Database::update
1682 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1683 if ( $this->mTouched
) {
1684 // CAS check: only update if the row wasn't changed sicne it was loaded.
1685 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1692 * Bump user_touched if it didn't change since this object was loaded
1694 * On success, the mTouched field is updated.
1695 * The user serialization cache is always cleared.
1697 * @return bool Whether user_touched was actually updated
1700 protected function checkAndSetTouched() {
1703 if ( !$this->mId
) {
1704 return false; // anon
1707 // Get a new user_touched that is higher than the old one
1708 $newTouched = $this->newTouchedTimestamp();
1710 $dbw = wfGetDB( DB_MASTER
);
1711 $dbw->update( 'user',
1712 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1713 $this->makeUpdateConditions( $dbw, [
1714 'user_id' => $this->mId
,
1718 $success = ( $dbw->affectedRows() > 0 );
1721 $this->mTouched
= $newTouched;
1722 $this->clearSharedCache();
1724 // Clears on failure too since that is desired if the cache is stale
1725 $this->clearSharedCache( 'refresh' );
1732 * Clear various cached data stored in this object. The cache of the user table
1733 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1735 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1736 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1738 public function clearInstanceCache( $reloadFrom = false ) {
1739 $this->mNewtalk
= -1;
1740 $this->mDatePreference
= null;
1741 $this->mBlockedby
= -1; # Unset
1742 $this->mHash
= false;
1743 $this->mRights
= null;
1744 $this->mEffectiveGroups
= null;
1745 $this->mImplicitGroups
= null;
1746 $this->mGroupMemberships
= null;
1747 $this->mOptions
= null;
1748 $this->mOptionsLoaded
= false;
1749 $this->mEditCount
= null;
1751 if ( $reloadFrom ) {
1752 $this->mLoadedItems
= [];
1753 $this->mFrom
= $reloadFrom;
1758 * Combine the language default options with any site-specific options
1759 * and add the default language variants.
1761 * @return array Array of String options
1763 public static function getDefaultOptions() {
1764 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1766 static $defOpt = null;
1767 static $defOptLang = null;
1769 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1770 if ( $defOpt !== null && $defOptLang === $contLang->getCode() ) {
1771 // The content language does not change (and should not change) mid-request, but the
1772 // unit tests change it anyway, and expect this method to return values relevant to the
1773 // current content language.
1777 $defOpt = $wgDefaultUserOptions;
1778 // Default language setting
1779 $defOptLang = $contLang->getCode();
1780 $defOpt['language'] = $defOptLang;
1781 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1782 if ( $langCode === $contLang->getCode() ) {
1783 $defOpt['variant'] = $langCode;
1785 $defOpt["variant-$langCode"] = $langCode;
1789 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1790 // since extensions may change the set of searchable namespaces depending
1791 // on user groups/permissions.
1792 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1793 $defOpt['searchNs' . $nsnum] = (bool)$val;
1795 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1797 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1803 * Get a given default option value.
1805 * @param string $opt Name of option to retrieve
1806 * @return string Default option value
1808 public static function getDefaultOption( $opt ) {
1809 $defOpts = self
::getDefaultOptions();
1810 if ( isset( $defOpts[$opt] ) ) {
1811 return $defOpts[$opt];
1818 * Get blocking information
1819 * @param bool $bFromSlave Whether to check the replica DB first.
1820 * To improve performance, non-critical checks are done against replica DBs.
1821 * Check when actually saving should be done against master.
1823 private function getBlockedStatus( $bFromSlave = true ) {
1824 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff, $wgSoftBlockRanges;
1826 if ( -1 != $this->mBlockedby
) {
1830 wfDebug( __METHOD__
. ": checking...\n" );
1832 // Initialize data...
1833 // Otherwise something ends up stomping on $this->mBlockedby when
1834 // things get lazy-loaded later, causing false positive block hits
1835 // due to -1 !== 0. Probably session-related... Nothing should be
1836 // overwriting mBlockedby, surely?
1839 # We only need to worry about passing the IP address to the Block generator if the
1840 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1841 # know which IP address they're actually coming from
1843 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1844 // $wgUser->getName() only works after the end of Setup.php. Until
1845 // then, assume it's a logged-out user.
1846 $globalUserName = $wgUser->isSafeToLoad()
1847 ?
$wgUser->getName()
1848 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1849 if ( $this->getName() === $globalUserName ) {
1850 $ip = $this->getRequest()->getIP();
1855 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1858 if ( !$block instanceof Block
) {
1859 $block = $this->getBlockFromCookieValue( $this->getRequest()->getCookie( 'BlockID' ) );
1863 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1865 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1866 $block = new Block( [
1867 'byText' => wfMessage( 'proxyblocker' )->text(),
1868 'reason' => wfMessage( 'proxyblockreason' )->plain(),
1870 'systemBlock' => 'proxy',
1872 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1873 $block = new Block( [
1874 'byText' => wfMessage( 'sorbs' )->text(),
1875 'reason' => wfMessage( 'sorbsreason' )->plain(),
1877 'systemBlock' => 'dnsbl',
1882 // (T25343) Apply IP blocks to the contents of XFF headers, if enabled
1883 if ( !$block instanceof Block
1884 && $wgApplyIpBlocksToXff
1886 && !in_array( $ip, $wgProxyWhitelist )
1888 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1889 $xff = array_map( 'trim', explode( ',', $xff ) );
1890 $xff = array_diff( $xff, [ $ip ] );
1891 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1892 $block = Block
::chooseBlock( $xffblocks, $xff );
1893 if ( $block instanceof Block
) {
1894 # Mangle the reason to alert the user that the block
1895 # originated from matching the X-Forwarded-For header.
1896 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->plain();
1900 if ( !$block instanceof Block
1903 && IP
::isInRanges( $ip, $wgSoftBlockRanges )
1905 $block = new Block( [
1907 'byText' => 'MediaWiki default',
1908 'reason' => wfMessage( 'softblockrangesreason', $ip )->plain(),
1910 'systemBlock' => 'wgSoftBlockRanges',
1914 if ( $block instanceof Block
) {
1915 wfDebug( __METHOD__
. ": Found block.\n" );
1916 $this->mBlock
= $block;
1917 $this->mBlockedby
= $block->getByName();
1918 $this->mBlockreason
= $block->mReason
;
1919 $this->mHideName
= $block->mHideName
;
1920 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1922 $this->mBlock
= null;
1923 $this->mBlockedby
= '';
1924 $this->mBlockreason
= '';
1925 $this->mHideName
= 0;
1926 $this->mAllowUsertalk
= false;
1929 // Avoid PHP 7.1 warning of passing $this by reference
1932 Hooks
::run( 'GetBlockedStatus', [ &$user ] );
1936 * Try to load a Block from an ID given in a cookie value.
1937 * @param string|null $blockCookieVal The cookie value to check.
1938 * @return Block|bool The Block object, or false if none could be loaded.
1940 protected function getBlockFromCookieValue( $blockCookieVal ) {
1941 // Make sure there's something to check. The cookie value must start with a number.
1942 if ( strlen( $blockCookieVal ) < 1 ||
!is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1945 // Load the Block from the ID in the cookie.
1946 $blockCookieId = Block
::getIdFromCookieValue( $blockCookieVal );
1947 if ( $blockCookieId !== null ) {
1948 // An ID was found in the cookie.
1949 $tmpBlock = Block
::newFromID( $blockCookieId );
1950 if ( $tmpBlock instanceof Block
) {
1951 $config = RequestContext
::getMain()->getConfig();
1953 switch ( $tmpBlock->getType() ) {
1954 case Block
::TYPE_USER
:
1955 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1956 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1958 case Block
::TYPE_IP
:
1959 case Block
::TYPE_RANGE
:
1960 // If block is type IP or IP range, load only if user is not logged in (T152462)
1961 $blockIsValid = !$tmpBlock->isExpired() && !$this->isLoggedIn();
1962 $useBlockCookie = ( $config->get( 'CookieSetOnIpBlock' ) === true );
1965 $blockIsValid = false;
1966 $useBlockCookie = false;
1969 if ( $blockIsValid && $useBlockCookie ) {
1973 // If the block is not valid, remove the cookie.
1974 Block
::clearCookie( $this->getRequest()->response() );
1977 // If the block doesn't exist, remove the cookie.
1978 Block
::clearCookie( $this->getRequest()->response() );
1985 * Whether the given IP is in a DNS blacklist.
1987 * @param string $ip IP to check
1988 * @param bool $checkWhitelist Whether to check the whitelist first
1989 * @return bool True if blacklisted.
1991 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1992 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1994 if ( !$wgEnableDnsBlacklist ) {
1998 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
2002 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
2006 * Whether the given IP is in a given DNS blacklist.
2008 * @param string $ip IP to check
2009 * @param string|array $bases Array of Strings: URL of the DNS blacklist
2010 * @return bool True if blacklisted.
2012 public function inDnsBlacklist( $ip, $bases ) {
2014 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
2015 if ( IP
::isIPv4( $ip ) ) {
2016 // Reverse IP, T23255
2017 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
2019 foreach ( (array)$bases as $base ) {
2021 // If we have an access key, use that too (ProjectHoneypot, etc.)
2023 if ( is_array( $base ) ) {
2024 if ( count( $base ) >= 2 ) {
2025 // Access key is 1, base URL is 0
2026 $host = "{$base[1]}.$ipReversed.{$base[0]}";
2028 $host = "$ipReversed.{$base[0]}";
2030 $basename = $base[0];
2032 $host = "$ipReversed.$base";
2036 $ipList = gethostbynamel( $host );
2039 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2043 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
2052 * Check if an IP address is in the local proxy list
2058 public static function isLocallyBlockedProxy( $ip ) {
2059 global $wgProxyList;
2061 if ( !$wgProxyList ) {
2065 if ( !is_array( $wgProxyList ) ) {
2066 // Load values from the specified file
2067 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
2070 $resultProxyList = [];
2071 $deprecatedIPEntries = [];
2073 // backward compatibility: move all ip addresses in keys to values
2074 foreach ( $wgProxyList as $key => $value ) {
2075 $keyIsIP = IP
::isIPAddress( $key );
2076 $valueIsIP = IP
::isIPAddress( $value );
2077 if ( $keyIsIP && !$valueIsIP ) {
2078 $deprecatedIPEntries[] = $key;
2079 $resultProxyList[] = $key;
2080 } elseif ( $keyIsIP && $valueIsIP ) {
2081 $deprecatedIPEntries[] = $key;
2082 $resultProxyList[] = $key;
2083 $resultProxyList[] = $value;
2085 $resultProxyList[] = $value;
2089 if ( $deprecatedIPEntries ) {
2091 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2092 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
2095 $proxyListIPSet = new IPSet( $resultProxyList );
2096 return $proxyListIPSet->match( $ip );
2100 * Is this user subject to rate limiting?
2102 * @return bool True if rate limited
2104 public function isPingLimitable() {
2105 global $wgRateLimitsExcludedIPs;
2106 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
2107 // No other good way currently to disable rate limits
2108 // for specific IPs. :P
2109 // But this is a crappy hack and should die.
2112 return !$this->isAllowed( 'noratelimit' );
2116 * Primitive rate limits: enforce maximum actions per time period
2117 * to put a brake on flooding.
2119 * The method generates both a generic profiling point and a per action one
2120 * (suffix being "-$action".
2122 * @note When using a shared cache like memcached, IP-address
2123 * last-hit counters will be shared across wikis.
2125 * @param string $action Action to enforce; 'edit' if unspecified
2126 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
2127 * @return bool True if a rate limiter was tripped
2129 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
2130 // Avoid PHP 7.1 warning of passing $this by reference
2132 // Call the 'PingLimiter' hook
2134 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
2138 global $wgRateLimits;
2139 if ( !isset( $wgRateLimits[$action] ) ) {
2143 $limits = array_merge(
2144 [ '&can-bypass' => true ],
2145 $wgRateLimits[$action]
2148 // Some groups shouldn't trigger the ping limiter, ever
2149 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2154 $id = $this->getId();
2156 $isNewbie = $this->isNewbie();
2157 $cache = ObjectCache
::getLocalClusterInstance();
2161 if ( isset( $limits['anon'] ) ) {
2162 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2165 // limits for logged-in users
2166 if ( isset( $limits['user'] ) ) {
2167 $userLimit = $limits['user'];
2171 // limits for anons and for newbie logged-in users
2174 if ( isset( $limits['ip'] ) ) {
2175 $ip = $this->getRequest()->getIP();
2176 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2178 // subnet-based limits
2179 if ( isset( $limits['subnet'] ) ) {
2180 $ip = $this->getRequest()->getIP();
2181 $subnet = IP
::getSubnet( $ip );
2182 if ( $subnet !== false ) {
2183 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2188 // Check for group-specific permissions
2189 // If more than one group applies, use the group with the highest limit ratio (max/period)
2190 foreach ( $this->getGroups() as $group ) {
2191 if ( isset( $limits[$group] ) ) {
2192 if ( $userLimit === false
2193 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2195 $userLimit = $limits[$group];
2200 // limits for newbie logged-in users (override all the normal user limits)
2201 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2202 $userLimit = $limits['newbie'];
2205 // Set the user limit key
2206 if ( $userLimit !== false ) {
2207 list( $max, $period ) = $userLimit;
2208 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2209 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2212 // ip-based limits for all ping-limitable users
2213 if ( isset( $limits['ip-all'] ) ) {
2214 $ip = $this->getRequest()->getIP();
2215 // ignore if user limit is more permissive
2216 if ( $isNewbie ||
$userLimit === false
2217 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2218 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2222 // subnet-based limits for all ping-limitable users
2223 if ( isset( $limits['subnet-all'] ) ) {
2224 $ip = $this->getRequest()->getIP();
2225 $subnet = IP
::getSubnet( $ip );
2226 if ( $subnet !== false ) {
2227 // ignore if user limit is more permissive
2228 if ( $isNewbie ||
$userLimit === false
2229 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2230 > $userLimit[0] / $userLimit[1] ) {
2231 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2237 foreach ( $keys as $key => $limit ) {
2238 list( $max, $period ) = $limit;
2239 $summary = "(limit $max in {$period}s)";
2240 $count = $cache->get( $key );
2243 if ( $count >= $max ) {
2244 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2245 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2248 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2251 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2252 if ( $incrBy > 0 ) {
2253 $cache->add( $key, 0, intval( $period ) ); // first ping
2256 if ( $incrBy > 0 ) {
2257 $cache->incr( $key, $incrBy );
2265 * Check if user is blocked
2267 * @param bool $bFromSlave Whether to check the replica DB instead of
2268 * the master. Hacked from false due to horrible probs on site.
2269 * @return bool True if blocked, false otherwise
2271 public function isBlocked( $bFromSlave = true ) {
2272 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
2276 * Get the block affecting the user, or null if the user is not blocked
2278 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2279 * @return Block|null
2281 public function getBlock( $bFromSlave = true ) {
2282 $this->getBlockedStatus( $bFromSlave );
2283 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
2287 * Check if user is blocked from editing a particular article
2289 * @param Title $title Title to check
2290 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2293 public function isBlockedFrom( $title, $bFromSlave = false ) {
2294 global $wgBlockAllowsUTEdit;
2296 $blocked = $this->isBlocked( $bFromSlave );
2297 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
2298 // If a user's name is suppressed, they cannot make edits anywhere
2299 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
2300 && $title->getNamespace() == NS_USER_TALK
) {
2302 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
2305 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2311 * If user is blocked, return the name of the user who placed the block
2312 * @return string Name of blocker
2314 public function blockedBy() {
2315 $this->getBlockedStatus();
2316 return $this->mBlockedby
;
2320 * If user is blocked, return the specified reason for the block
2321 * @return string Blocking reason
2323 public function blockedFor() {
2324 $this->getBlockedStatus();
2325 return $this->mBlockreason
;
2329 * If user is blocked, return the ID for the block
2330 * @return int Block ID
2332 public function getBlockId() {
2333 $this->getBlockedStatus();
2334 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2338 * Check if user is blocked on all wikis.
2339 * Do not use for actual edit permission checks!
2340 * This is intended for quick UI checks.
2342 * @param string $ip IP address, uses current client if none given
2343 * @return bool True if blocked, false otherwise
2345 public function isBlockedGlobally( $ip = '' ) {
2346 return $this->getGlobalBlock( $ip ) instanceof Block
;
2350 * Check if user is blocked on all wikis.
2351 * Do not use for actual edit permission checks!
2352 * This is intended for quick UI checks.
2354 * @param string $ip IP address, uses current client if none given
2355 * @return Block|null Block object if blocked, null otherwise
2356 * @throws FatalError
2357 * @throws MWException
2359 public function getGlobalBlock( $ip = '' ) {
2360 if ( $this->mGlobalBlock
!== null ) {
2361 return $this->mGlobalBlock ?
: null;
2363 // User is already an IP?
2364 if ( IP
::isIPAddress( $this->getName() ) ) {
2365 $ip = $this->getName();
2367 $ip = $this->getRequest()->getIP();
2369 // Avoid PHP 7.1 warning of passing $this by reference
2373 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2375 if ( $blocked && $block === null ) {
2376 // back-compat: UserIsBlockedGlobally didn't have $block param first
2377 $block = new Block( [
2379 'systemBlock' => 'global-block'
2383 $this->mGlobalBlock
= $blocked ?
$block : false;
2384 return $this->mGlobalBlock ?
: null;
2388 * Check if user account is locked
2390 * @return bool True if locked, false otherwise
2392 public function isLocked() {
2393 if ( $this->mLocked
!== null ) {
2394 return $this->mLocked
;
2396 // Avoid PHP 7.1 warning of passing $this by reference
2398 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2399 $this->mLocked
= $authUser && $authUser->isLocked();
2400 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2401 return $this->mLocked
;
2405 * Check if user account is hidden
2407 * @return bool True if hidden, false otherwise
2409 public function isHidden() {
2410 if ( $this->mHideName
!== null ) {
2411 return $this->mHideName
;
2413 $this->getBlockedStatus();
2414 if ( !$this->mHideName
) {
2415 // Avoid PHP 7.1 warning of passing $this by reference
2417 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$user ], null );
2418 $this->mHideName
= $authUser && $authUser->isHidden();
2419 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2421 return $this->mHideName
;
2425 * Get the user's ID.
2426 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2428 public function getId() {
2429 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2430 // Special case, we know the user is anonymous
2432 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2433 // Don't load if this was initialized from an ID
2437 return (int)$this->mId
;
2441 * Set the user and reload all fields according to a given ID
2442 * @param int $v User ID to reload
2444 public function setId( $v ) {
2446 $this->clearInstanceCache( 'id' );
2450 * Get the user name, or the IP of an anonymous user
2451 * @return string User's name or IP address
2453 public function getName() {
2454 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2455 // Special case optimisation
2456 return $this->mName
;
2459 if ( $this->mName
=== false ) {
2461 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2463 return $this->mName
;
2468 * Set the user name.
2470 * This does not reload fields from the database according to the given
2471 * name. Rather, it is used to create a temporary "nonexistent user" for
2472 * later addition to the database. It can also be used to set the IP
2473 * address for an anonymous user to something other than the current
2476 * @note User::newFromName() has roughly the same function, when the named user
2478 * @param string $str New user name to set
2480 public function setName( $str ) {
2482 $this->mName
= $str;
2486 * Get the user's actor ID.
2488 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2489 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2491 public function getActorId( IDatabase
$dbw = null ) {
2492 global $wgActorTableSchemaMigrationStage;
2494 if ( $wgActorTableSchemaMigrationStage <= MIGRATION_OLD
) {
2498 if ( !$this->isItemLoaded( 'actor' ) ) {
2502 // Currently $this->mActorId might be null if $this was loaded from a
2503 // cache entry that was written when $wgActorTableSchemaMigrationStage
2504 // was MIGRATION_OLD. Once that is no longer a possibility (i.e. when
2505 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2506 // has been removed), that condition may be removed.
2507 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2509 'actor_user' => $this->getId() ?
: null,
2510 'actor_name' => (string)$this->getName(),
2513 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2514 throw new CannotCreateActorException(
2515 'Cannot create an actor for a usable name that is not an existing user'
2518 if ( $q['actor_name'] === '' ) {
2519 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2521 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2522 if ( $dbw->affectedRows() ) {
2523 $this->mActorId
= (int)$dbw->insertId();
2526 list( , $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2527 $this->mActorId
= (int)$dbw->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2528 if ( !$this->mActorId
) {
2529 throw new CannotCreateActorException(
2530 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2534 $this->invalidateCache();
2536 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2537 $db = wfGetDB( $index );
2538 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2540 $this->setItemLoaded( 'actor' );
2543 return (int)$this->mActorId
;
2547 * Get the user's name escaped by underscores.
2548 * @return string Username escaped by underscores.
2550 public function getTitleKey() {
2551 return str_replace( ' ', '_', $this->getName() );
2555 * Check if the user has new messages.
2556 * @return bool True if the user has new messages
2558 public function getNewtalk() {
2561 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2562 if ( $this->mNewtalk
=== -1 ) {
2563 $this->mNewtalk
= false; # reset talk page status
2565 // Check memcached separately for anons, who have no
2566 // entire User object stored in there.
2567 if ( !$this->mId
) {
2568 global $wgDisableAnonTalk;
2569 if ( $wgDisableAnonTalk ) {
2570 // Anon newtalk disabled by configuration.
2571 $this->mNewtalk
= false;
2573 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2576 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2580 return (bool)$this->mNewtalk
;
2584 * Return the data needed to construct links for new talk page message
2585 * alerts. If there are new messages, this will return an associative array
2586 * with the following data:
2587 * wiki: The database name of the wiki
2588 * link: Root-relative link to the user's talk page
2589 * rev: The last talk page revision that the user has seen or null. This
2590 * is useful for building diff links.
2591 * If there are no new messages, it returns an empty array.
2592 * @note This function was designed to accomodate multiple talk pages, but
2593 * currently only returns a single link and revision.
2596 public function getNewMessageLinks() {
2597 // Avoid PHP 7.1 warning of passing $this by reference
2600 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2602 } elseif ( !$this->getNewtalk() ) {
2605 $utp = $this->getTalkPage();
2606 $dbr = wfGetDB( DB_REPLICA
);
2607 // Get the "last viewed rev" timestamp from the oldest message notification
2608 $timestamp = $dbr->selectField( 'user_newtalk',
2609 'MIN(user_last_timestamp)',
2610 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2612 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2613 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2617 * Get the revision ID for the last talk page revision viewed by the talk
2619 * @return int|null Revision ID or null
2621 public function getNewMessageRevisionId() {
2622 $newMessageRevisionId = null;
2623 $newMessageLinks = $this->getNewMessageLinks();
2624 if ( $newMessageLinks ) {
2625 // Note: getNewMessageLinks() never returns more than a single link
2626 // and it is always for the same wiki, but we double-check here in
2627 // case that changes some time in the future.
2628 if ( count( $newMessageLinks ) === 1
2629 && $newMessageLinks[0]['wiki'] === wfWikiID()
2630 && $newMessageLinks[0]['rev']
2632 /** @var Revision $newMessageRevision */
2633 $newMessageRevision = $newMessageLinks[0]['rev'];
2634 $newMessageRevisionId = $newMessageRevision->getId();
2637 return $newMessageRevisionId;
2641 * Internal uncached check for new messages
2644 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2645 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2646 * @return bool True if the user has new messages
2648 protected function checkNewtalk( $field, $id ) {
2649 $dbr = wfGetDB( DB_REPLICA
);
2651 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2653 return $ok !== false;
2657 * Add or update the new messages flag
2658 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2659 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2660 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2661 * @return bool True if successful, false otherwise
2663 protected function updateNewtalk( $field, $id, $curRev = null ) {
2664 // Get timestamp of the talk page revision prior to the current one
2665 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2666 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2667 // Mark the user as having new messages since this revision
2668 $dbw = wfGetDB( DB_MASTER
);
2669 $dbw->insert( 'user_newtalk',
2670 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2673 if ( $dbw->affectedRows() ) {
2674 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2677 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2683 * Clear the new messages flag for the given user
2684 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2685 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2686 * @return bool True if successful, false otherwise
2688 protected function deleteNewtalk( $field, $id ) {
2689 $dbw = wfGetDB( DB_MASTER
);
2690 $dbw->delete( 'user_newtalk',
2693 if ( $dbw->affectedRows() ) {
2694 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2697 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2703 * Update the 'You have new messages!' status.
2704 * @param bool $val Whether the user has new messages
2705 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2706 * page. Ignored if null or !$val.
2708 public function setNewtalk( $val, $curRev = null ) {
2709 if ( wfReadOnly() ) {
2714 $this->mNewtalk
= $val;
2716 if ( $this->isAnon() ) {
2718 $id = $this->getName();
2721 $id = $this->getId();
2725 $changed = $this->updateNewtalk( $field, $id, $curRev );
2727 $changed = $this->deleteNewtalk( $field, $id );
2731 $this->invalidateCache();
2736 * Generate a current or new-future timestamp to be stored in the
2737 * user_touched field when we update things.
2738 * @return string Timestamp in TS_MW format
2740 private function newTouchedTimestamp() {
2741 global $wgClockSkewFudge;
2743 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2744 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2745 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2752 * Clear user data from memcached
2754 * Use after applying updates to the database; caller's
2755 * responsibility to update user_touched if appropriate.
2757 * Called implicitly from invalidateCache() and saveSettings().
2759 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2761 public function clearSharedCache( $mode = 'changed' ) {
2762 if ( !$this->getId() ) {
2766 $cache = ObjectCache
::getMainWANInstance();
2767 $key = $this->getCacheKey( $cache );
2768 if ( $mode === 'refresh' ) {
2769 $cache->delete( $key, 1 );
2771 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2772 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2773 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2774 function () use ( $cache, $key ) {
2775 $cache->delete( $key );
2780 $cache->delete( $key );
2786 * Immediately touch the user data cache for this account
2788 * Calls touch() and removes account data from memcached
2790 public function invalidateCache() {
2792 $this->clearSharedCache();
2796 * Update the "touched" timestamp for the user
2798 * This is useful on various login/logout events when making sure that
2799 * a browser or proxy that has multiple tenants does not suffer cache
2800 * pollution where the new user sees the old users content. The value
2801 * of getTouched() is checked when determining 304 vs 200 responses.
2802 * Unlike invalidateCache(), this preserves the User object cache and
2803 * avoids database writes.
2807 public function touch() {
2808 $id = $this->getId();
2810 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2811 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2812 $cache->touchCheckKey( $key );
2813 $this->mQuickTouched
= null;
2818 * Validate the cache for this account.
2819 * @param string $timestamp A timestamp in TS_MW format
2822 public function validateCache( $timestamp ) {
2823 return ( $timestamp >= $this->getTouched() );
2827 * Get the user touched timestamp
2829 * Use this value only to validate caches via inequalities
2830 * such as in the case of HTTP If-Modified-Since response logic
2832 * @return string TS_MW Timestamp
2834 public function getTouched() {
2838 if ( $this->mQuickTouched
=== null ) {
2839 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2840 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2842 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2845 return max( $this->mTouched
, $this->mQuickTouched
);
2848 return $this->mTouched
;
2852 * Get the user_touched timestamp field (time of last DB updates)
2853 * @return string TS_MW Timestamp
2856 public function getDBTouched() {
2859 return $this->mTouched
;
2863 * Set the password and reset the random token.
2864 * Calls through to authentication plugin if necessary;
2865 * will have no effect if the auth plugin refuses to
2866 * pass the change through or if the legal password
2869 * As a special case, setting the password to null
2870 * wipes it, so the account cannot be logged in until
2871 * a new password is set, for instance via e-mail.
2873 * @deprecated since 1.27, use AuthManager instead
2874 * @param string $str New password to set
2875 * @throws PasswordError On failure
2878 public function setPassword( $str ) {
2879 wfDeprecated( __METHOD__
, '1.27' );
2880 return $this->setPasswordInternal( $str );
2884 * Set the password and reset the random token unconditionally.
2886 * @deprecated since 1.27, use AuthManager instead
2887 * @param string|null $str New password to set or null to set an invalid
2888 * password hash meaning that the user will not be able to log in
2889 * through the web interface.
2891 public function setInternalPassword( $str ) {
2892 wfDeprecated( __METHOD__
, '1.27' );
2893 $this->setPasswordInternal( $str );
2897 * Actually set the password and such
2898 * @since 1.27 cannot set a password for a user not in the database
2899 * @param string|null $str New password to set or null to set an invalid
2900 * password hash meaning that the user will not be able to log in
2901 * through the web interface.
2902 * @return bool Success
2904 private function setPasswordInternal( $str ) {
2905 $manager = AuthManager
::singleton();
2907 // If the user doesn't exist yet, fail
2908 if ( !$manager->userExists( $this->getName() ) ) {
2909 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2912 $status = $this->changeAuthenticationData( [
2913 'username' => $this->getName(),
2917 if ( !$status->isGood() ) {
2918 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2919 ->info( __METHOD__
. ': Password change rejected: '
2920 . $status->getWikiText( null, null, 'en' ) );
2924 $this->setOption( 'watchlisttoken', false );
2925 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2931 * Changes credentials of the user.
2933 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2934 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2935 * e.g. when no provider handled the change.
2937 * @param array $data A set of authentication data in fieldname => value format. This is the
2938 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2942 public function changeAuthenticationData( array $data ) {
2943 $manager = AuthManager
::singleton();
2944 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2945 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2947 $status = Status
::newGood( 'ignored' );
2948 foreach ( $reqs as $req ) {
2949 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2951 if ( $status->getValue() === 'ignored' ) {
2952 $status->warning( 'authenticationdatachange-ignored' );
2955 if ( $status->isGood() ) {
2956 foreach ( $reqs as $req ) {
2957 $manager->changeAuthenticationData( $req );
2964 * Get the user's current token.
2965 * @param bool $forceCreation Force the generation of a new token if the
2966 * user doesn't have one (default=true for backwards compatibility).
2967 * @return string|null Token
2969 public function getToken( $forceCreation = true ) {
2970 global $wgAuthenticationTokenVersion;
2973 if ( !$this->mToken
&& $forceCreation ) {
2977 if ( !$this->mToken
) {
2978 // The user doesn't have a token, return null to indicate that.
2980 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2981 // We return a random value here so existing token checks are very
2983 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2984 } elseif ( $wgAuthenticationTokenVersion === null ) {
2985 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2986 return $this->mToken
;
2988 // $wgAuthenticationTokenVersion in use, so hmac it.
2989 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2991 // The raw hash can be overly long. Shorten it up.
2992 $len = max( 32, self
::TOKEN_LENGTH
);
2993 if ( strlen( $ret ) < $len ) {
2994 // Should never happen, even md5 is 128 bits
2995 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2997 return substr( $ret, -$len );
3002 * Set the random token (used for persistent authentication)
3003 * Called from loadDefaults() among other places.
3005 * @param string|bool $token If specified, set the token to this value
3007 public function setToken( $token = false ) {
3009 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
3010 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3011 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
3012 } elseif ( !$token ) {
3013 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
3015 $this->mToken
= $token;
3020 * Set the password for a password reminder or new account email
3022 * @deprecated Removed in 1.27. Use PasswordReset instead.
3023 * @param string $str New password to set or null to set an invalid
3024 * password hash meaning that the user will not be able to use it
3025 * @param bool $throttle If true, reset the throttle timestamp to the present
3027 public function setNewpassword( $str, $throttle = true ) {
3028 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
3032 * Get the user's e-mail address
3033 * @return string User's email address
3035 public function getEmail() {
3037 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
3038 return $this->mEmail
;
3042 * Get the timestamp of the user's e-mail authentication
3043 * @return string TS_MW timestamp
3045 public function getEmailAuthenticationTimestamp() {
3047 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
3048 return $this->mEmailAuthenticated
;
3052 * Set the user's e-mail address
3053 * @param string $str New e-mail address
3055 public function setEmail( $str ) {
3057 if ( $str == $this->mEmail
) {
3060 $this->invalidateEmail();
3061 $this->mEmail
= $str;
3062 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
3066 * Set the user's e-mail address and a confirmation mail if needed.
3069 * @param string $str New e-mail address
3072 public function setEmailWithConfirmation( $str ) {
3073 global $wgEnableEmail, $wgEmailAuthentication;
3075 if ( !$wgEnableEmail ) {
3076 return Status
::newFatal( 'emaildisabled' );
3079 $oldaddr = $this->getEmail();
3080 if ( $str === $oldaddr ) {
3081 return Status
::newGood( true );
3084 $type = $oldaddr != '' ?
'changed' : 'set';
3085 $notificationResult = null;
3087 if ( $wgEmailAuthentication ) {
3088 // Send the user an email notifying the user of the change in registered
3089 // email address on their previous email address
3090 if ( $type == 'changed' ) {
3091 $change = $str != '' ?
'changed' : 'removed';
3092 $notificationResult = $this->sendMail(
3093 wfMessage( 'notificationemail_subject_' . $change )->text(),
3094 wfMessage( 'notificationemail_body_' . $change,
3095 $this->getRequest()->getIP(),
3102 $this->setEmail( $str );
3104 if ( $str !== '' && $wgEmailAuthentication ) {
3105 // Send a confirmation request to the new address if needed
3106 $result = $this->sendConfirmationMail( $type );
3108 if ( $notificationResult !== null ) {
3109 $result->merge( $notificationResult );
3112 if ( $result->isGood() ) {
3113 // Say to the caller that a confirmation and notification mail has been sent
3114 $result->value
= 'eauth';
3117 $result = Status
::newGood( true );
3124 * Get the user's real name
3125 * @return string User's real name
3127 public function getRealName() {
3128 if ( !$this->isItemLoaded( 'realname' ) ) {
3132 return $this->mRealName
;
3136 * Set the user's real name
3137 * @param string $str New real name
3139 public function setRealName( $str ) {
3141 $this->mRealName
= $str;
3145 * Get the user's current setting for a given option.
3147 * @param string $oname The option to check
3148 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3149 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3150 * @return string|array|int|null User's current value for the option
3151 * @see getBoolOption()
3152 * @see getIntOption()
3154 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3155 global $wgHiddenPrefs;
3156 $this->loadOptions();
3158 # We want 'disabled' preferences to always behave as the default value for
3159 # users, even if they have set the option explicitly in their settings (ie they
3160 # set it, and then it was disabled removing their ability to change it). But
3161 # we don't want to erase the preferences in the database in case the preference
3162 # is re-enabled again. So don't touch $mOptions, just override the returned value
3163 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3164 return self
::getDefaultOption( $oname );
3167 if ( array_key_exists( $oname, $this->mOptions
) ) {
3168 return $this->mOptions
[$oname];
3170 return $defaultOverride;
3175 * Get all user's options
3177 * @param int $flags Bitwise combination of:
3178 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3179 * to the default value. (Since 1.25)
3182 public function getOptions( $flags = 0 ) {
3183 global $wgHiddenPrefs;
3184 $this->loadOptions();
3185 $options = $this->mOptions
;
3187 # We want 'disabled' preferences to always behave as the default value for
3188 # users, even if they have set the option explicitly in their settings (ie they
3189 # set it, and then it was disabled removing their ability to change it). But
3190 # we don't want to erase the preferences in the database in case the preference
3191 # is re-enabled again. So don't touch $mOptions, just override the returned value
3192 foreach ( $wgHiddenPrefs as $pref ) {
3193 $default = self
::getDefaultOption( $pref );
3194 if ( $default !== null ) {
3195 $options[$pref] = $default;
3199 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3200 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3207 * Get the user's current setting for a given option, as a boolean value.
3209 * @param string $oname The option to check
3210 * @return bool User's current value for the option
3213 public function getBoolOption( $oname ) {
3214 return (bool)$this->getOption( $oname );
3218 * Get the user's current setting for a given option, as an integer value.
3220 * @param string $oname The option to check
3221 * @param int $defaultOverride A default value returned if the option does not exist
3222 * @return int User's current value for the option
3225 public function getIntOption( $oname, $defaultOverride = 0 ) {
3226 $val = $this->getOption( $oname );
3228 $val = $defaultOverride;
3230 return intval( $val );
3234 * Set the given option for a user.
3236 * You need to call saveSettings() to actually write to the database.
3238 * @param string $oname The option to set
3239 * @param mixed $val New value to set
3241 public function setOption( $oname, $val ) {
3242 $this->loadOptions();
3244 // Explicitly NULL values should refer to defaults
3245 if ( is_null( $val ) ) {
3246 $val = self
::getDefaultOption( $oname );
3249 $this->mOptions
[$oname] = $val;
3253 * Get a token stored in the preferences (like the watchlist one),
3254 * resetting it if it's empty (and saving changes).
3256 * @param string $oname The option name to retrieve the token from
3257 * @return string|bool User's current value for the option, or false if this option is disabled.
3258 * @see resetTokenFromOption()
3260 * @deprecated since 1.26 Applications should use the OAuth extension
3262 public function getTokenFromOption( $oname ) {
3263 global $wgHiddenPrefs;
3265 $id = $this->getId();
3266 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3270 $token = $this->getOption( $oname );
3272 // Default to a value based on the user token to avoid space
3273 // wasted on storing tokens for all users. When this option
3274 // is set manually by the user, only then is it stored.
3275 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3282 * Reset a token stored in the preferences (like the watchlist one).
3283 * *Does not* save user's preferences (similarly to setOption()).
3285 * @param string $oname The option name to reset the token in
3286 * @return string|bool New token value, or false if this option is disabled.
3287 * @see getTokenFromOption()
3290 public function resetTokenFromOption( $oname ) {
3291 global $wgHiddenPrefs;
3292 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3296 $token = MWCryptRand
::generateHex( 40 );
3297 $this->setOption( $oname, $token );
3302 * Return a list of the types of user options currently returned by
3303 * User::getOptionKinds().
3305 * Currently, the option kinds are:
3306 * - 'registered' - preferences which are registered in core MediaWiki or
3307 * by extensions using the UserGetDefaultOptions hook.
3308 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3309 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3310 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3311 * be used by user scripts.
3312 * - 'special' - "preferences" that are not accessible via User::getOptions
3313 * or User::setOptions.
3314 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3315 * These are usually legacy options, removed in newer versions.
3317 * The API (and possibly others) use this function to determine the possible
3318 * option types for validation purposes, so make sure to update this when a
3319 * new option kind is added.
3321 * @see User::getOptionKinds
3322 * @return array Option kinds
3324 public static function listOptionKinds() {
3327 'registered-multiselect',
3328 'registered-checkmatrix',
3336 * Return an associative array mapping preferences keys to the kind of a preference they're
3337 * used for. Different kinds are handled differently when setting or reading preferences.
3339 * See User::listOptionKinds for the list of valid option types that can be provided.
3341 * @see User::listOptionKinds
3342 * @param IContextSource $context
3343 * @param array|null $options Assoc. array with options keys to check as keys.
3344 * Defaults to $this->mOptions.
3345 * @return array The key => kind mapping data
3347 public function getOptionKinds( IContextSource
$context, $options = null ) {
3348 $this->loadOptions();
3349 if ( $options === null ) {
3350 $options = $this->mOptions
;
3353 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3354 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3357 // Pull out the "special" options, so they don't get converted as
3358 // multiselect or checkmatrix.
3359 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3360 foreach ( $specialOptions as $name => $value ) {
3361 unset( $prefs[$name] );
3364 // Multiselect and checkmatrix options are stored in the database with
3365 // one key per option, each having a boolean value. Extract those keys.
3366 $multiselectOptions = [];
3367 foreach ( $prefs as $name => $info ) {
3368 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3369 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3370 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3371 $prefix = $info['prefix'] ??
$name;
3373 foreach ( $opts as $value ) {
3374 $multiselectOptions["$prefix$value"] = true;
3377 unset( $prefs[$name] );
3380 $checkmatrixOptions = [];
3381 foreach ( $prefs as $name => $info ) {
3382 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3383 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3384 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3385 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3386 $prefix = $info['prefix'] ??
$name;
3388 foreach ( $columns as $column ) {
3389 foreach ( $rows as $row ) {
3390 $checkmatrixOptions["$prefix$column-$row"] = true;
3394 unset( $prefs[$name] );
3398 // $value is ignored
3399 foreach ( $options as $key => $value ) {
3400 if ( isset( $prefs[$key] ) ) {
3401 $mapping[$key] = 'registered';
3402 } elseif ( isset( $multiselectOptions[$key] ) ) {
3403 $mapping[$key] = 'registered-multiselect';
3404 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3405 $mapping[$key] = 'registered-checkmatrix';
3406 } elseif ( isset( $specialOptions[$key] ) ) {
3407 $mapping[$key] = 'special';
3408 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3409 $mapping[$key] = 'userjs';
3411 $mapping[$key] = 'unused';
3419 * Reset certain (or all) options to the site defaults
3421 * The optional parameter determines which kinds of preferences will be reset.
3422 * Supported values are everything that can be reported by getOptionKinds()
3423 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3425 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3426 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3427 * for backwards-compatibility.
3428 * @param IContextSource|null $context Context source used when $resetKinds
3429 * does not contain 'all', passed to getOptionKinds().
3430 * Defaults to RequestContext::getMain() when null.
3432 public function resetOptions(
3433 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3434 IContextSource
$context = null
3437 $defaultOptions = self
::getDefaultOptions();
3439 if ( !is_array( $resetKinds ) ) {
3440 $resetKinds = [ $resetKinds ];
3443 if ( in_array( 'all', $resetKinds ) ) {
3444 $newOptions = $defaultOptions;
3446 if ( $context === null ) {
3447 $context = RequestContext
::getMain();
3450 $optionKinds = $this->getOptionKinds( $context );
3451 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3454 // Use default values for the options that should be deleted, and
3455 // copy old values for the ones that shouldn't.
3456 foreach ( $this->mOptions
as $key => $value ) {
3457 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3458 if ( array_key_exists( $key, $defaultOptions ) ) {
3459 $newOptions[$key] = $defaultOptions[$key];
3462 $newOptions[$key] = $value;
3467 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3469 $this->mOptions
= $newOptions;
3470 $this->mOptionsLoaded
= true;
3474 * Get the user's preferred date format.
3475 * @return string User's preferred date format
3477 public function getDatePreference() {
3478 // Important migration for old data rows
3479 if ( is_null( $this->mDatePreference
) ) {
3481 $value = $this->getOption( 'date' );
3482 $map = $wgLang->getDatePreferenceMigrationMap();
3483 if ( isset( $map[$value] ) ) {
3484 $value = $map[$value];
3486 $this->mDatePreference
= $value;
3488 return $this->mDatePreference
;
3492 * Determine based on the wiki configuration and the user's options,
3493 * whether this user must be over HTTPS no matter what.
3497 public function requiresHTTPS() {
3498 global $wgSecureLogin;
3499 if ( !$wgSecureLogin ) {
3502 $https = $this->getBoolOption( 'prefershttps' );
3503 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3505 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3512 * Get the user preferred stub threshold
3516 public function getStubThreshold() {
3517 global $wgMaxArticleSize; # Maximum article size, in Kb
3518 $threshold = $this->getIntOption( 'stubthreshold' );
3519 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3520 // If they have set an impossible value, disable the preference
3521 // so we can use the parser cache again.
3528 * Get the permissions this user has.
3529 * @return string[] permission names
3531 public function getRights() {
3532 if ( is_null( $this->mRights
) ) {
3533 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3534 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3536 // Deny any rights denied by the user's session, unless this
3537 // endpoint has no sessions.
3538 if ( !defined( 'MW_NO_SESSION' ) ) {
3539 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3540 if ( $allowedRights !== null ) {
3541 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3545 Hooks
::run( 'UserGetRightsRemove', [ $this, &$this->mRights
] );
3546 // Force reindexation of rights when a hook has unset one of them
3547 $this->mRights
= array_values( array_unique( $this->mRights
) );
3549 // If block disables login, we should also remove any
3550 // extra rights blocked users might have, in case the
3551 // blocked user has a pre-existing session (T129738).
3552 // This is checked here for cases where people only call
3553 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3554 // to give a better error message in the common case.
3555 $config = RequestContext
::getMain()->getConfig();
3557 $this->isLoggedIn() &&
3558 $config->get( 'BlockDisablesLogin' ) &&
3562 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3565 return $this->mRights
;
3569 * Get the list of explicit group memberships this user has.
3570 * The implicit * and user groups are not included.
3571 * @return array Array of String internal group names
3573 public function getGroups() {
3575 $this->loadGroups();
3576 return array_keys( $this->mGroupMemberships
);
3580 * Get the list of explicit group memberships this user has, stored as
3581 * UserGroupMembership objects. Implicit groups are not included.
3583 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3586 public function getGroupMemberships() {
3588 $this->loadGroups();
3589 return $this->mGroupMemberships
;
3593 * Get the list of implicit group memberships this user has.
3594 * This includes all explicit groups, plus 'user' if logged in,
3595 * '*' for all accounts, and autopromoted groups
3596 * @param bool $recache Whether to avoid the cache
3597 * @return array Array of String internal group names
3599 public function getEffectiveGroups( $recache = false ) {
3600 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3601 $this->mEffectiveGroups
= array_unique( array_merge(
3602 $this->getGroups(), // explicit groups
3603 $this->getAutomaticGroups( $recache ) // implicit groups
3605 // Avoid PHP 7.1 warning of passing $this by reference
3607 // Hook for additional groups
3608 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3609 // Force reindexation of groups when a hook has unset one of them
3610 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3612 return $this->mEffectiveGroups
;
3616 * Get the list of implicit group memberships this user has.
3617 * This includes 'user' if logged in, '*' for all accounts,
3618 * and autopromoted groups
3619 * @param bool $recache Whether to avoid the cache
3620 * @return array Array of String internal group names
3622 public function getAutomaticGroups( $recache = false ) {
3623 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3624 $this->mImplicitGroups
= [ '*' ];
3625 if ( $this->getId() ) {
3626 $this->mImplicitGroups
[] = 'user';
3628 $this->mImplicitGroups
= array_unique( array_merge(
3629 $this->mImplicitGroups
,
3630 Autopromote
::getAutopromoteGroups( $this )
3634 // Assure data consistency with rights/groups,
3635 // as getEffectiveGroups() depends on this function
3636 $this->mEffectiveGroups
= null;
3639 return $this->mImplicitGroups
;
3643 * Returns the groups the user has belonged to.
3645 * The user may still belong to the returned groups. Compare with getGroups().
3647 * The function will not return groups the user had belonged to before MW 1.17
3649 * @return array Names of the groups the user has belonged to.
3651 public function getFormerGroups() {
3654 if ( is_null( $this->mFormerGroups
) ) {
3655 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3656 ?
wfGetDB( DB_MASTER
)
3657 : wfGetDB( DB_REPLICA
);
3658 $res = $db->select( 'user_former_groups',
3660 [ 'ufg_user' => $this->mId
],
3662 $this->mFormerGroups
= [];
3663 foreach ( $res as $row ) {
3664 $this->mFormerGroups
[] = $row->ufg_group
;
3668 return $this->mFormerGroups
;
3672 * Get the user's edit count.
3673 * @return int|null Null for anonymous users
3675 public function getEditCount() {
3676 if ( !$this->getId() ) {
3680 if ( $this->mEditCount
=== null ) {
3681 /* Populate the count, if it has not been populated yet */
3682 $dbr = wfGetDB( DB_REPLICA
);
3683 // check if the user_editcount field has been initialized
3684 $count = $dbr->selectField(
3685 'user', 'user_editcount',
3686 [ 'user_id' => $this->mId
],
3690 if ( $count === null ) {
3691 // it has not been initialized. do so.
3692 $count = $this->initEditCount();
3694 $this->mEditCount
= $count;
3696 return (int)$this->mEditCount
;
3700 * Add the user to the given group. This takes immediate effect.
3701 * If the user is already in the group, the expiry time will be updated to the new
3702 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3705 * @param string $group Name of the group to add
3706 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3707 * wfTimestamp(), or null if the group assignment should not expire
3710 public function addGroup( $group, $expiry = null ) {
3712 $this->loadGroups();
3715 $expiry = wfTimestamp( TS_MW
, $expiry );
3718 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3722 // create the new UserGroupMembership and put it in the DB
3723 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3724 if ( !$ugm->insert( true ) ) {
3728 $this->mGroupMemberships
[$group] = $ugm;
3730 // Refresh the groups caches, and clear the rights cache so it will be
3731 // refreshed on the next call to $this->getRights().
3732 $this->getEffectiveGroups( true );
3733 $this->mRights
= null;
3735 $this->invalidateCache();
3741 * Remove the user from the given group.
3742 * This takes immediate effect.
3743 * @param string $group Name of the group to remove
3746 public function removeGroup( $group ) {
3749 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3753 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3754 // delete the membership entry
3755 if ( !$ugm ||
!$ugm->delete() ) {
3759 $this->loadGroups();
3760 unset( $this->mGroupMemberships
[$group] );
3762 // Refresh the groups caches, and clear the rights cache so it will be
3763 // refreshed on the next call to $this->getRights().
3764 $this->getEffectiveGroups( true );
3765 $this->mRights
= null;
3767 $this->invalidateCache();
3773 * Get whether the user is logged in
3776 public function isLoggedIn() {
3777 return $this->getId() != 0;
3781 * Get whether the user is anonymous
3784 public function isAnon() {
3785 return !$this->isLoggedIn();
3789 * @return bool Whether this user is flagged as being a bot role account
3792 public function isBot() {
3793 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3798 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3804 * Check if user is allowed to access a feature / make an action
3806 * @param string $permissions,... Permissions to test
3807 * @return bool True if user is allowed to perform *any* of the given actions
3809 public function isAllowedAny() {
3810 $permissions = func_get_args();
3811 foreach ( $permissions as $permission ) {
3812 if ( $this->isAllowed( $permission ) ) {
3821 * @param string $permissions,... Permissions to test
3822 * @return bool True if the user is allowed to perform *all* of the given actions
3824 public function isAllowedAll() {
3825 $permissions = func_get_args();
3826 foreach ( $permissions as $permission ) {
3827 if ( !$this->isAllowed( $permission ) ) {
3835 * Internal mechanics of testing a permission
3836 * @param string $action
3839 public function isAllowed( $action = '' ) {
3840 if ( $action === '' ) {
3841 return true; // In the spirit of DWIM
3843 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3844 // by misconfiguration: 0 == 'foo'
3845 return in_array( $action, $this->getRights(), true );
3849 * Check whether to enable recent changes patrol features for this user
3850 * @return bool True or false
3852 public function useRCPatrol() {
3853 global $wgUseRCPatrol;
3854 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3858 * Check whether to enable new pages patrol features for this user
3859 * @return bool True or false
3861 public function useNPPatrol() {
3862 global $wgUseRCPatrol, $wgUseNPPatrol;
3864 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3865 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3870 * Check whether to enable new files patrol features for this user
3871 * @return bool True or false
3873 public function useFilePatrol() {
3874 global $wgUseRCPatrol, $wgUseFilePatrol;
3876 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3877 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3882 * Get the WebRequest object to use with this object
3884 * @return WebRequest
3886 public function getRequest() {
3887 if ( $this->mRequest
) {
3888 return $this->mRequest
;
3896 * Check the watched status of an article.
3897 * @since 1.22 $checkRights parameter added
3898 * @param Title $title Title of the article to look at
3899 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3900 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3903 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3904 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3905 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3912 * @since 1.22 $checkRights parameter added
3913 * @param Title $title Title of the article to look at
3914 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3915 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3917 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3918 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3919 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3921 [ $title->getSubjectPage(), $title->getTalkPage() ]
3924 $this->invalidateCache();
3928 * Stop watching an article.
3929 * @since 1.22 $checkRights parameter added
3930 * @param Title $title Title of the article to look at
3931 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3932 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3934 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3935 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3936 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3937 $store->removeWatch( $this, $title->getSubjectPage() );
3938 $store->removeWatch( $this, $title->getTalkPage() );
3940 $this->invalidateCache();
3944 * Clear the user's notification timestamp for the given title.
3945 * If e-notif e-mails are on, they will receive notification mails on
3946 * the next change of the page if it's watched etc.
3947 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3948 * @param Title &$title Title of the article to look at
3949 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3951 public function clearNotification( &$title, $oldid = 0 ) {
3952 global $wgUseEnotif, $wgShowUpdatedMarker;
3954 // Do nothing if the database is locked to writes
3955 if ( wfReadOnly() ) {
3959 // Do nothing if not allowed to edit the watchlist
3960 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3964 // If we're working on user's talk page, we should update the talk page message indicator
3965 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3966 // Avoid PHP 7.1 warning of passing $this by reference
3968 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3972 // Try to update the DB post-send and only if needed...
3973 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3974 if ( !$this->getNewtalk() ) {
3975 return; // no notifications to clear
3978 // Delete the last notifications (they stack up)
3979 $this->setNewtalk( false );
3981 // If there is a new, unseen, revision, use its timestamp
3983 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3986 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3991 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3995 if ( $this->isAnon() ) {
3996 // Nothing else to do...
4000 // Only update the timestamp if the page is being watched.
4001 // The query to find out if it is watched is cached both in memcached and per-invocation,
4002 // and when it does have to be executed, it can be on a replica DB
4003 // If this is the user's newtalk page, we always update the timestamp
4005 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
4009 MediaWikiServices
::getInstance()->getWatchedItemStore()
4010 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
4014 * Resets all of the given user's page-change notification timestamps.
4015 * If e-notif e-mails are on, they will receive notification mails on
4016 * the next change of any watched page.
4017 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
4019 public function clearAllNotifications() {
4020 global $wgUseEnotif, $wgShowUpdatedMarker;
4021 // Do nothing if not allowed to edit the watchlist
4022 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
4026 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
4027 $this->setNewtalk( false );
4031 $id = $this->getId();
4036 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
4037 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4039 // We also need to clear here the "you have new message" notification for the own
4040 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
4044 * Compute experienced level based on edit count and registration date.
4046 * @return string 'newcomer', 'learner', or 'experienced'
4048 public function getExperienceLevel() {
4049 global $wgLearnerEdits,
4050 $wgExperiencedUserEdits,
4051 $wgLearnerMemberSince,
4052 $wgExperiencedUserMemberSince;
4054 if ( $this->isAnon() ) {
4058 $editCount = $this->getEditCount();
4059 $registration = $this->getRegistration();
4061 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
4062 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
4065 $editCount < $wgLearnerEdits ||
4066 $registration > $learnerRegistration
4070 $editCount > $wgExperiencedUserEdits &&
4071 $registration <= $experiencedRegistration
4073 return 'experienced';
4080 * Persist this user's session (e.g. set cookies)
4082 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
4084 * @param bool|null $secure Whether to force secure/insecure cookies or use default
4085 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
4087 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
4089 if ( 0 == $this->mId
) {
4093 $session = $this->getRequest()->getSession();
4094 if ( $request && $session->getRequest() !== $request ) {
4095 $session = $session->sessionWithRequest( $request );
4097 $delay = $session->delaySave();
4099 if ( !$session->getUser()->equals( $this ) ) {
4100 if ( !$session->canSetUser() ) {
4101 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4102 ->warning( __METHOD__
.
4103 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4107 $session->setUser( $this );
4110 $session->setRememberUser( $rememberMe );
4111 if ( $secure !== null ) {
4112 $session->setForceHTTPS( $secure );
4115 $session->persist();
4117 ScopedCallback
::consume( $delay );
4121 * Log this user out.
4123 public function logout() {
4124 // Avoid PHP 7.1 warning of passing $this by reference
4126 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4132 * Clear the user's session, and reset the instance cache.
4135 public function doLogout() {
4136 $session = $this->getRequest()->getSession();
4137 if ( !$session->canSetUser() ) {
4138 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4139 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4140 $error = 'immutable';
4141 } elseif ( !$session->getUser()->equals( $this ) ) {
4142 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4143 ->warning( __METHOD__
.
4144 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4146 // But we still may as well make this user object anon
4147 $this->clearInstanceCache( 'defaults' );
4148 $error = 'wronguser';
4150 $this->clearInstanceCache( 'defaults' );
4151 $delay = $session->delaySave();
4152 $session->unpersist(); // Clear cookies (T127436)
4153 $session->setLoggedOutTimestamp( time() );
4154 $session->setUser( new User
);
4155 $session->set( 'wsUserID', 0 ); // Other code expects this
4156 $session->resetAllTokens();
4157 ScopedCallback
::consume( $delay );
4160 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4161 'event' => 'logout',
4162 'successful' => $error === false,
4163 'status' => $error ?
: 'success',
4168 * Save this user's settings into the database.
4169 * @todo Only rarely do all these fields need to be set!
4171 public function saveSettings() {
4172 if ( wfReadOnly() ) {
4173 // @TODO: caller should deal with this instead!
4174 // This should really just be an exception.
4175 MWExceptionHandler
::logException( new DBExpectedError(
4177 "Could not update user with ID '{$this->mId}'; DB is read-only."
4183 if ( 0 == $this->mId
) {
4187 // Get a new user_touched that is higher than the old one.
4188 // This will be used for a CAS check as a last-resort safety
4189 // check against race conditions and replica DB lag.
4190 $newTouched = $this->newTouchedTimestamp();
4192 $dbw = wfGetDB( DB_MASTER
);
4193 $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $newTouched ) {
4194 global $wgActorTableSchemaMigrationStage;
4196 $dbw->update( 'user',
4198 'user_name' => $this->mName
,
4199 'user_real_name' => $this->mRealName
,
4200 'user_email' => $this->mEmail
,
4201 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4202 'user_touched' => $dbw->timestamp( $newTouched ),
4203 'user_token' => strval( $this->mToken
),
4204 'user_email_token' => $this->mEmailToken
,
4205 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4206 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4207 'user_id' => $this->mId
,
4211 if ( !$dbw->affectedRows() ) {
4212 // Maybe the problem was a missed cache update; clear it to be safe
4213 $this->clearSharedCache( 'refresh' );
4214 // User was changed in the meantime or loaded with stale data
4215 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4216 LoggerFactory
::getInstance( 'preferences' )->warning(
4217 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4218 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4220 throw new MWException( "CAS update failed on user_touched. " .
4221 "The version of the user to be saved is older than the current version."
4225 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4228 [ 'actor_name' => $this->mName
],
4229 [ 'actor_user' => $this->mId
],
4235 $this->mTouched
= $newTouched;
4236 $this->saveOptions();
4238 Hooks
::run( 'UserSaveSettings', [ $this ] );
4239 $this->clearSharedCache();
4240 $this->getUserPage()->invalidateCache();
4244 * If only this user's username is known, and it exists, return the user ID.
4246 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4249 public function idForName( $flags = 0 ) {
4250 $s = trim( $this->getName() );
4255 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4256 ?
wfGetDB( DB_MASTER
)
4257 : wfGetDB( DB_REPLICA
);
4259 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4260 ?
[ 'LOCK IN SHARE MODE' ]
4263 $id = $db->selectField( 'user',
4264 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4270 * Add a user to the database, return the user object
4272 * @param string $name Username to add
4273 * @param array $params Array of Strings Non-default parameters to save to
4274 * the database as user_* fields:
4275 * - email: The user's email address.
4276 * - email_authenticated: The email authentication timestamp.
4277 * - real_name: The user's real name.
4278 * - options: An associative array of non-default options.
4279 * - token: Random authentication token. Do not set.
4280 * - registration: Registration timestamp. Do not set.
4282 * @return User|null User object, or null if the username already exists.
4284 public static function createNew( $name, $params = [] ) {
4285 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4286 if ( isset( $params[$field] ) ) {
4287 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4288 unset( $params[$field] );
4294 $user->setToken(); // init token
4295 if ( isset( $params['options'] ) ) {
4296 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4297 unset( $params['options'] );
4299 $dbw = wfGetDB( DB_MASTER
);
4301 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4304 'user_name' => $name,
4305 'user_password' => $noPass,
4306 'user_newpassword' => $noPass,
4307 'user_email' => $user->mEmail
,
4308 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4309 'user_real_name' => $user->mRealName
,
4310 'user_token' => strval( $user->mToken
),
4311 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4312 'user_editcount' => 0,
4313 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4315 foreach ( $params as $name => $value ) {
4316 $fields["user_$name"] = $value;
4319 return $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) use ( $fields ) {
4320 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4321 if ( $dbw->affectedRows() ) {
4322 $newUser = self
::newFromId( $dbw->insertId() );
4323 // Load the user from master to avoid replica lag
4324 $newUser->load( self
::READ_LATEST
);
4325 $newUser->updateActorId( $dbw );
4334 * Add this existing user object to the database. If the user already
4335 * exists, a fatal status object is returned, and the user object is
4336 * initialised with the data from the database.
4338 * Previously, this function generated a DB error due to a key conflict
4339 * if the user already existed. Many extension callers use this function
4340 * in code along the lines of:
4342 * $user = User::newFromName( $name );
4343 * if ( !$user->isLoggedIn() ) {
4344 * $user->addToDatabase();
4346 * // do something with $user...
4348 * However, this was vulnerable to a race condition (T18020). By
4349 * initialising the user object if the user exists, we aim to support this
4350 * calling sequence as far as possible.
4352 * Note that if the user exists, this function will acquire a write lock,
4353 * so it is still advisable to make the call conditional on isLoggedIn(),
4354 * and to commit the transaction after calling.
4356 * @throws MWException
4359 public function addToDatabase() {
4361 if ( !$this->mToken
) {
4362 $this->setToken(); // init token
4365 if ( !is_string( $this->mName
) ) {
4366 throw new RuntimeException( "User name field is not set." );
4369 $this->mTouched
= $this->newTouchedTimestamp();
4371 $dbw = wfGetDB( DB_MASTER
);
4372 $status = $dbw->doAtomicSection( __METHOD__
, function ( $dbw, $fname ) {
4373 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4374 $dbw->insert( 'user',
4376 'user_name' => $this->mName
,
4377 'user_password' => $noPass,
4378 'user_newpassword' => $noPass,
4379 'user_email' => $this->mEmail
,
4380 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4381 'user_real_name' => $this->mRealName
,
4382 'user_token' => strval( $this->mToken
),
4383 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4384 'user_editcount' => 0,
4385 'user_touched' => $dbw->timestamp( $this->mTouched
),
4389 if ( !$dbw->affectedRows() ) {
4390 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4391 $this->mId
= $dbw->selectField(
4394 [ 'user_name' => $this->mName
],
4396 [ 'LOCK IN SHARE MODE' ]
4400 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4405 throw new MWException( $fname . ": hit a key conflict attempting " .
4406 "to insert user '{$this->mName}' row, but it was not present in select!" );
4408 return Status
::newFatal( 'userexists' );
4410 $this->mId
= $dbw->insertId();
4411 self
::$idCacheByName[$this->mName
] = $this->mId
;
4412 $this->updateActorId( $dbw );
4414 return Status
::newGood();
4416 if ( !$status->isGood() ) {
4420 // Clear instance cache other than user table data and actor, which is already accurate
4421 $this->clearInstanceCache();
4423 $this->saveOptions();
4424 return Status
::newGood();
4428 * Update the actor ID after an insert
4429 * @param IDatabase $dbw Writable database handle
4431 private function updateActorId( IDatabase
$dbw ) {
4432 global $wgActorTableSchemaMigrationStage;
4434 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
4437 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4440 $this->mActorId
= (int)$dbw->insertId();
4445 * If this user is logged-in and blocked,
4446 * block any IP address they've successfully logged in from.
4447 * @return bool A block was spread
4449 public function spreadAnyEditBlock() {
4450 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4451 return $this->spreadBlock();
4458 * If this (non-anonymous) user is blocked,
4459 * block the IP address they've successfully logged in from.
4460 * @return bool A block was spread
4462 protected function spreadBlock() {
4463 wfDebug( __METHOD__
. "()\n" );
4465 if ( $this->mId
== 0 ) {
4469 $userblock = Block
::newFromTarget( $this->getName() );
4470 if ( !$userblock ) {
4474 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4478 * Get whether the user is explicitly blocked from account creation.
4479 * @return bool|Block
4481 public function isBlockedFromCreateAccount() {
4482 $this->getBlockedStatus();
4483 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4484 return $this->mBlock
;
4487 # T15611: if the IP address the user is trying to create an account from is
4488 # blocked with createaccount disabled, prevent new account creation there even
4489 # when the user is logged in
4490 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4491 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4493 return $this->mBlockedFromCreateAccount
instanceof Block
4494 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4495 ?
$this->mBlockedFromCreateAccount
4500 * Get whether the user is blocked from using Special:Emailuser.
4503 public function isBlockedFromEmailuser() {
4504 $this->getBlockedStatus();
4505 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4509 * Get whether the user is allowed to create an account.
4512 public function isAllowedToCreateAccount() {
4513 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4517 * Get this user's personal page title.
4519 * @return Title User's personal page title
4521 public function getUserPage() {
4522 return Title
::makeTitle( NS_USER
, $this->getName() );
4526 * Get this user's talk page title.
4528 * @return Title User's talk page title
4530 public function getTalkPage() {
4531 $title = $this->getUserPage();
4532 return $title->getTalkPage();
4536 * Determine whether the user is a newbie. Newbies are either
4537 * anonymous IPs, or the most recently created accounts.
4540 public function isNewbie() {
4541 return !$this->isAllowed( 'autoconfirmed' );
4545 * Check to see if the given clear-text password is one of the accepted passwords
4546 * @deprecated since 1.27, use AuthManager instead
4547 * @param string $password User password
4548 * @return bool True if the given password is correct, otherwise False
4550 public function checkPassword( $password ) {
4551 wfDeprecated( __METHOD__
, '1.27' );
4553 $manager = AuthManager
::singleton();
4554 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4555 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4557 'username' => $this->getName(),
4558 'password' => $password,
4561 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4562 switch ( $res->status
) {
4563 case AuthenticationResponse
::PASS
:
4565 case AuthenticationResponse
::FAIL
:
4566 // Hope it's not a PreAuthenticationProvider that failed...
4567 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4568 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4571 throw new BadMethodCallException(
4572 'AuthManager returned a response unsupported by ' . __METHOD__
4578 * Check if the given clear-text password matches the temporary password
4579 * sent by e-mail for password reset operations.
4581 * @deprecated since 1.27, use AuthManager instead
4582 * @param string $plaintext
4583 * @return bool True if matches, false otherwise
4585 public function checkTemporaryPassword( $plaintext ) {
4586 wfDeprecated( __METHOD__
, '1.27' );
4587 // Can't check the temporary password individually.
4588 return $this->checkPassword( $plaintext );
4592 * Initialize (if necessary) and return a session token value
4593 * which can be used in edit forms to show that the user's
4594 * login credentials aren't being hijacked with a foreign form
4598 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4599 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4600 * @return MediaWiki\Session\Token The new edit token
4602 public function getEditTokenObject( $salt = '', $request = null ) {
4603 if ( $this->isAnon() ) {
4604 return new LoggedOutEditToken();
4608 $request = $this->getRequest();
4610 return $request->getSession()->getToken( $salt );
4614 * Initialize (if necessary) and return a session token value
4615 * which can be used in edit forms to show that the user's
4616 * login credentials aren't being hijacked with a foreign form
4619 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4622 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4623 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4624 * @return string The new edit token
4626 public function getEditToken( $salt = '', $request = null ) {
4627 return $this->getEditTokenObject( $salt, $request )->toString();
4631 * Check given value against the token value stored in the session.
4632 * A match should confirm that the form was submitted from the
4633 * user's own login session, not a form submission from a third-party
4636 * @param string $val Input value to compare
4637 * @param string|array $salt Optional function-specific data for hashing
4638 * @param WebRequest|null $request Object to use or null to use $wgRequest
4639 * @param int|null $maxage Fail tokens older than this, in seconds
4640 * @return bool Whether the token matches
4642 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4643 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4647 * Check given value against the token value stored in the session,
4648 * ignoring the suffix.
4650 * @param string $val Input value to compare
4651 * @param string|array $salt Optional function-specific data for hashing
4652 * @param WebRequest|null $request Object to use or null to use $wgRequest
4653 * @param int|null $maxage Fail tokens older than this, in seconds
4654 * @return bool Whether the token matches
4656 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4657 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4658 return $this->matchEditToken( $val, $salt, $request, $maxage );
4662 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4663 * mail to the user's given address.
4665 * @param string $type Message to send, either "created", "changed" or "set"
4668 public function sendConfirmationMail( $type = 'created' ) {
4670 $expiration = null; // gets passed-by-ref and defined in next line.
4671 $token = $this->confirmationToken( $expiration );
4672 $url = $this->confirmationTokenUrl( $token );
4673 $invalidateURL = $this->invalidationTokenUrl( $token );
4674 $this->saveSettings();
4676 if ( $type == 'created' ||
$type === false ) {
4677 $message = 'confirmemail_body';
4678 } elseif ( $type === true ) {
4679 $message = 'confirmemail_body_changed';
4681 // Messages: confirmemail_body_changed, confirmemail_body_set
4682 $message = 'confirmemail_body_' . $type;
4685 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4686 wfMessage( $message,
4687 $this->getRequest()->getIP(),
4690 $wgLang->userTimeAndDate( $expiration, $this ),
4692 $wgLang->userDate( $expiration, $this ),
4693 $wgLang->userTime( $expiration, $this ) )->text() );
4697 * Send an e-mail to this user's account. Does not check for
4698 * confirmed status or validity.
4700 * @param string $subject Message subject
4701 * @param string $body Message body
4702 * @param User|null $from Optional sending user; if unspecified, default
4703 * $wgPasswordSender will be used.
4704 * @param string|null $replyto Reply-To address
4707 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4708 global $wgPasswordSender;
4710 if ( $from instanceof User
) {
4711 $sender = MailAddress
::newFromUser( $from );
4713 $sender = new MailAddress( $wgPasswordSender,
4714 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4716 $to = MailAddress
::newFromUser( $this );
4718 return UserMailer
::send( $to, $sender, $subject, $body, [
4719 'replyTo' => $replyto,
4724 * Generate, store, and return a new e-mail confirmation code.
4725 * A hash (unsalted, since it's used as a key) is stored.
4727 * @note Call saveSettings() after calling this function to commit
4728 * this change to the database.
4730 * @param string &$expiration Accepts the expiration time
4731 * @return string New token
4733 protected function confirmationToken( &$expiration ) {
4734 global $wgUserEmailConfirmationTokenExpiry;
4736 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4737 $expiration = wfTimestamp( TS_MW
, $expires );
4739 $token = MWCryptRand
::generateHex( 32 );
4740 $hash = md5( $token );
4741 $this->mEmailToken
= $hash;
4742 $this->mEmailTokenExpires
= $expiration;
4747 * Return a URL the user can use to confirm their email address.
4748 * @param string $token Accepts the email confirmation token
4749 * @return string New token URL
4751 protected function confirmationTokenUrl( $token ) {
4752 return $this->getTokenUrl( 'ConfirmEmail', $token );
4756 * Return a URL the user can use to invalidate their email address.
4757 * @param string $token Accepts the email confirmation token
4758 * @return string New token URL
4760 protected function invalidationTokenUrl( $token ) {
4761 return $this->getTokenUrl( 'InvalidateEmail', $token );
4765 * Internal function to format the e-mail validation/invalidation URLs.
4766 * This uses a quickie hack to use the
4767 * hardcoded English names of the Special: pages, for ASCII safety.
4769 * @note Since these URLs get dropped directly into emails, using the
4770 * short English names avoids insanely long URL-encoded links, which
4771 * also sometimes can get corrupted in some browsers/mailers
4772 * (T8957 with Gmail and Internet Explorer).
4774 * @param string $page Special page
4775 * @param string $token
4776 * @return string Formatted URL
4778 protected function getTokenUrl( $page, $token ) {
4779 // Hack to bypass localization of 'Special:'
4780 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4781 return $title->getCanonicalURL();
4785 * Mark the e-mail address confirmed.
4787 * @note Call saveSettings() after calling this function to commit the change.
4791 public function confirmEmail() {
4792 // Check if it's already confirmed, so we don't touch the database
4793 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4794 if ( !$this->isEmailConfirmed() ) {
4795 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4796 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4802 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4803 * address if it was already confirmed.
4805 * @note Call saveSettings() after calling this function to commit the change.
4806 * @return bool Returns true
4808 public function invalidateEmail() {
4810 $this->mEmailToken
= null;
4811 $this->mEmailTokenExpires
= null;
4812 $this->setEmailAuthenticationTimestamp( null );
4814 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4819 * Set the e-mail authentication timestamp.
4820 * @param string $timestamp TS_MW timestamp
4822 public function setEmailAuthenticationTimestamp( $timestamp ) {
4824 $this->mEmailAuthenticated
= $timestamp;
4825 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4829 * Is this user allowed to send e-mails within limits of current
4830 * site configuration?
4833 public function canSendEmail() {
4834 global $wgEnableEmail, $wgEnableUserEmail;
4835 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4838 $canSend = $this->isEmailConfirmed();
4839 // Avoid PHP 7.1 warning of passing $this by reference
4841 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4846 * Is this user allowed to receive e-mails within limits of current
4847 * site configuration?
4850 public function canReceiveEmail() {
4851 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4855 * Is this user's e-mail address valid-looking and confirmed within
4856 * limits of the current site configuration?
4858 * @note If $wgEmailAuthentication is on, this may require the user to have
4859 * confirmed their address by returning a code or using a password
4860 * sent to the address from the wiki.
4864 public function isEmailConfirmed() {
4865 global $wgEmailAuthentication;
4867 // Avoid PHP 7.1 warning of passing $this by reference
4870 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4871 if ( $this->isAnon() ) {
4874 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4877 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4887 * Check whether there is an outstanding request for e-mail confirmation.
4890 public function isEmailConfirmationPending() {
4891 global $wgEmailAuthentication;
4892 return $wgEmailAuthentication &&
4893 !$this->isEmailConfirmed() &&
4894 $this->mEmailToken
&&
4895 $this->mEmailTokenExpires
> wfTimestamp();
4899 * Get the timestamp of account creation.
4901 * @return string|bool|null Timestamp of account creation, false for
4902 * non-existent/anonymous user accounts, or null if existing account
4903 * but information is not in database.
4905 public function getRegistration() {
4906 if ( $this->isAnon() ) {
4910 return $this->mRegistration
;
4914 * Get the timestamp of the first edit
4916 * @return string|bool Timestamp of first edit, or false for
4917 * non-existent/anonymous user accounts.
4919 public function getFirstEditTimestamp() {
4920 if ( $this->getId() == 0 ) {
4921 return false; // anons
4923 $dbr = wfGetDB( DB_REPLICA
);
4924 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4925 $time = $dbr->selectField(
4926 [ 'revision' ] +
$actorWhere['tables'],
4928 [ $actorWhere['conds'] ],
4930 [ 'ORDER BY' => 'rev_timestamp ASC' ],
4931 $actorWhere['joins']
4934 return false; // no edits
4936 return wfTimestamp( TS_MW
, $time );
4940 * Get the permissions associated with a given list of groups
4942 * @param array $groups Array of Strings List of internal group names
4943 * @return array Array of Strings List of permission key names for given groups combined
4945 public static function getGroupPermissions( $groups ) {
4946 global $wgGroupPermissions, $wgRevokePermissions;
4948 // grant every granted permission first
4949 foreach ( $groups as $group ) {
4950 if ( isset( $wgGroupPermissions[$group] ) ) {
4951 $rights = array_merge( $rights,
4952 // array_filter removes empty items
4953 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4956 // now revoke the revoked permissions
4957 foreach ( $groups as $group ) {
4958 if ( isset( $wgRevokePermissions[$group] ) ) {
4959 $rights = array_diff( $rights,
4960 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4963 return array_unique( $rights );
4967 * Get all the groups who have a given permission
4969 * @param string $role Role to check
4970 * @return array Array of Strings List of internal group names with the given permission
4972 public static function getGroupsWithPermission( $role ) {
4973 global $wgGroupPermissions;
4974 $allowedGroups = [];
4975 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4976 if ( self
::groupHasPermission( $group, $role ) ) {
4977 $allowedGroups[] = $group;
4980 return $allowedGroups;
4984 * Check, if the given group has the given permission
4986 * If you're wanting to check whether all users have a permission, use
4987 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4991 * @param string $group Group to check
4992 * @param string $role Role to check
4995 public static function groupHasPermission( $group, $role ) {
4996 global $wgGroupPermissions, $wgRevokePermissions;
4997 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4998 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
5002 * Check if all users may be assumed to have the given permission
5004 * We generally assume so if the right is granted to '*' and isn't revoked
5005 * on any group. It doesn't attempt to take grants or other extension
5006 * limitations on rights into account in the general case, though, as that
5007 * would require it to always return false and defeat the purpose.
5008 * Specifically, session-based rights restrictions (such as OAuth or bot
5009 * passwords) are applied based on the current session.
5012 * @param string $right Right to check
5015 public static function isEveryoneAllowed( $right ) {
5016 global $wgGroupPermissions, $wgRevokePermissions;
5019 // Use the cached results, except in unit tests which rely on
5020 // being able change the permission mid-request
5021 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
5022 return $cache[$right];
5025 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
5026 $cache[$right] = false;
5030 // If it's revoked anywhere, then everyone doesn't have it
5031 foreach ( $wgRevokePermissions as $rights ) {
5032 if ( isset( $rights[$right] ) && $rights[$right] ) {
5033 $cache[$right] = false;
5038 // Remove any rights that aren't allowed to the global-session user,
5039 // unless there are no sessions for this endpoint.
5040 if ( !defined( 'MW_NO_SESSION' ) ) {
5041 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
5042 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
5043 $cache[$right] = false;
5048 // Allow extensions to say false
5049 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
5050 $cache[$right] = false;
5054 $cache[$right] = true;
5059 * Get the localized descriptive name for a group, if it exists
5060 * @deprecated since 1.29 Use UserGroupMembership::getGroupName instead
5062 * @param string $group Internal group name
5063 * @return string Localized descriptive group name
5065 public static function getGroupName( $group ) {
5066 wfDeprecated( __METHOD__
, '1.29' );
5067 return UserGroupMembership
::getGroupName( $group );
5071 * Get the localized descriptive name for a member of a group, if it exists
5072 * @deprecated since 1.29 Use UserGroupMembership::getGroupMemberName instead
5074 * @param string $group Internal group name
5075 * @param string $username Username for gender (since 1.19)
5076 * @return string Localized name for group member
5078 public static function getGroupMember( $group, $username = '#' ) {
5079 wfDeprecated( __METHOD__
, '1.29' );
5080 return UserGroupMembership
::getGroupMemberName( $group, $username );
5084 * Return the set of defined explicit groups.
5085 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5086 * are not included, as they are defined automatically, not in the database.
5087 * @return array Array of internal group names
5089 public static function getAllGroups() {
5090 global $wgGroupPermissions, $wgRevokePermissions;
5091 return array_values( array_diff(
5092 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5093 self
::getImplicitGroups()
5098 * Get a list of all available permissions.
5099 * @return string[] Array of permission names
5101 public static function getAllRights() {
5102 if ( self
::$mAllRights === false ) {
5103 global $wgAvailableRights;
5104 if ( count( $wgAvailableRights ) ) {
5105 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5107 self
::$mAllRights = self
::$mCoreRights;
5109 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5111 return self
::$mAllRights;
5115 * Get a list of implicit groups
5116 * @return array Array of Strings Array of internal group names
5118 public static function getImplicitGroups() {
5119 global $wgImplicitGroups;
5121 $groups = $wgImplicitGroups;
5122 # Deprecated, use $wgImplicitGroups instead
5123 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
5129 * Get the title of a page describing a particular group
5130 * @deprecated since 1.29 Use UserGroupMembership::getGroupPage instead
5132 * @param string $group Internal group name
5133 * @return Title|bool Title of the page if it exists, false otherwise
5135 public static function getGroupPage( $group ) {
5136 wfDeprecated( __METHOD__
, '1.29' );
5137 return UserGroupMembership
::getGroupPage( $group );
5141 * Create a link to the group in HTML, if available;
5142 * else return the group name.
5143 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5144 * make the link yourself if you need custom text
5146 * @param string $group Internal name of the group
5147 * @param string $text The text of the link
5148 * @return string HTML link to the group
5150 public static function makeGroupLinkHTML( $group, $text = '' ) {
5151 wfDeprecated( __METHOD__
, '1.29' );
5153 if ( $text == '' ) {
5154 $text = UserGroupMembership
::getGroupName( $group );
5156 $title = UserGroupMembership
::getGroupPage( $group );
5158 return MediaWikiServices
::getInstance()
5159 ->getLinkRenderer()->makeLink( $title, $text );
5161 return htmlspecialchars( $text );
5166 * Create a link to the group in Wikitext, if available;
5167 * else return the group name.
5168 * @deprecated since 1.29 Use UserGroupMembership::getLink instead, or
5169 * make the link yourself if you need custom text
5171 * @param string $group Internal name of the group
5172 * @param string $text The text of the link
5173 * @return string Wikilink to the group
5175 public static function makeGroupLinkWiki( $group, $text = '' ) {
5176 wfDeprecated( __METHOD__
, '1.29' );
5178 if ( $text == '' ) {
5179 $text = UserGroupMembership
::getGroupName( $group );
5181 $title = UserGroupMembership
::getGroupPage( $group );
5183 $page = $title->getFullText();
5184 return "[[$page|$text]]";
5191 * Returns an array of the groups that a particular group can add/remove.
5193 * @param string $group The group to check for whether it can add/remove
5194 * @return array Array( 'add' => array( addablegroups ),
5195 * 'remove' => array( removablegroups ),
5196 * 'add-self' => array( addablegroups to self),
5197 * 'remove-self' => array( removable groups from self) )
5199 public static function changeableByGroup( $group ) {
5200 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5209 if ( empty( $wgAddGroups[$group] ) ) {
5210 // Don't add anything to $groups
5211 } elseif ( $wgAddGroups[$group] === true ) {
5212 // You get everything
5213 $groups['add'] = self
::getAllGroups();
5214 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5215 $groups['add'] = $wgAddGroups[$group];
5218 // Same thing for remove
5219 if ( empty( $wgRemoveGroups[$group] ) ) {
5221 } elseif ( $wgRemoveGroups[$group] === true ) {
5222 $groups['remove'] = self
::getAllGroups();
5223 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5224 $groups['remove'] = $wgRemoveGroups[$group];
5227 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5228 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5229 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5230 if ( is_int( $key ) ) {
5231 $wgGroupsAddToSelf['user'][] = $value;
5236 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5237 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5238 if ( is_int( $key ) ) {
5239 $wgGroupsRemoveFromSelf['user'][] = $value;
5244 // Now figure out what groups the user can add to him/herself
5245 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5247 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5248 // No idea WHY this would be used, but it's there
5249 $groups['add-self'] = self
::getAllGroups();
5250 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5251 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5254 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5256 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5257 $groups['remove-self'] = self
::getAllGroups();
5258 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5259 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5266 * Returns an array of groups that this user can add and remove
5267 * @return array Array( 'add' => array( addablegroups ),
5268 * 'remove' => array( removablegroups ),
5269 * 'add-self' => array( addablegroups to self),
5270 * 'remove-self' => array( removable groups from self) )
5272 public function changeableGroups() {
5273 if ( $this->isAllowed( 'userrights' ) ) {
5274 // This group gives the right to modify everything (reverse-
5275 // compatibility with old "userrights lets you change
5277 // Using array_merge to make the groups reindexed
5278 $all = array_merge( self
::getAllGroups() );
5287 // Okay, it's not so simple, we will have to go through the arrays
5294 $addergroups = $this->getEffectiveGroups();
5296 foreach ( $addergroups as $addergroup ) {
5297 $groups = array_merge_recursive(
5298 $groups, $this->changeableByGroup( $addergroup )
5300 $groups['add'] = array_unique( $groups['add'] );
5301 $groups['remove'] = array_unique( $groups['remove'] );
5302 $groups['add-self'] = array_unique( $groups['add-self'] );
5303 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5309 * Deferred version of incEditCountImmediate()
5311 * This function, rather than incEditCountImmediate(), should be used for
5312 * most cases as it avoids potential deadlocks caused by concurrent editing.
5314 public function incEditCount() {
5315 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
5317 $this->incEditCountImmediate();
5324 * Increment the user's edit-count field.
5325 * Will have no effect for anonymous users.
5328 public function incEditCountImmediate() {
5329 if ( $this->isAnon() ) {
5333 $dbw = wfGetDB( DB_MASTER
);
5334 // No rows will be "affected" if user_editcount is NULL
5337 [ 'user_editcount=user_editcount+1' ],
5338 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5341 // Lazy initialization check...
5342 if ( $dbw->affectedRows() == 0 ) {
5343 // Now here's a goddamn hack...
5344 $dbr = wfGetDB( DB_REPLICA
);
5345 if ( $dbr !== $dbw ) {
5346 // If we actually have a replica DB server, the count is
5347 // at least one behind because the current transaction
5348 // has not been committed and replicated.
5349 $this->mEditCount
= $this->initEditCount( 1 );
5351 // But if DB_REPLICA is selecting the master, then the
5352 // count we just read includes the revision that was
5353 // just added in the working transaction.
5354 $this->mEditCount
= $this->initEditCount();
5357 if ( $this->mEditCount
=== null ) {
5358 $this->getEditCount();
5359 $dbr = wfGetDB( DB_REPLICA
);
5360 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
5362 $this->mEditCount++
;
5365 // Edit count in user cache too
5366 $this->invalidateCache();
5370 * Initialize user_editcount from data out of the revision table
5372 * @param int $add Edits to add to the count from the revision table
5373 * @return int Number of edits
5375 protected function initEditCount( $add = 0 ) {
5376 // Pull from a replica DB to be less cruel to servers
5377 // Accuracy isn't the point anyway here
5378 $dbr = wfGetDB( DB_REPLICA
);
5379 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5380 $count = (int)$dbr->selectField(
5381 [ 'revision' ] +
$actorWhere['tables'],
5383 [ $actorWhere['conds'] ],
5386 $actorWhere['joins']
5388 $count = $count +
$add;
5390 $dbw = wfGetDB( DB_MASTER
);
5393 [ 'user_editcount' => $count ],
5394 [ 'user_id' => $this->getId() ],
5402 * Get the description of a given right
5405 * @param string $right Right to query
5406 * @return string Localized description of the right
5408 public static function getRightDescription( $right ) {
5409 $key = "right-$right";
5410 $msg = wfMessage( $key );
5411 return $msg->isDisabled() ?
$right : $msg->text();
5415 * Get the name of a given grant
5418 * @param string $grant Grant to query
5419 * @return string Localized name of the grant
5421 public static function getGrantName( $grant ) {
5422 $key = "grant-$grant";
5423 $msg = wfMessage( $key );
5424 return $msg->isDisabled() ?
$grant : $msg->text();
5428 * Add a newuser log entry for this user.
5429 * Before 1.19 the return value was always true.
5431 * @deprecated since 1.27, AuthManager handles logging
5432 * @param string|bool $action Account creation type.
5433 * - String, one of the following values:
5434 * - 'create' for an anonymous user creating an account for himself.
5435 * This will force the action's performer to be the created user itself,
5436 * no matter the value of $wgUser
5437 * - 'create2' for a logged in user creating an account for someone else
5438 * - 'byemail' when the created user will receive its password by e-mail
5439 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5440 * - Boolean means whether the account was created by e-mail (deprecated):
5441 * - true will be converted to 'byemail'
5442 * - false will be converted to 'create' if this object is the same as
5443 * $wgUser and to 'create2' otherwise
5444 * @param string $reason User supplied reason
5447 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5448 return true; // disabled
5452 * Add an autocreate newuser log entry for this user
5453 * Used by things like CentralAuth and perhaps other authplugins.
5454 * Consider calling addNewUserLogEntry() directly instead.
5456 * @deprecated since 1.27, AuthManager handles logging
5459 public function addNewUserLogEntryAutoCreate() {
5460 $this->addNewUserLogEntry( 'autocreate' );
5466 * Load the user options either from cache, the database or an array
5468 * @param array|null $data Rows for the current user out of the user_properties table
5470 protected function loadOptions( $data = null ) {
5473 if ( $this->mOptionsLoaded
) {
5477 $this->mOptions
= self
::getDefaultOptions();
5479 if ( !$this->getId() ) {
5480 // For unlogged-in users, load language/variant options from request.
5481 // There's no need to do it for logged-in users: they can set preferences,
5482 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5483 // so don't override user's choice (especially when the user chooses site default).
5484 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5485 $this->mOptions
['variant'] = $variant;
5486 $this->mOptions
['language'] = $variant;
5487 $this->mOptionsLoaded
= true;
5491 // Maybe load from the object
5492 if ( !is_null( $this->mOptionOverrides
) ) {
5493 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5494 foreach ( $this->mOptionOverrides
as $key => $value ) {
5495 $this->mOptions
[$key] = $value;
5498 if ( !is_array( $data ) ) {
5499 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5500 // Load from database
5501 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5502 ?
wfGetDB( DB_MASTER
)
5503 : wfGetDB( DB_REPLICA
);
5505 $res = $dbr->select(
5507 [ 'up_property', 'up_value' ],
5508 [ 'up_user' => $this->getId() ],
5512 $this->mOptionOverrides
= [];
5514 foreach ( $res as $row ) {
5515 // Convert '0' to 0. PHP's boolean conversion considers them both
5516 // false, but e.g. JavaScript considers the former as true.
5517 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5518 // and convert all values here.
5519 if ( $row->up_value
=== '0' ) {
5522 $data[$row->up_property
] = $row->up_value
;
5526 foreach ( $data as $property => $value ) {
5527 $this->mOptionOverrides
[$property] = $value;
5528 $this->mOptions
[$property] = $value;
5532 // Replace deprecated language codes
5533 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5534 $this->mOptions
['language']
5537 $this->mOptionsLoaded
= true;
5539 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5543 * Saves the non-default options for this user, as previously set e.g. via
5544 * setOption(), in the database's "user_properties" (preferences) table.
5545 * Usually used via saveSettings().
5547 protected function saveOptions() {
5548 $this->loadOptions();
5550 // Not using getOptions(), to keep hidden preferences in database
5551 $saveOptions = $this->mOptions
;
5553 // Allow hooks to abort, for instance to save to a global profile.
5554 // Reset options to default state before saving.
5555 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5559 $userId = $this->getId();
5561 $insert_rows = []; // all the new preference rows
5562 foreach ( $saveOptions as $key => $value ) {
5563 // Don't bother storing default values
5564 $defaultOption = self
::getDefaultOption( $key );
5565 if ( ( $defaultOption === null && $value !== false && $value !== null )
5566 ||
$value != $defaultOption
5569 'up_user' => $userId,
5570 'up_property' => $key,
5571 'up_value' => $value,
5576 $dbw = wfGetDB( DB_MASTER
);
5578 $res = $dbw->select( 'user_properties',
5579 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5581 // Find prior rows that need to be removed or updated. These rows will
5582 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5584 foreach ( $res as $row ) {
5585 if ( !isset( $saveOptions[$row->up_property
] )
5586 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5588 $keysDelete[] = $row->up_property
;
5592 if ( count( $keysDelete ) ) {
5593 // Do the DELETE by PRIMARY KEY for prior rows.
5594 // In the past a very large portion of calls to this function are for setting
5595 // 'rememberpassword' for new accounts (a preference that has since been removed).
5596 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5597 // caused gap locks on [max user ID,+infinity) which caused high contention since
5598 // updates would pile up on each other as they are for higher (newer) user IDs.
5599 // It might not be necessary these days, but it shouldn't hurt either.
5600 $dbw->delete( 'user_properties',
5601 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5603 // Insert the new preference rows
5604 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5608 * Return the list of user fields that should be selected to create
5609 * a new user object.
5610 * @deprecated since 1.31, use self::getQueryInfo() instead.
5613 public static function selectFields() {
5614 wfDeprecated( __METHOD__
, '1.31' );
5622 'user_email_authenticated',
5624 'user_email_token_expires',
5625 'user_registration',
5631 * Return the tables, fields, and join conditions to be selected to create
5632 * a new user object.
5634 * @return array With three keys:
5635 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5636 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5637 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5639 public static function getQueryInfo() {
5640 global $wgActorTableSchemaMigrationStage;
5643 'tables' => [ 'user' ],
5651 'user_email_authenticated',
5653 'user_email_token_expires',
5654 'user_registration',
5659 if ( $wgActorTableSchemaMigrationStage > MIGRATION_OLD
) {
5660 $ret['tables']['user_actor'] = 'actor';
5661 $ret['fields'][] = 'user_actor.actor_id';
5662 $ret['joins']['user_actor'] = [
5663 $wgActorTableSchemaMigrationStage === MIGRATION_NEW ?
'JOIN' : 'LEFT JOIN',
5664 [ 'user_actor.actor_user = user_id' ]
5671 * Factory function for fatal permission-denied errors
5674 * @param string $permission User right required
5677 static function newFatalPermissionDeniedStatus( $permission ) {
5681 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5682 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5686 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5688 return Status
::newFatal( 'badaccess-group0' );
5693 * Get a new instance of this user that was loaded from the master via a locking read
5695 * Use this instead of the main context User when updating that user. This avoids races
5696 * where that user was loaded from a replica DB or even the master but without proper locks.
5698 * @return User|null Returns null if the user was not found in the DB
5701 public function getInstanceForUpdate() {
5702 if ( !$this->getId() ) {
5703 return null; // anon
5706 $user = self
::newFromId( $this->getId() );
5707 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5715 * Checks if two user objects point to the same user.
5717 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5718 * @param UserIdentity $user
5721 public function equals( UserIdentity
$user ) {
5722 // XXX it's not clear whether central ID providers are supposed to obey this
5723 return $this->getName() === $user->getName();