3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\Block\AbstractBlock
;
24 use MediaWiki\Block\DatabaseBlock
;
25 use MediaWiki\Block\SystemBlock
;
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Session\SessionManager
;
28 use MediaWiki\Session\Token
;
29 use MediaWiki\Auth\AuthManager
;
30 use MediaWiki\Auth\AuthenticationResponse
;
31 use MediaWiki\Auth\AuthenticationRequest
;
32 use MediaWiki\User\UserIdentity
;
33 use MediaWiki\Logger\LoggerFactory
;
34 use Wikimedia\Assert\Assert
;
36 use Wikimedia\ScopedCallback
;
37 use Wikimedia\Rdbms\Database
;
38 use Wikimedia\Rdbms\DBExpectedError
;
39 use Wikimedia\Rdbms\IDatabase
;
42 * The User object encapsulates all of the user-specific settings (user_id,
43 * name, rights, email address, options, last login time). Client
44 * classes use the getXXX() functions to access these fields. These functions
45 * do all the work of determining whether the user is logged in,
46 * whether the requested option can be satisfied from cookies or
47 * whether a database query is needed. Most of the settings needed
48 * for rendering normal pages are set in the cookie to minimize use
51 class User
implements IDBAccessObject
, UserIdentity
{
54 * Number of characters required for the user_token field.
56 const TOKEN_LENGTH
= 32;
59 * An invalid string value for the user_token field.
61 const INVALID_TOKEN
= '*** INVALID ***';
64 * Version number to tag cached versions of serialized User objects. Should be increased when
65 * {@link $mCacheVars} or one of it's members changes.
70 * Exclude user options that are set to their default value.
73 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
78 const CHECK_USER_RIGHTS
= true;
83 const IGNORE_USER_RIGHTS
= false;
86 * Array of Strings List of member variables which are saved to the
87 * shared cache (memcached). Any operation which changes the
88 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
114 * Array of Strings Core rights.
115 * Each of these should have a corresponding message of the form
120 protected static $mCoreRights = [
168 'move-categorypages',
169 'move-rootuserpages',
173 'override-export-depth',
195 'userrights-interwiki',
203 * @var string[] Cached results of getAllRights()
205 protected static $mAllRights = false;
207 /** Cache variables */
220 /** @var string TS_MW timestamp from the DB */
222 /** @var string TS_MW timestamp from cache */
223 protected $mQuickTouched;
227 public $mEmailAuthenticated;
229 protected $mEmailToken;
231 protected $mEmailTokenExpires;
233 protected $mRegistration;
235 protected $mEditCount;
236 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
237 protected $mGroupMemberships;
239 protected $mOptionOverrides;
244 * @var bool Whether the cache variables have been loaded.
246 public $mOptionsLoaded;
249 * @var array|bool Array with already loaded items or true if all items have been loaded.
251 protected $mLoadedItems = [];
255 * @var string Initialization data source if mLoadedItems!==true. May be one of:
256 * - 'defaults' anonymous user initialised from class defaults
257 * - 'name' initialise from mName
258 * - 'id' initialise from mId
259 * - 'actor' initialise from mActorId
260 * - 'session' log in from session if possible
262 * Use the User::newFrom*() family of functions to set this.
267 * Lazy-initialized variables, invalidated with clearInstanceCache
272 protected $mDatePreference;
280 protected $mBlockreason;
282 protected $mEffectiveGroups;
284 protected $mImplicitGroups;
286 protected $mFormerGroups;
287 /** @var AbstractBlock */
288 protected $mGlobalBlock;
296 /** @var WebRequest */
299 /** @var AbstractBlock */
303 protected $mAllowUsertalk;
305 /** @var AbstractBlock|bool */
306 private $mBlockedFromCreateAccount = false;
308 /** @var int User::READ_* constant bitfield used to load data */
309 protected $queryFlagsUsed = self
::READ_NORMAL
;
312 public static $idCacheByName = [];
315 * Lightweight constructor for an anonymous user.
316 * Use the User::newFrom* factory functions for other kinds of users.
320 * @see newFromActorId()
321 * @see newFromConfirmationCode()
322 * @see newFromSession()
325 public function __construct() {
326 $this->clearInstanceCache( 'defaults' );
332 public function __toString() {
333 return (string)$this->getName();
337 * Test if it's safe to load this User object.
339 * You should typically check this before using $wgUser or
340 * RequestContext::getUser in a method that might be called before the
341 * system has been fully initialized. If the object is unsafe, you should
342 * use an anonymous user:
344 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
350 public function isSafeToLoad() {
351 global $wgFullyInitialised;
353 // The user is safe to load if:
354 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
355 // * mLoadedItems === true (already loaded)
356 // * mFrom !== 'session' (sessions not involved at all)
358 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
359 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
363 * Load the user table data for this object from the source given by mFrom.
365 * @param int $flags User::READ_* constant bitfield
367 public function load( $flags = self
::READ_NORMAL
) {
368 global $wgFullyInitialised;
370 if ( $this->mLoadedItems
=== true ) {
374 // Set it now to avoid infinite recursion in accessors
375 $oldLoadedItems = $this->mLoadedItems
;
376 $this->mLoadedItems
= true;
377 $this->queryFlagsUsed
= $flags;
379 // If this is called too early, things are likely to break.
380 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
381 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
382 ->warning( 'User::loadFromSession called before the end of Setup.php', [
383 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
385 $this->loadDefaults();
386 $this->mLoadedItems
= $oldLoadedItems;
390 switch ( $this->mFrom
) {
392 $this->loadDefaults();
395 // Make sure this thread sees its own changes
396 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
397 if ( $lb->hasOrMadeRecentMasterChanges() ) {
398 $flags |
= self
::READ_LATEST
;
399 $this->queryFlagsUsed
= $flags;
402 $this->mId
= self
::idFromName( $this->mName
, $flags );
404 // Nonexistent user placeholder object
405 $this->loadDefaults( $this->mName
);
407 $this->loadFromId( $flags );
411 // Make sure this thread sees its own changes, if the ID isn't 0
412 if ( $this->mId
!= 0 ) {
413 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
414 if ( $lb->hasOrMadeRecentMasterChanges() ) {
415 $flags |
= self
::READ_LATEST
;
416 $this->queryFlagsUsed
= $flags;
420 $this->loadFromId( $flags );
423 // Make sure this thread sees its own changes
424 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
425 if ( $lb->hasOrMadeRecentMasterChanges() ) {
426 $flags |
= self
::READ_LATEST
;
427 $this->queryFlagsUsed
= $flags;
430 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
431 $row = wfGetDB( $index )->selectRow(
433 [ 'actor_user', 'actor_name' ],
434 [ 'actor_id' => $this->mActorId
],
441 $this->loadDefaults();
442 } elseif ( $row->actor_user
) {
443 $this->mId
= $row->actor_user
;
444 $this->loadFromId( $flags );
446 $this->loadDefaults( $row->actor_name
);
450 if ( !$this->loadFromSession() ) {
451 // Loading from session failed. Load defaults.
452 $this->loadDefaults();
454 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
457 throw new UnexpectedValueException(
458 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
463 * Load user table data, given mId has already been set.
464 * @param int $flags User::READ_* constant bitfield
465 * @return bool False if the ID does not exist, true otherwise
467 public function loadFromId( $flags = self
::READ_NORMAL
) {
468 if ( $this->mId
== 0 ) {
469 // Anonymous users are not in the database (don't need cache)
470 $this->loadDefaults();
474 // Try cache (unless this needs data from the master DB).
475 // NOTE: if this thread called saveSettings(), the cache was cleared.
476 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
478 if ( !$this->loadFromDatabase( $flags ) ) {
479 // Can't load from ID
483 $this->loadFromCache();
486 $this->mLoadedItems
= true;
487 $this->queryFlagsUsed
= $flags;
494 * @param string $wikiId
497 public static function purge( $wikiId, $userId ) {
498 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
499 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
500 $cache->delete( $key );
505 * @param WANObjectCache $cache
508 protected function getCacheKey( WANObjectCache
$cache ) {
509 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
511 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
515 * @param WANObjectCache $cache
519 public function getMutableCacheKeys( WANObjectCache
$cache ) {
520 $id = $this->getId();
522 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
526 * Load user data from shared cache, given mId has already been set.
531 protected function loadFromCache() {
532 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
533 $data = $cache->getWithSetCallback(
534 $this->getCacheKey( $cache ),
536 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
537 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
538 wfDebug( "User: cache miss for user {$this->mId}\n" );
540 $this->loadFromDatabase( self
::READ_NORMAL
);
542 $this->loadOptions();
545 foreach ( self
::$mCacheVars as $name ) {
546 $data[$name] = $this->$name;
549 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
551 // if a user group membership is about to expire, the cache needs to
552 // expire at that time (T163691)
553 foreach ( $this->mGroupMemberships
as $ugm ) {
554 if ( $ugm->getExpiry() ) {
555 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
556 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
557 $ttl = $secondsUntilExpiry;
564 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
567 // Restore from cache
568 foreach ( self
::$mCacheVars as $name ) {
569 $this->$name = $data[$name];
575 /** @name newFrom*() static factory methods */
579 * Static factory method for creation from username.
581 * This is slightly less efficient than newFromId(), so use newFromId() if
582 * you have both an ID and a name handy.
584 * @param string $name Username, validated by Title::newFromText()
585 * @param string|bool $validate Validate username. Takes the same parameters as
586 * User::getCanonicalName(), except that true is accepted as an alias
587 * for 'valid', for BC.
589 * @return User|bool User object, or false if the username is invalid
590 * (e.g. if it contains illegal characters or is an IP address). If the
591 * username is not present in the database, the result will be a user object
592 * with a name, zero user ID and default settings.
594 public static function newFromName( $name, $validate = 'valid' ) {
595 if ( $validate === true ) {
598 $name = self
::getCanonicalName( $name, $validate );
599 if ( $name === false ) {
603 // Create unloaded user object
607 $u->setItemLoaded( 'name' );
613 * Static factory method for creation from a given user ID.
615 * @param int $id Valid user ID
616 * @return User The corresponding User object
618 public static function newFromId( $id ) {
622 $u->setItemLoaded( 'id' );
627 * Static factory method for creation from a given actor ID.
630 * @param int $id Valid actor ID
631 * @return User The corresponding User object
633 public static function newFromActorId( $id ) {
634 global $wgActorTableSchemaMigrationStage;
636 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
637 // but it does little harm and might be needed for write callers loading a User.
638 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
639 throw new BadMethodCallException(
640 'Cannot use ' . __METHOD__
641 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
648 $u->setItemLoaded( 'actor' );
653 * Returns a User object corresponding to the given UserIdentity.
657 * @param UserIdentity $identity
661 public static function newFromIdentity( UserIdentity
$identity ) {
662 if ( $identity instanceof User
) {
666 return self
::newFromAnyId(
667 $identity->getId() === 0 ?
null : $identity->getId(),
668 $identity->getName() === '' ?
null : $identity->getName(),
669 $identity->getActorId() === 0 ?
null : $identity->getActorId()
674 * Static factory method for creation from an ID, name, and/or actor ID
676 * This does not check that the ID, name, and actor ID all correspond to
680 * @param int|null $userId User ID, if known
681 * @param string|null $userName User name, if known
682 * @param int|null $actorId Actor ID, if known
683 * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none
686 public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) {
687 global $wgActorTableSchemaMigrationStage;
689 // Stop-gap solution for the problem described in T222212.
690 // Force the User ID and Actor ID to zero for users loaded from the database
691 // of another wiki, to prevent subtle data corruption and confusing failure modes.
692 if ( $wikiId !== false ) {
698 $user->mFrom
= 'defaults';
700 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
701 // but it does little harm and might be needed for write callers loading a User.
702 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
703 $user->mActorId
= (int)$actorId;
704 if ( $user->mActorId
!== 0 ) {
705 $user->mFrom
= 'actor';
707 $user->setItemLoaded( 'actor' );
710 if ( $userName !== null && $userName !== '' ) {
711 $user->mName
= $userName;
712 $user->mFrom
= 'name';
713 $user->setItemLoaded( 'name' );
716 if ( $userId !== null ) {
717 $user->mId
= (int)$userId;
718 if ( $user->mId
!== 0 ) {
721 $user->setItemLoaded( 'id' );
724 if ( $user->mFrom
=== 'defaults' ) {
725 throw new InvalidArgumentException(
726 'Cannot create a user with no name, no ID, and no actor ID'
734 * Factory method to fetch whichever user has a given email confirmation code.
735 * This code is generated when an account is created or its e-mail address
738 * If the code is invalid or has expired, returns NULL.
740 * @param string $code Confirmation code
741 * @param int $flags User::READ_* bitfield
744 public static function newFromConfirmationCode( $code, $flags = 0 ) {
745 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
746 ?
wfGetDB( DB_MASTER
)
747 : wfGetDB( DB_REPLICA
);
749 $id = $db->selectField(
753 'user_email_token' => md5( $code ),
754 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
758 return $id ? self
::newFromId( $id ) : null;
762 * Create a new user object using data from session. If the login
763 * credentials are invalid, the result is an anonymous user.
765 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
768 public static function newFromSession( WebRequest
$request = null ) {
770 $user->mFrom
= 'session';
771 $user->mRequest
= $request;
776 * Create a new user object from a user row.
777 * The row should have the following fields from the user table in it:
778 * - either user_name or user_id to load further data if needed (or both)
780 * - all other fields (email, etc.)
781 * It is useless to provide the remaining fields if either user_id,
782 * user_name and user_real_name are not provided because the whole row
783 * will be loaded once more from the database when accessing them.
785 * @param stdClass $row A row from the user table
786 * @param array|null $data Further data to load into the object
787 * (see User::loadFromRow for valid keys)
790 public static function newFromRow( $row, $data = null ) {
792 $user->loadFromRow( $row, $data );
797 * Static factory method for creation of a "system" user from username.
799 * A "system" user is an account that's used to attribute logged actions
800 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
801 * might include the 'Maintenance script' or 'Conversion script' accounts
802 * used by various scripts in the maintenance/ directory or accounts such
803 * as 'MediaWiki message delivery' used by the MassMessage extension.
805 * This can optionally create the user if it doesn't exist, and "steal" the
806 * account if it does exist.
808 * "Stealing" an existing user is intended to make it impossible for normal
809 * authentication processes to use the account, effectively disabling the
810 * account for normal use:
811 * - Email is invalidated, to prevent account recovery by emailing a
812 * temporary password and to disassociate the account from the existing
814 * - The token is set to a magic invalid value, to kill existing sessions
815 * and to prevent $this->setToken() calls from resetting the token to a
817 * - SessionManager is instructed to prevent new sessions for the user, to
818 * do things like deauthorizing OAuth consumers.
819 * - AuthManager is instructed to revoke access, to invalidate or remove
820 * passwords and other credentials.
822 * @param string $name Username
823 * @param array $options Options are:
824 * - validate: As for User::getCanonicalName(), default 'valid'
825 * - create: Whether to create the user if it doesn't already exist, default true
826 * - steal: Whether to "disable" the account for normal use if it already
827 * exists, default false
831 public static function newSystemUser( $name, $options = [] ) {
833 'validate' => 'valid',
838 $name = self
::getCanonicalName( $name, $options['validate'] );
839 if ( $name === false ) {
843 $dbr = wfGetDB( DB_REPLICA
);
844 $userQuery = self
::getQueryInfo();
845 $row = $dbr->selectRow(
846 $userQuery['tables'],
847 $userQuery['fields'],
848 [ 'user_name' => $name ],
854 // Try the master database...
855 $dbw = wfGetDB( DB_MASTER
);
856 $row = $dbw->selectRow(
857 $userQuery['tables'],
858 $userQuery['fields'],
859 [ 'user_name' => $name ],
867 // No user. Create it?
868 return $options['create']
869 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
873 $user = self
::newFromRow( $row );
875 // A user is considered to exist as a non-system user if it can
876 // authenticate, or has an email set, or has a non-invalid token.
877 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
878 AuthManager
::singleton()->userCanAuthenticate( $name )
880 // User exists. Steal it?
881 if ( !$options['steal'] ) {
885 AuthManager
::singleton()->revokeAccessForUser( $name );
887 $user->invalidateEmail();
888 $user->mToken
= self
::INVALID_TOKEN
;
889 $user->saveSettings();
890 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
899 * Get the username corresponding to a given user ID
900 * @param int $id User ID
901 * @return string|bool The corresponding username
903 public static function whoIs( $id ) {
904 return UserCache
::singleton()->getProp( $id, 'name' );
908 * Get the real name of a user given their user ID
910 * @param int $id User ID
911 * @return string|bool The corresponding user's real name
913 public static function whoIsReal( $id ) {
914 return UserCache
::singleton()->getProp( $id, 'real_name' );
918 * Get database id given a user name
919 * @param string $name Username
920 * @param int $flags User::READ_* constant bitfield
921 * @return int|null The corresponding user's ID, or null if user is nonexistent
923 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
924 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
925 $name = (string)$name;
926 $nt = Title
::makeTitleSafe( NS_USER
, $name );
927 if ( is_null( $nt ) ) {
932 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
933 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
936 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
937 $db = wfGetDB( $index );
942 [ 'user_name' => $nt->getText() ],
947 if ( $s === false ) {
950 $result = (int)$s->user_id
;
953 if ( count( self
::$idCacheByName ) >= 1000 ) {
954 self
::$idCacheByName = [];
957 self
::$idCacheByName[$name] = $result;
963 * Reset the cache used in idFromName(). For use in tests.
965 public static function resetIdByNameCache() {
966 self
::$idCacheByName = [];
970 * Does the string match an anonymous IP address?
972 * This function exists for username validation, in order to reject
973 * usernames which are similar in form to IP addresses. Strings such
974 * as 300.300.300.300 will return true because it looks like an IP
975 * address, despite not being strictly valid.
977 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
978 * address because the usemod software would "cloak" anonymous IP
979 * addresses like this, if we allowed accounts like this to be created
980 * new users could get the old edits of these anonymous users.
982 * @param string $name Name to match
985 public static function isIP( $name ) {
986 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
987 || IP
::isIPv6( $name );
991 * Is the user an IP range?
996 public function isIPRange() {
997 return IP
::isValidRange( $this->mName
);
1001 * Is the input a valid username?
1003 * Checks if the input is a valid username, we don't want an empty string,
1004 * an IP address, anything that contains slashes (would mess up subpages),
1005 * is longer than the maximum allowed username size or doesn't begin with
1008 * @param string $name Name to match
1011 public static function isValidUserName( $name ) {
1012 global $wgMaxNameChars;
1015 || self
::isIP( $name )
1016 ||
strpos( $name, '/' ) !== false
1017 ||
strlen( $name ) > $wgMaxNameChars
1018 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
1023 // Ensure that the name can't be misresolved as a different title,
1024 // such as with extra namespace keys at the start.
1025 $parsed = Title
::newFromText( $name );
1026 if ( is_null( $parsed )
1027 ||
$parsed->getNamespace()
1028 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1032 // Check an additional blacklist of troublemaker characters.
1033 // Should these be merged into the title char list?
1034 $unicodeBlacklist = '/[' .
1035 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1036 '\x{00a0}' . # non-breaking space
1037 '\x{2000}-\x{200f}' . # various whitespace
1038 '\x{2028}-\x{202f}' . # breaks and control chars
1039 '\x{3000}' . # ideographic space
1040 '\x{e000}-\x{f8ff}' . # private use
1042 if ( preg_match( $unicodeBlacklist, $name ) ) {
1050 * Usernames which fail to pass this function will be blocked
1051 * from user login and new account registrations, but may be used
1052 * internally by batch processes.
1054 * If an account already exists in this form, login will be blocked
1055 * by a failure to pass this function.
1057 * @param string $name Name to match
1060 public static function isUsableName( $name ) {
1061 global $wgReservedUsernames;
1062 // Must be a valid username, obviously ;)
1063 if ( !self
::isValidUserName( $name ) ) {
1067 static $reservedUsernames = false;
1068 if ( !$reservedUsernames ) {
1069 $reservedUsernames = $wgReservedUsernames;
1070 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1073 // Certain names may be reserved for batch processes.
1074 foreach ( $reservedUsernames as $reserved ) {
1075 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1076 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1078 if ( $reserved == $name ) {
1086 * Return the users who are members of the given group(s). In case of multiple groups,
1087 * users who are members of at least one of them are returned.
1089 * @param string|array $groups A single group name or an array of group names
1090 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1091 * records; larger values are ignored.
1092 * @param int|null $after ID the user to start after
1093 * @return UserArrayFromResult
1095 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1096 if ( $groups === [] ) {
1097 return UserArrayFromResult
::newFromIDs( [] );
1100 $groups = array_unique( (array)$groups );
1101 $limit = min( 5000, $limit );
1103 $conds = [ 'ug_group' => $groups ];
1104 if ( $after !== null ) {
1105 $conds[] = 'ug_user > ' . (int)$after;
1108 $dbr = wfGetDB( DB_REPLICA
);
1109 $ids = $dbr->selectFieldValues(
1116 'ORDER BY' => 'ug_user',
1120 return UserArray
::newFromIDs( $ids );
1124 * Usernames which fail to pass this function will be blocked
1125 * from new account registrations, but may be used internally
1126 * either by batch processes or by user accounts which have
1127 * already been created.
1129 * Additional blacklisting may be added here rather than in
1130 * isValidUserName() to avoid disrupting existing accounts.
1132 * @param string $name String to match
1135 public static function isCreatableName( $name ) {
1136 global $wgInvalidUsernameCharacters;
1138 // Ensure that the username isn't longer than 235 bytes, so that
1139 // (at least for the builtin skins) user javascript and css files
1140 // will work. (T25080)
1141 if ( strlen( $name ) > 235 ) {
1142 wfDebugLog( 'username', __METHOD__
.
1143 ": '$name' invalid due to length" );
1147 // Preg yells if you try to give it an empty string
1148 if ( $wgInvalidUsernameCharacters !== '' &&
1149 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1151 wfDebugLog( 'username', __METHOD__
.
1152 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1156 return self
::isUsableName( $name );
1160 * Is the input a valid password for this user?
1162 * @param string $password Desired password
1165 public function isValidPassword( $password ) {
1166 // simple boolean wrapper for checkPasswordValidity
1167 return $this->checkPasswordValidity( $password )->isGood();
1171 * Check if this is a valid password for this user
1173 * Returns a Status object with a set of messages describing
1174 * problems with the password. If the return status is fatal,
1175 * the action should be refused and the password should not be
1176 * checked at all (this is mainly meant for DoS mitigation).
1177 * If the return value is OK but not good, the password can be checked,
1178 * but the user should not be able to set their password to this.
1179 * The value of the returned Status object will be an array which
1180 * can have the following fields:
1181 * - forceChange (bool): if set to true, the user should not be
1182 * allowed to log with this password unless they change it during
1183 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1184 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1185 * a password change on login.
1187 * @param string $password Desired password
1191 public function checkPasswordValidity( $password ) {
1192 global $wgPasswordPolicy;
1194 $upp = new UserPasswordPolicy(
1195 $wgPasswordPolicy['policies'],
1196 $wgPasswordPolicy['checks']
1199 $status = Status
::newGood( [] );
1200 $result = false; // init $result to false for the internal checks
1202 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1203 $status->error( $result );
1207 if ( $result === false ) {
1208 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1212 if ( $result === true ) {
1216 $status->error( $result );
1217 return $status; // the isValidPassword hook set a string $result and returned true
1221 * Given unvalidated user input, return a canonical username, or false if
1222 * the username is invalid.
1223 * @param string $name User input
1224 * @param string|bool $validate Type of validation to use:
1225 * - false No validation
1226 * - 'valid' Valid for batch processes
1227 * - 'usable' Valid for batch processes and login
1228 * - 'creatable' Valid for batch processes, login and account creation
1230 * @throws InvalidArgumentException
1231 * @return bool|string
1233 public static function getCanonicalName( $name, $validate = 'valid' ) {
1234 // Force usernames to capital
1235 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1237 # Reject names containing '#'; these will be cleaned up
1238 # with title normalisation, but then it's too late to
1240 if ( strpos( $name, '#' ) !== false ) {
1244 // Clean up name according to title rules,
1245 // but only when validation is requested (T14654)
1246 $t = ( $validate !== false ) ?
1247 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1248 // Check for invalid titles
1249 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1253 $name = $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 * Set cached properties to default.
1283 * @note This no longer clears uncached lazy-initialised properties;
1284 * the constructor does that instead.
1286 * @param string|bool $name
1288 public function loadDefaults( $name = false ) {
1290 $this->mName
= $name;
1291 $this->mActorId
= null;
1292 $this->mRealName
= '';
1294 $this->mOptionOverrides
= null;
1295 $this->mOptionsLoaded
= false;
1297 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1298 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1299 if ( $loggedOut !== 0 ) {
1300 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1302 $this->mTouched
= '1'; # Allow any pages to be cached
1305 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1306 $this->mEmailAuthenticated
= null;
1307 $this->mEmailToken
= '';
1308 $this->mEmailTokenExpires
= null;
1309 $this->mRegistration
= wfTimestamp( TS_MW
);
1310 $this->mGroupMemberships
= [];
1312 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1316 * Return whether an item has been loaded.
1318 * @param string $item Item to check. Current possibilities:
1322 * @param string $all 'all' to check if the whole object has been loaded
1323 * or any other string to check if only the item is available (e.g.
1327 public function isItemLoaded( $item, $all = 'all' ) {
1328 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1329 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1333 * Set that an item has been loaded
1335 * @param string $item
1337 protected function setItemLoaded( $item ) {
1338 if ( is_array( $this->mLoadedItems
) ) {
1339 $this->mLoadedItems
[$item] = true;
1344 * Load user data from the session.
1346 * @return bool True if the user is logged in, false otherwise.
1348 private function loadFromSession() {
1349 // MediaWiki\Session\Session already did the necessary authentication of the user
1350 // returned here, so just use it if applicable.
1351 $session = $this->getRequest()->getSession();
1352 $user = $session->getUser();
1353 if ( $user->isLoggedIn() ) {
1354 $this->loadFromUserObject( $user );
1356 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1357 // every session load, because an autoblocked editor might not edit again from the same
1358 // IP address after being blocked.
1359 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1361 // Other code expects these to be set in the session, so set them.
1362 $session->set( 'wsUserID', $this->getId() );
1363 $session->set( 'wsUserName', $this->getName() );
1364 $session->set( 'wsToken', $this->getToken() );
1373 * Set the 'BlockID' cookie depending on block type and user authentication status.
1375 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
1377 public function trackBlockWithCookie() {
1378 MediaWikiServices
::getInstance()->getBlockManager()->trackBlockWithCookie( $this );
1382 * Load user and user_group data from the database.
1383 * $this->mId must be set, this is how the user is identified.
1385 * @param int $flags User::READ_* constant bitfield
1386 * @return bool True if the user exists, false if the user is anonymous
1388 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1390 $this->mId
= intval( $this->mId
);
1392 if ( !$this->mId
) {
1393 // Anonymous users are not in the database
1394 $this->loadDefaults();
1398 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1399 $db = wfGetDB( $index );
1401 $userQuery = self
::getQueryInfo();
1402 $s = $db->selectRow(
1403 $userQuery['tables'],
1404 $userQuery['fields'],
1405 [ 'user_id' => $this->mId
],
1411 $this->queryFlagsUsed
= $flags;
1412 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1414 if ( $s !== false ) {
1415 // Initialise user table data
1416 $this->loadFromRow( $s );
1417 $this->mGroupMemberships
= null; // deferred
1418 $this->getEditCount(); // revalidation for nulls
1424 $this->loadDefaults();
1430 * Initialize this object from a row from the user table.
1432 * @param stdClass $row Row from the user table to load.
1433 * @param array|null $data Further user data to load into the object
1435 * user_groups Array of arrays or stdClass result rows out of the user_groups
1436 * table. Previously you were supposed to pass an array of strings
1437 * here, but we also need expiry info nowadays, so an array of
1438 * strings is ignored.
1439 * user_properties Array with properties out of the user_properties table
1441 protected function loadFromRow( $row, $data = null ) {
1442 global $wgActorTableSchemaMigrationStage;
1444 if ( !is_object( $row ) ) {
1445 throw new InvalidArgumentException( '$row must be an object' );
1450 $this->mGroupMemberships
= null; // deferred
1452 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1453 // but it does little harm and might be needed for write callers loading a User.
1454 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1455 if ( isset( $row->actor_id
) ) {
1456 $this->mActorId
= (int)$row->actor_id
;
1457 if ( $this->mActorId
!== 0 ) {
1458 $this->mFrom
= 'actor';
1460 $this->setItemLoaded( 'actor' );
1466 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1467 $this->mName
= $row->user_name
;
1468 $this->mFrom
= 'name';
1469 $this->setItemLoaded( 'name' );
1474 if ( isset( $row->user_real_name
) ) {
1475 $this->mRealName
= $row->user_real_name
;
1476 $this->setItemLoaded( 'realname' );
1481 if ( isset( $row->user_id
) ) {
1482 $this->mId
= intval( $row->user_id
);
1483 if ( $this->mId
!== 0 ) {
1484 $this->mFrom
= 'id';
1486 $this->setItemLoaded( 'id' );
1491 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1492 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1495 if ( isset( $row->user_editcount
) ) {
1496 $this->mEditCount
= $row->user_editcount
;
1501 if ( isset( $row->user_touched
) ) {
1502 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1507 if ( isset( $row->user_token
) ) {
1508 // The definition for the column is binary(32), so trim the NULs
1509 // that appends. The previous definition was char(32), so trim
1511 $this->mToken
= rtrim( $row->user_token
, " \0" );
1512 if ( $this->mToken
=== '' ) {
1513 $this->mToken
= null;
1519 if ( isset( $row->user_email
) ) {
1520 $this->mEmail
= $row->user_email
;
1521 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1522 $this->mEmailToken
= $row->user_email_token
;
1523 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1524 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1530 $this->mLoadedItems
= true;
1533 if ( is_array( $data ) ) {
1534 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1535 if ( $data['user_groups'] === [] ) {
1536 $this->mGroupMemberships
= [];
1538 $firstGroup = reset( $data['user_groups'] );
1539 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1540 $this->mGroupMemberships
= [];
1541 foreach ( $data['user_groups'] as $row ) {
1542 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1543 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1548 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1549 $this->loadOptions( $data['user_properties'] );
1555 * Load the data for this user object from another user object.
1559 protected function loadFromUserObject( $user ) {
1561 foreach ( self
::$mCacheVars as $var ) {
1562 $this->$var = $user->$var;
1567 * Load the groups from the database if they aren't already loaded.
1569 private function loadGroups() {
1570 if ( is_null( $this->mGroupMemberships
) ) {
1571 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1572 ?
wfGetDB( DB_MASTER
)
1573 : wfGetDB( DB_REPLICA
);
1574 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1580 * Add the user to the group if he/she meets given criteria.
1582 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1583 * possible to remove manually via Special:UserRights. In such case it
1584 * will not be re-added automatically. The user will also not lose the
1585 * group if they no longer meet the criteria.
1587 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1589 * @return array Array of groups the user has been promoted to.
1591 * @see $wgAutopromoteOnce
1593 public function addAutopromoteOnceGroups( $event ) {
1594 global $wgAutopromoteOnceLogInRC;
1596 if ( wfReadOnly() ||
!$this->getId() ) {
1600 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1601 if ( $toPromote === [] ) {
1605 if ( !$this->checkAndSetTouched() ) {
1606 return []; // raced out (bug T48834)
1609 $oldGroups = $this->getGroups(); // previous groups
1610 $oldUGMs = $this->getGroupMemberships();
1611 foreach ( $toPromote as $group ) {
1612 $this->addGroup( $group );
1614 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1615 $newUGMs = $this->getGroupMemberships();
1617 // update groups in external authentication database
1618 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1620 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1621 $logEntry->setPerformer( $this );
1622 $logEntry->setTarget( $this->getUserPage() );
1623 $logEntry->setParameters( [
1624 '4::oldgroups' => $oldGroups,
1625 '5::newgroups' => $newGroups,
1627 $logid = $logEntry->insert();
1628 if ( $wgAutopromoteOnceLogInRC ) {
1629 $logEntry->publish( $logid );
1636 * Builds update conditions. Additional conditions may be added to $conditions to
1637 * protected against race conditions using a compare-and-set (CAS) mechanism
1638 * based on comparing $this->mTouched with the user_touched field.
1640 * @param IDatabase $db
1641 * @param array $conditions WHERE conditions for use with Database::update
1642 * @return array WHERE conditions for use with Database::update
1644 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1645 if ( $this->mTouched
) {
1646 // CAS check: only update if the row wasn't changed sicne it was loaded.
1647 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1654 * Bump user_touched if it didn't change since this object was loaded
1656 * On success, the mTouched field is updated.
1657 * The user serialization cache is always cleared.
1659 * @return bool Whether user_touched was actually updated
1662 protected function checkAndSetTouched() {
1665 if ( !$this->mId
) {
1666 return false; // anon
1669 // Get a new user_touched that is higher than the old one
1670 $newTouched = $this->newTouchedTimestamp();
1672 $dbw = wfGetDB( DB_MASTER
);
1673 $dbw->update( 'user',
1674 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1675 $this->makeUpdateConditions( $dbw, [
1676 'user_id' => $this->mId
,
1680 $success = ( $dbw->affectedRows() > 0 );
1683 $this->mTouched
= $newTouched;
1684 $this->clearSharedCache( 'changed' );
1686 // Clears on failure too since that is desired if the cache is stale
1687 $this->clearSharedCache( 'refresh' );
1694 * Clear various cached data stored in this object. The cache of the user table
1695 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1697 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1698 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1700 public function clearInstanceCache( $reloadFrom = false ) {
1701 $this->mNewtalk
= -1;
1702 $this->mDatePreference
= null;
1703 $this->mBlockedby
= -1; # Unset
1704 $this->mHash
= false;
1705 $this->mRights
= null;
1706 $this->mEffectiveGroups
= null;
1707 $this->mImplicitGroups
= null;
1708 $this->mGroupMemberships
= null;
1709 $this->mOptions
= null;
1710 $this->mOptionsLoaded
= false;
1711 $this->mEditCount
= null;
1713 if ( $reloadFrom ) {
1714 $this->mLoadedItems
= [];
1715 $this->mFrom
= $reloadFrom;
1719 /** @var array|null */
1720 private static $defOpt = null;
1721 /** @var string|null */
1722 private static $defOptLang = null;
1725 * Reset the process cache of default user options. This is only necessary
1726 * if the wiki configuration has changed since defaults were calculated,
1727 * and as such should only be performed inside the testing suite that
1728 * regularly changes wiki configuration.
1730 public static function resetGetDefaultOptionsForTestsOnly() {
1731 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1732 self
::$defOpt = null;
1733 self
::$defOptLang = null;
1737 * Combine the language default options with any site-specific options
1738 * and add the default language variants.
1740 * @return array Array of String options
1742 public static function getDefaultOptions() {
1743 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1745 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1746 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1747 // The content language does not change (and should not change) mid-request, but the
1748 // unit tests change it anyway, and expect this method to return values relevant to the
1749 // current content language.
1750 return self
::$defOpt;
1753 self
::$defOpt = $wgDefaultUserOptions;
1754 // Default language setting
1755 self
::$defOptLang = $contLang->getCode();
1756 self
::$defOpt['language'] = self
::$defOptLang;
1757 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1758 if ( $langCode === $contLang->getCode() ) {
1759 self
::$defOpt['variant'] = $langCode;
1761 self
::$defOpt["variant-$langCode"] = $langCode;
1765 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1766 // since extensions may change the set of searchable namespaces depending
1767 // on user groups/permissions.
1768 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1769 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1771 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1773 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1775 return self
::$defOpt;
1779 * Get a given default option value.
1781 * @param string $opt Name of option to retrieve
1782 * @return string Default option value
1784 public static function getDefaultOption( $opt ) {
1785 $defOpts = self
::getDefaultOptions();
1786 return $defOpts[$opt] ??
null;
1790 * Get blocking information
1792 * TODO: Move this into the BlockManager, along with block-related properties.
1794 * @param bool $fromReplica Whether to check the replica DB first.
1795 * To improve performance, non-critical checks are done against replica DBs.
1796 * Check when actually saving should be done against master.
1798 private function getBlockedStatus( $fromReplica = true ) {
1799 if ( $this->mBlockedby
!= -1 ) {
1803 wfDebug( __METHOD__
. ": checking...\n" );
1805 // Initialize data...
1806 // Otherwise something ends up stomping on $this->mBlockedby when
1807 // things get lazy-loaded later, causing false positive block hits
1808 // due to -1 !== 0. Probably session-related... Nothing should be
1809 // overwriting mBlockedby, surely?
1812 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1818 $this->mBlock
= $block;
1819 $this->mBlockedby
= $block->getByName();
1820 $this->mBlockreason
= $block->getReason();
1821 $this->mHideName
= $block->getHideName();
1822 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1824 $this->mBlock
= null;
1825 $this->mBlockedby
= '';
1826 $this->mBlockreason
= '';
1827 $this->mHideName
= 0;
1828 $this->mAllowUsertalk
= false;
1831 // Avoid PHP 7.1 warning of passing $this by reference
1834 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1838 * Whether the given IP is in a DNS blacklist.
1840 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1841 * @param string $ip IP to check
1842 * @param bool $checkWhitelist Whether to check the whitelist first
1843 * @return bool True if blacklisted.
1845 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1846 return MediaWikiServices
::getInstance()->getBlockManager()
1847 ->isDnsBlacklisted( $ip, $checkWhitelist );
1851 * Whether the given IP is in a given DNS blacklist.
1853 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1854 * @param string $ip IP to check
1855 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1856 * @return bool True if blacklisted.
1858 public function inDnsBlacklist( $ip, $bases ) {
1859 wfDeprecated( __METHOD__
, '1.34' );
1862 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1863 if ( IP
::isIPv4( $ip ) ) {
1864 // Reverse IP, T23255
1865 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1867 foreach ( (array)$bases as $base ) {
1869 // If we have an access key, use that too (ProjectHoneypot, etc.)
1871 if ( is_array( $base ) ) {
1872 if ( count( $base ) >= 2 ) {
1873 // Access key is 1, base URL is 0
1874 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1876 $host = "$ipReversed.{$base[0]}";
1878 $basename = $base[0];
1880 $host = "$ipReversed.$base";
1884 $ipList = gethostbynamel( $host );
1887 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1892 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1900 * Check if an IP address is in the local proxy list
1902 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1906 public static function isLocallyBlockedProxy( $ip ) {
1907 wfDeprecated( __METHOD__
, '1.34' );
1909 global $wgProxyList;
1911 if ( !$wgProxyList ) {
1915 if ( !is_array( $wgProxyList ) ) {
1916 // Load values from the specified file
1917 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1920 $resultProxyList = [];
1921 $deprecatedIPEntries = [];
1923 // backward compatibility: move all ip addresses in keys to values
1924 foreach ( $wgProxyList as $key => $value ) {
1925 $keyIsIP = IP
::isIPAddress( $key );
1926 $valueIsIP = IP
::isIPAddress( $value );
1927 if ( $keyIsIP && !$valueIsIP ) {
1928 $deprecatedIPEntries[] = $key;
1929 $resultProxyList[] = $key;
1930 } elseif ( $keyIsIP && $valueIsIP ) {
1931 $deprecatedIPEntries[] = $key;
1932 $resultProxyList[] = $key;
1933 $resultProxyList[] = $value;
1935 $resultProxyList[] = $value;
1939 if ( $deprecatedIPEntries ) {
1941 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1942 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1945 $proxyListIPSet = new IPSet( $resultProxyList );
1946 return $proxyListIPSet->match( $ip );
1950 * Is this user subject to rate limiting?
1952 * @return bool True if rate limited
1954 public function isPingLimitable() {
1955 global $wgRateLimitsExcludedIPs;
1956 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1957 // No other good way currently to disable rate limits
1958 // for specific IPs. :P
1959 // But this is a crappy hack and should die.
1962 return !$this->isAllowed( 'noratelimit' );
1966 * Primitive rate limits: enforce maximum actions per time period
1967 * to put a brake on flooding.
1969 * The method generates both a generic profiling point and a per action one
1970 * (suffix being "-$action".
1972 * @note When using a shared cache like memcached, IP-address
1973 * last-hit counters will be shared across wikis.
1975 * @param string $action Action to enforce; 'edit' if unspecified
1976 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1977 * @return bool True if a rate limiter was tripped
1979 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1980 // Avoid PHP 7.1 warning of passing $this by reference
1982 // Call the 'PingLimiter' hook
1984 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1988 global $wgRateLimits;
1989 if ( !isset( $wgRateLimits[$action] ) ) {
1993 $limits = array_merge(
1994 [ '&can-bypass' => true ],
1995 $wgRateLimits[$action]
1998 // Some groups shouldn't trigger the ping limiter, ever
1999 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2004 $id = $this->getId();
2006 $isNewbie = $this->isNewbie();
2007 $cache = ObjectCache
::getLocalClusterInstance();
2011 if ( isset( $limits['anon'] ) ) {
2012 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2014 } elseif ( isset( $limits['user'] ) ) {
2015 // limits for logged-in users
2016 $userLimit = $limits['user'];
2019 // limits for anons and for newbie logged-in users
2022 if ( isset( $limits['ip'] ) ) {
2023 $ip = $this->getRequest()->getIP();
2024 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2026 // subnet-based limits
2027 if ( isset( $limits['subnet'] ) ) {
2028 $ip = $this->getRequest()->getIP();
2029 $subnet = IP
::getSubnet( $ip );
2030 if ( $subnet !== false ) {
2031 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2036 // Check for group-specific permissions
2037 // If more than one group applies, use the group with the highest limit ratio (max/period)
2038 foreach ( $this->getGroups() as $group ) {
2039 if ( isset( $limits[$group] ) ) {
2040 if ( $userLimit === false
2041 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2043 $userLimit = $limits[$group];
2048 // limits for newbie logged-in users (override all the normal user limits)
2049 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2050 $userLimit = $limits['newbie'];
2053 // Set the user limit key
2054 if ( $userLimit !== false ) {
2055 // phan is confused because &can-bypass's value is a bool, so it assumes
2056 // that $userLimit is also a bool here.
2057 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2058 list( $max, $period ) = $userLimit;
2059 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2060 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2063 // ip-based limits for all ping-limitable users
2064 if ( isset( $limits['ip-all'] ) ) {
2065 $ip = $this->getRequest()->getIP();
2066 // ignore if user limit is more permissive
2067 if ( $isNewbie ||
$userLimit === false
2068 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2069 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2073 // subnet-based limits for all ping-limitable users
2074 if ( isset( $limits['subnet-all'] ) ) {
2075 $ip = $this->getRequest()->getIP();
2076 $subnet = IP
::getSubnet( $ip );
2077 if ( $subnet !== false ) {
2078 // ignore if user limit is more permissive
2079 if ( $isNewbie ||
$userLimit === false
2080 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2081 > $userLimit[0] / $userLimit[1] ) {
2082 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2088 foreach ( $keys as $key => $limit ) {
2089 // phan is confused because &can-bypass's value is a bool, so it assumes
2090 // that $userLimit is also a bool here.
2091 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2092 list( $max, $period ) = $limit;
2093 $summary = "(limit $max in {$period}s)";
2094 $count = $cache->get( $key );
2097 if ( $count >= $max ) {
2098 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2099 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2102 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2105 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2106 if ( $incrBy > 0 ) {
2107 $cache->add( $key, 0, intval( $period ) ); // first ping
2110 if ( $incrBy > 0 ) {
2111 $cache->incr( $key, $incrBy );
2119 * Check if user is blocked
2121 * @deprecated since 1.34, use User::getBlock() or
2122 * PermissionManager::isBlockedFrom() or
2123 * PermissionManager::userCan() instead.
2125 * @param bool $fromReplica Whether to check the replica DB instead of
2126 * the master. Hacked from false due to horrible probs on site.
2127 * @return bool True if blocked, false otherwise
2129 public function isBlocked( $fromReplica = true ) {
2130 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2131 $this->getBlock()->appliesToRight( 'edit' );
2135 * Get the block affecting the user, or null if the user is not blocked
2137 * @param bool $fromReplica Whether to check the replica DB instead of the master
2138 * @return AbstractBlock|null
2140 public function getBlock( $fromReplica = true ) {
2141 $this->getBlockedStatus( $fromReplica );
2142 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2146 * Check if user is blocked from editing a particular article
2148 * @param Title $title Title to check
2149 * @param bool $fromReplica Whether to check the replica DB instead of the master
2151 * @throws MWException
2153 * @deprecated since 1.33,
2154 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2157 public function isBlockedFrom( $title, $fromReplica = false ) {
2158 return MediaWikiServices
::getInstance()->getPermissionManager()
2159 ->isBlockedFrom( $this, $title, $fromReplica );
2163 * If user is blocked, return the name of the user who placed the block
2164 * @return string Name of blocker
2166 public function blockedBy() {
2167 $this->getBlockedStatus();
2168 return $this->mBlockedby
;
2172 * If user is blocked, return the specified reason for the block
2173 * @return string Blocking reason
2175 public function blockedFor() {
2176 $this->getBlockedStatus();
2177 return $this->mBlockreason
;
2181 * If user is blocked, return the ID for the block
2182 * @return int Block ID
2184 public function getBlockId() {
2185 $this->getBlockedStatus();
2186 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2190 * Check if user is blocked on all wikis.
2191 * Do not use for actual edit permission checks!
2192 * This is intended for quick UI checks.
2194 * @param string $ip IP address, uses current client if none given
2195 * @return bool True if blocked, false otherwise
2197 public function isBlockedGlobally( $ip = '' ) {
2198 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2202 * Check if user is blocked on all wikis.
2203 * Do not use for actual edit permission checks!
2204 * This is intended for quick UI checks.
2206 * @param string $ip IP address, uses current client if none given
2207 * @return AbstractBlock|null Block object if blocked, null otherwise
2208 * @throws FatalError
2209 * @throws MWException
2211 public function getGlobalBlock( $ip = '' ) {
2212 if ( $this->mGlobalBlock
!== null ) {
2213 return $this->mGlobalBlock ?
: null;
2215 // User is already an IP?
2216 if ( IP
::isIPAddress( $this->getName() ) ) {
2217 $ip = $this->getName();
2219 $ip = $this->getRequest()->getIP();
2221 // Avoid PHP 7.1 warning of passing $this by reference
2225 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2227 if ( $blocked && $block === null ) {
2228 // back-compat: UserIsBlockedGlobally didn't have $block param first
2229 $block = new SystemBlock( [
2231 'systemBlock' => 'global-block'
2235 $this->mGlobalBlock
= $blocked ?
$block : false;
2236 return $this->mGlobalBlock ?
: null;
2240 * Check if user account is locked
2242 * @return bool True if locked, false otherwise
2244 public function isLocked() {
2245 if ( $this->mLocked
!== null ) {
2246 return $this->mLocked
;
2249 $this->mLocked
= false;
2250 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2251 return $this->mLocked
;
2255 * Check if user account is hidden
2257 * @return bool True if hidden, false otherwise
2259 public function isHidden() {
2260 if ( $this->mHideName
!== null ) {
2261 return (bool)$this->mHideName
;
2263 $this->getBlockedStatus();
2264 if ( !$this->mHideName
) {
2266 $this->mHideName
= false;
2267 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2269 return (bool)$this->mHideName
;
2273 * Get the user's ID.
2274 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2276 public function getId() {
2277 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2278 // Special case, we know the user is anonymous
2282 if ( !$this->isItemLoaded( 'id' ) ) {
2283 // Don't load if this was initialized from an ID
2287 return (int)$this->mId
;
2291 * Set the user and reload all fields according to a given ID
2292 * @param int $v User ID to reload
2294 public function setId( $v ) {
2296 $this->clearInstanceCache( 'id' );
2300 * Get the user name, or the IP of an anonymous user
2301 * @return string User's name or IP address
2303 public function getName() {
2304 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2305 // Special case optimisation
2306 return $this->mName
;
2310 if ( $this->mName
=== false ) {
2312 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2315 return $this->mName
;
2319 * Set the user name.
2321 * This does not reload fields from the database according to the given
2322 * name. Rather, it is used to create a temporary "nonexistent user" for
2323 * later addition to the database. It can also be used to set the IP
2324 * address for an anonymous user to something other than the current
2327 * @note User::newFromName() has roughly the same function, when the named user
2329 * @param string $str New user name to set
2331 public function setName( $str ) {
2333 $this->mName
= $str;
2337 * Get the user's actor ID.
2339 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2340 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2342 public function getActorId( IDatabase
$dbw = null ) {
2343 global $wgActorTableSchemaMigrationStage;
2345 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2346 // but it does little harm and might be needed for write callers loading a User.
2347 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2351 if ( !$this->isItemLoaded( 'actor' ) ) {
2355 // Currently $this->mActorId might be null if $this was loaded from a
2356 // cache entry that was written when $wgActorTableSchemaMigrationStage
2357 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2358 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2359 // has been removed), that condition may be removed.
2360 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2362 'actor_user' => $this->getId() ?
: null,
2363 'actor_name' => (string)$this->getName(),
2366 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2367 throw new CannotCreateActorException(
2368 'Cannot create an actor for a usable name that is not an existing user'
2371 if ( $q['actor_name'] === '' ) {
2372 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2374 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2375 if ( $dbw->affectedRows() ) {
2376 $this->mActorId
= (int)$dbw->insertId();
2379 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2380 $this->mActorId
= (int)$dbw->selectField(
2385 [ 'LOCK IN SHARE MODE' ]
2387 if ( !$this->mActorId
) {
2388 throw new CannotCreateActorException(
2389 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2393 $this->invalidateCache();
2395 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2396 $db = wfGetDB( $index );
2397 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2399 $this->setItemLoaded( 'actor' );
2402 return (int)$this->mActorId
;
2406 * Get the user's name escaped by underscores.
2407 * @return string Username escaped by underscores.
2409 public function getTitleKey() {
2410 return str_replace( ' ', '_', $this->getName() );
2414 * Check if the user has new messages.
2415 * @return bool True if the user has new messages
2417 public function getNewtalk() {
2420 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2421 if ( $this->mNewtalk
=== -1 ) {
2422 $this->mNewtalk
= false; # reset talk page status
2424 // Check memcached separately for anons, who have no
2425 // entire User object stored in there.
2426 if ( !$this->mId
) {
2427 global $wgDisableAnonTalk;
2428 if ( $wgDisableAnonTalk ) {
2429 // Anon newtalk disabled by configuration.
2430 $this->mNewtalk
= false;
2432 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2435 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2439 return (bool)$this->mNewtalk
;
2443 * Return the data needed to construct links for new talk page message
2444 * alerts. If there are new messages, this will return an associative array
2445 * with the following data:
2446 * wiki: The database name of the wiki
2447 * link: Root-relative link to the user's talk page
2448 * rev: The last talk page revision that the user has seen or null. This
2449 * is useful for building diff links.
2450 * If there are no new messages, it returns an empty array.
2451 * @note This function was designed to accomodate multiple talk pages, but
2452 * currently only returns a single link and revision.
2455 public function getNewMessageLinks() {
2456 // Avoid PHP 7.1 warning of passing $this by reference
2459 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2463 if ( !$this->getNewtalk() ) {
2466 $utp = $this->getTalkPage();
2467 $dbr = wfGetDB( DB_REPLICA
);
2468 // Get the "last viewed rev" timestamp from the oldest message notification
2469 $timestamp = $dbr->selectField( 'user_newtalk',
2470 'MIN(user_last_timestamp)',
2471 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2473 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2476 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2477 'link' => $utp->getLocalURL(),
2484 * Get the revision ID for the last talk page revision viewed by the talk
2486 * @return int|null Revision ID or null
2488 public function getNewMessageRevisionId() {
2489 $newMessageRevisionId = null;
2490 $newMessageLinks = $this->getNewMessageLinks();
2492 // Note: getNewMessageLinks() never returns more than a single link
2493 // and it is always for the same wiki, but we double-check here in
2494 // case that changes some time in the future.
2495 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2496 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2497 && $newMessageLinks[0]['rev']
2499 /** @var Revision $newMessageRevision */
2500 $newMessageRevision = $newMessageLinks[0]['rev'];
2501 $newMessageRevisionId = $newMessageRevision->getId();
2504 return $newMessageRevisionId;
2508 * Internal uncached check for new messages
2511 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2512 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2513 * @return bool True if the user has new messages
2515 protected function checkNewtalk( $field, $id ) {
2516 $dbr = wfGetDB( DB_REPLICA
);
2518 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2520 return $ok !== false;
2524 * Add or update the new messages flag
2525 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2526 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2527 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2528 * @return bool True if successful, false otherwise
2530 protected function updateNewtalk( $field, $id, $curRev = null ) {
2531 // Get timestamp of the talk page revision prior to the current one
2532 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2533 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2534 // Mark the user as having new messages since this revision
2535 $dbw = wfGetDB( DB_MASTER
);
2536 $dbw->insert( 'user_newtalk',
2537 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2540 if ( $dbw->affectedRows() ) {
2541 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2545 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2550 * Clear the new messages flag for the given user
2551 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2552 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2553 * @return bool True if successful, false otherwise
2555 protected function deleteNewtalk( $field, $id ) {
2556 $dbw = wfGetDB( DB_MASTER
);
2557 $dbw->delete( 'user_newtalk',
2560 if ( $dbw->affectedRows() ) {
2561 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2565 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2570 * Update the 'You have new messages!' status.
2571 * @param bool $val Whether the user has new messages
2572 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2573 * page. Ignored if null or !$val.
2575 public function setNewtalk( $val, $curRev = null ) {
2576 if ( wfReadOnly() ) {
2581 $this->mNewtalk
= $val;
2583 if ( $this->isAnon() ) {
2585 $id = $this->getName();
2588 $id = $this->getId();
2592 $changed = $this->updateNewtalk( $field, $id, $curRev );
2594 $changed = $this->deleteNewtalk( $field, $id );
2598 $this->invalidateCache();
2603 * Generate a current or new-future timestamp to be stored in the
2604 * user_touched field when we update things.
2606 * @return string Timestamp in TS_MW format
2608 private function newTouchedTimestamp() {
2610 if ( $this->mTouched
) {
2611 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2614 return wfTimestamp( TS_MW
, $time );
2618 * Clear user data from memcached
2620 * Use after applying updates to the database; caller's
2621 * responsibility to update user_touched if appropriate.
2623 * Called implicitly from invalidateCache() and saveSettings().
2625 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2627 public function clearSharedCache( $mode = 'refresh' ) {
2628 if ( !$this->getId() ) {
2632 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2633 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2634 $key = $this->getCacheKey( $cache );
2636 if ( $mode === 'refresh' ) {
2637 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2639 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2640 function () use ( $cache, $key ) {
2641 $cache->delete( $key );
2649 * Immediately touch the user data cache for this account
2651 * Calls touch() and removes account data from memcached
2653 public function invalidateCache() {
2655 $this->clearSharedCache( 'changed' );
2659 * Update the "touched" timestamp for the user
2661 * This is useful on various login/logout events when making sure that
2662 * a browser or proxy that has multiple tenants does not suffer cache
2663 * pollution where the new user sees the old users content. The value
2664 * of getTouched() is checked when determining 304 vs 200 responses.
2665 * Unlike invalidateCache(), this preserves the User object cache and
2666 * avoids database writes.
2670 public function touch() {
2671 $id = $this->getId();
2673 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2674 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2675 $cache->touchCheckKey( $key );
2676 $this->mQuickTouched
= null;
2681 * Validate the cache for this account.
2682 * @param string $timestamp A timestamp in TS_MW format
2685 public function validateCache( $timestamp ) {
2686 return ( $timestamp >= $this->getTouched() );
2690 * Get the user touched timestamp
2692 * Use this value only to validate caches via inequalities
2693 * such as in the case of HTTP If-Modified-Since response logic
2695 * @return string TS_MW Timestamp
2697 public function getTouched() {
2701 if ( $this->mQuickTouched
=== null ) {
2702 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2703 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2705 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2708 return max( $this->mTouched
, $this->mQuickTouched
);
2711 return $this->mTouched
;
2715 * Get the user_touched timestamp field (time of last DB updates)
2716 * @return string TS_MW Timestamp
2719 public function getDBTouched() {
2722 return $this->mTouched
;
2726 * Set the password and reset the random token.
2727 * Calls through to authentication plugin if necessary;
2728 * will have no effect if the auth plugin refuses to
2729 * pass the change through or if the legal password
2732 * As a special case, setting the password to null
2733 * wipes it, so the account cannot be logged in until
2734 * a new password is set, for instance via e-mail.
2736 * @deprecated since 1.27, use AuthManager instead
2737 * @param string $str New password to set
2738 * @throws PasswordError On failure
2741 public function setPassword( $str ) {
2742 wfDeprecated( __METHOD__
, '1.27' );
2743 return $this->setPasswordInternal( $str );
2747 * Set the password and reset the random token unconditionally.
2749 * @deprecated since 1.27, use AuthManager instead
2750 * @param string|null $str New password to set or null to set an invalid
2751 * password hash meaning that the user will not be able to log in
2752 * through the web interface.
2754 public function setInternalPassword( $str ) {
2755 wfDeprecated( __METHOD__
, '1.27' );
2756 $this->setPasswordInternal( $str );
2760 * Actually set the password and such
2761 * @since 1.27 cannot set a password for a user not in the database
2762 * @param string|null $str New password to set or null to set an invalid
2763 * password hash meaning that the user will not be able to log in
2764 * through the web interface.
2765 * @return bool Success
2767 private function setPasswordInternal( $str ) {
2768 $manager = AuthManager
::singleton();
2770 // If the user doesn't exist yet, fail
2771 if ( !$manager->userExists( $this->getName() ) ) {
2772 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2775 $status = $this->changeAuthenticationData( [
2776 'username' => $this->getName(),
2780 if ( !$status->isGood() ) {
2781 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2782 ->info( __METHOD__
. ': Password change rejected: '
2783 . $status->getWikiText( null, null, 'en' ) );
2787 $this->setOption( 'watchlisttoken', false );
2788 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2794 * Changes credentials of the user.
2796 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2797 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2798 * e.g. when no provider handled the change.
2800 * @param array $data A set of authentication data in fieldname => value format. This is the
2801 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2805 public function changeAuthenticationData( array $data ) {
2806 $manager = AuthManager
::singleton();
2807 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2808 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2810 $status = Status
::newGood( 'ignored' );
2811 foreach ( $reqs as $req ) {
2812 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2814 if ( $status->getValue() === 'ignored' ) {
2815 $status->warning( 'authenticationdatachange-ignored' );
2818 if ( $status->isGood() ) {
2819 foreach ( $reqs as $req ) {
2820 $manager->changeAuthenticationData( $req );
2827 * Get the user's current token.
2828 * @param bool $forceCreation Force the generation of a new token if the
2829 * user doesn't have one (default=true for backwards compatibility).
2830 * @return string|null Token
2832 public function getToken( $forceCreation = true ) {
2833 global $wgAuthenticationTokenVersion;
2836 if ( !$this->mToken
&& $forceCreation ) {
2840 if ( !$this->mToken
) {
2841 // The user doesn't have a token, return null to indicate that.
2845 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2846 // We return a random value here so existing token checks are very
2848 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2851 if ( $wgAuthenticationTokenVersion === null ) {
2852 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2853 return $this->mToken
;
2856 // $wgAuthenticationTokenVersion in use, so hmac it.
2857 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2859 // The raw hash can be overly long. Shorten it up.
2860 $len = max( 32, self
::TOKEN_LENGTH
);
2861 if ( strlen( $ret ) < $len ) {
2862 // Should never happen, even md5 is 128 bits
2863 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2866 return substr( $ret, -$len );
2870 * Set the random token (used for persistent authentication)
2871 * Called from loadDefaults() among other places.
2873 * @param string|bool $token If specified, set the token to this value
2875 public function setToken( $token = false ) {
2877 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2878 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2879 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2880 } elseif ( !$token ) {
2881 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2883 $this->mToken
= $token;
2888 * Set the password for a password reminder or new account email
2890 * @deprecated Removed in 1.27. Use PasswordReset instead.
2891 * @param string $str New password to set or null to set an invalid
2892 * password hash meaning that the user will not be able to use it
2893 * @param bool $throttle If true, reset the throttle timestamp to the present
2895 public function setNewpassword( $str, $throttle = true ) {
2896 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2900 * Get the user's e-mail address
2901 * @return string User's email address
2903 public function getEmail() {
2905 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2906 return $this->mEmail
;
2910 * Get the timestamp of the user's e-mail authentication
2911 * @return string TS_MW timestamp
2913 public function getEmailAuthenticationTimestamp() {
2915 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2916 return $this->mEmailAuthenticated
;
2920 * Set the user's e-mail address
2921 * @param string $str New e-mail address
2923 public function setEmail( $str ) {
2925 if ( $str == $this->mEmail
) {
2928 $this->invalidateEmail();
2929 $this->mEmail
= $str;
2930 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2934 * Set the user's e-mail address and a confirmation mail if needed.
2937 * @param string $str New e-mail address
2940 public function setEmailWithConfirmation( $str ) {
2941 global $wgEnableEmail, $wgEmailAuthentication;
2943 if ( !$wgEnableEmail ) {
2944 return Status
::newFatal( 'emaildisabled' );
2947 $oldaddr = $this->getEmail();
2948 if ( $str === $oldaddr ) {
2949 return Status
::newGood( true );
2952 $type = $oldaddr != '' ?
'changed' : 'set';
2953 $notificationResult = null;
2955 if ( $wgEmailAuthentication && $type === 'changed' ) {
2956 // Send the user an email notifying the user of the change in registered
2957 // email address on their previous email address
2958 $change = $str != '' ?
'changed' : 'removed';
2959 $notificationResult = $this->sendMail(
2960 wfMessage( 'notificationemail_subject_' . $change )->text(),
2961 wfMessage( 'notificationemail_body_' . $change,
2962 $this->getRequest()->getIP(),
2968 $this->setEmail( $str );
2970 if ( $str !== '' && $wgEmailAuthentication ) {
2971 // Send a confirmation request to the new address if needed
2972 $result = $this->sendConfirmationMail( $type );
2974 if ( $notificationResult !== null ) {
2975 $result->merge( $notificationResult );
2978 if ( $result->isGood() ) {
2979 // Say to the caller that a confirmation and notification mail has been sent
2980 $result->value
= 'eauth';
2983 $result = Status
::newGood( true );
2990 * Get the user's real name
2991 * @return string User's real name
2993 public function getRealName() {
2994 if ( !$this->isItemLoaded( 'realname' ) ) {
2998 return $this->mRealName
;
3002 * Set the user's real name
3003 * @param string $str New real name
3005 public function setRealName( $str ) {
3007 $this->mRealName
= $str;
3011 * Get the user's current setting for a given option.
3013 * @param string $oname The option to check
3014 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3015 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3016 * @return string|array|int|null User's current value for the option
3017 * @see getBoolOption()
3018 * @see getIntOption()
3020 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3021 global $wgHiddenPrefs;
3022 $this->loadOptions();
3024 # We want 'disabled' preferences to always behave as the default value for
3025 # users, even if they have set the option explicitly in their settings (ie they
3026 # set it, and then it was disabled removing their ability to change it). But
3027 # we don't want to erase the preferences in the database in case the preference
3028 # is re-enabled again. So don't touch $mOptions, just override the returned value
3029 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3030 return self
::getDefaultOption( $oname );
3033 if ( array_key_exists( $oname, $this->mOptions
) ) {
3034 return $this->mOptions
[$oname];
3037 return $defaultOverride;
3041 * Get all user's options
3043 * @param int $flags Bitwise combination of:
3044 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3045 * to the default value. (Since 1.25)
3048 public function getOptions( $flags = 0 ) {
3049 global $wgHiddenPrefs;
3050 $this->loadOptions();
3051 $options = $this->mOptions
;
3053 # We want 'disabled' preferences to always behave as the default value for
3054 # users, even if they have set the option explicitly in their settings (ie they
3055 # set it, and then it was disabled removing their ability to change it). But
3056 # we don't want to erase the preferences in the database in case the preference
3057 # is re-enabled again. So don't touch $mOptions, just override the returned value
3058 foreach ( $wgHiddenPrefs as $pref ) {
3059 $default = self
::getDefaultOption( $pref );
3060 if ( $default !== null ) {
3061 $options[$pref] = $default;
3065 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3066 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3073 * Get the user's current setting for a given option, as a boolean value.
3075 * @param string $oname The option to check
3076 * @return bool User's current value for the option
3079 public function getBoolOption( $oname ) {
3080 return (bool)$this->getOption( $oname );
3084 * Get the user's current setting for a given option, as an integer value.
3086 * @param string $oname The option to check
3087 * @param int $defaultOverride A default value returned if the option does not exist
3088 * @return int User's current value for the option
3091 public function getIntOption( $oname, $defaultOverride = 0 ) {
3092 $val = $this->getOption( $oname );
3094 $val = $defaultOverride;
3096 return intval( $val );
3100 * Set the given option for a user.
3102 * You need to call saveSettings() to actually write to the database.
3104 * @param string $oname The option to set
3105 * @param mixed $val New value to set
3107 public function setOption( $oname, $val ) {
3108 $this->loadOptions();
3110 // Explicitly NULL values should refer to defaults
3111 if ( is_null( $val ) ) {
3112 $val = self
::getDefaultOption( $oname );
3115 $this->mOptions
[$oname] = $val;
3119 * Get a token stored in the preferences (like the watchlist one),
3120 * resetting it if it's empty (and saving changes).
3122 * @param string $oname The option name to retrieve the token from
3123 * @return string|bool User's current value for the option, or false if this option is disabled.
3124 * @see resetTokenFromOption()
3126 * @deprecated since 1.26 Applications should use the OAuth extension
3128 public function getTokenFromOption( $oname ) {
3129 global $wgHiddenPrefs;
3131 $id = $this->getId();
3132 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3136 $token = $this->getOption( $oname );
3138 // Default to a value based on the user token to avoid space
3139 // wasted on storing tokens for all users. When this option
3140 // is set manually by the user, only then is it stored.
3141 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3148 * Reset a token stored in the preferences (like the watchlist one).
3149 * *Does not* save user's preferences (similarly to setOption()).
3151 * @param string $oname The option name to reset the token in
3152 * @return string|bool New token value, or false if this option is disabled.
3153 * @see getTokenFromOption()
3156 public function resetTokenFromOption( $oname ) {
3157 global $wgHiddenPrefs;
3158 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3162 $token = MWCryptRand
::generateHex( 40 );
3163 $this->setOption( $oname, $token );
3168 * Return a list of the types of user options currently returned by
3169 * User::getOptionKinds().
3171 * Currently, the option kinds are:
3172 * - 'registered' - preferences which are registered in core MediaWiki or
3173 * by extensions using the UserGetDefaultOptions hook.
3174 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3175 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3176 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3177 * be used by user scripts.
3178 * - 'special' - "preferences" that are not accessible via User::getOptions
3179 * or User::setOptions.
3180 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3181 * These are usually legacy options, removed in newer versions.
3183 * The API (and possibly others) use this function to determine the possible
3184 * option types for validation purposes, so make sure to update this when a
3185 * new option kind is added.
3187 * @see User::getOptionKinds
3188 * @return array Option kinds
3190 public static function listOptionKinds() {
3193 'registered-multiselect',
3194 'registered-checkmatrix',
3202 * Return an associative array mapping preferences keys to the kind of a preference they're
3203 * used for. Different kinds are handled differently when setting or reading preferences.
3205 * See User::listOptionKinds for the list of valid option types that can be provided.
3207 * @see User::listOptionKinds
3208 * @param IContextSource $context
3209 * @param array|null $options Assoc. array with options keys to check as keys.
3210 * Defaults to $this->mOptions.
3211 * @return array The key => kind mapping data
3213 public function getOptionKinds( IContextSource
$context, $options = null ) {
3214 $this->loadOptions();
3215 if ( $options === null ) {
3216 $options = $this->mOptions
;
3219 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3220 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3223 // Pull out the "special" options, so they don't get converted as
3224 // multiselect or checkmatrix.
3225 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3226 foreach ( $specialOptions as $name => $value ) {
3227 unset( $prefs[$name] );
3230 // Multiselect and checkmatrix options are stored in the database with
3231 // one key per option, each having a boolean value. Extract those keys.
3232 $multiselectOptions = [];
3233 foreach ( $prefs as $name => $info ) {
3234 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3235 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3236 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3237 $prefix = $info['prefix'] ??
$name;
3239 foreach ( $opts as $value ) {
3240 $multiselectOptions["$prefix$value"] = true;
3243 unset( $prefs[$name] );
3246 $checkmatrixOptions = [];
3247 foreach ( $prefs as $name => $info ) {
3248 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3249 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3250 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3251 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3252 $prefix = $info['prefix'] ??
$name;
3254 foreach ( $columns as $column ) {
3255 foreach ( $rows as $row ) {
3256 $checkmatrixOptions["$prefix$column-$row"] = true;
3260 unset( $prefs[$name] );
3264 // $value is ignored
3265 foreach ( $options as $key => $value ) {
3266 if ( isset( $prefs[$key] ) ) {
3267 $mapping[$key] = 'registered';
3268 } elseif ( isset( $multiselectOptions[$key] ) ) {
3269 $mapping[$key] = 'registered-multiselect';
3270 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3271 $mapping[$key] = 'registered-checkmatrix';
3272 } elseif ( isset( $specialOptions[$key] ) ) {
3273 $mapping[$key] = 'special';
3274 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3275 $mapping[$key] = 'userjs';
3277 $mapping[$key] = 'unused';
3285 * Reset certain (or all) options to the site defaults
3287 * The optional parameter determines which kinds of preferences will be reset.
3288 * Supported values are everything that can be reported by getOptionKinds()
3289 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3291 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3292 * [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ]
3293 * for backwards-compatibility.
3294 * @param IContextSource|null $context Context source used when $resetKinds
3295 * does not contain 'all', passed to getOptionKinds().
3296 * Defaults to RequestContext::getMain() when null.
3298 public function resetOptions(
3299 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3300 IContextSource
$context = null
3303 $defaultOptions = self
::getDefaultOptions();
3305 if ( !is_array( $resetKinds ) ) {
3306 $resetKinds = [ $resetKinds ];
3309 if ( in_array( 'all', $resetKinds ) ) {
3310 $newOptions = $defaultOptions;
3312 if ( $context === null ) {
3313 $context = RequestContext
::getMain();
3316 $optionKinds = $this->getOptionKinds( $context );
3317 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3320 // Use default values for the options that should be deleted, and
3321 // copy old values for the ones that shouldn't.
3322 foreach ( $this->mOptions
as $key => $value ) {
3323 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3324 if ( array_key_exists( $key, $defaultOptions ) ) {
3325 $newOptions[$key] = $defaultOptions[$key];
3328 $newOptions[$key] = $value;
3333 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3335 $this->mOptions
= $newOptions;
3336 $this->mOptionsLoaded
= true;
3340 * Get the user's preferred date format.
3341 * @return string User's preferred date format
3343 public function getDatePreference() {
3344 // Important migration for old data rows
3345 if ( is_null( $this->mDatePreference
) ) {
3347 $value = $this->getOption( 'date' );
3348 $map = $wgLang->getDatePreferenceMigrationMap();
3349 if ( isset( $map[$value] ) ) {
3350 $value = $map[$value];
3352 $this->mDatePreference
= $value;
3354 return $this->mDatePreference
;
3358 * Determine based on the wiki configuration and the user's options,
3359 * whether this user must be over HTTPS no matter what.
3363 public function requiresHTTPS() {
3364 global $wgSecureLogin;
3365 if ( !$wgSecureLogin ) {
3369 $https = $this->getBoolOption( 'prefershttps' );
3370 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3372 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3379 * Get the user preferred stub threshold
3383 public function getStubThreshold() {
3384 global $wgMaxArticleSize; # Maximum article size, in Kb
3385 $threshold = $this->getIntOption( 'stubthreshold' );
3386 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3387 // If they have set an impossible value, disable the preference
3388 // so we can use the parser cache again.
3395 * Get the permissions this user has.
3396 * @return string[] permission names
3398 public function getRights() {
3399 if ( is_null( $this->mRights
) ) {
3400 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3401 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3403 // Deny any rights denied by the user's session, unless this
3404 // endpoint has no sessions.
3405 if ( !defined( 'MW_NO_SESSION' ) ) {
3406 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3407 if ( $allowedRights !== null ) {
3408 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3412 Hooks
::run( 'UserGetRightsRemove', [ $this, &$this->mRights
] );
3413 // Force reindexation of rights when a hook has unset one of them
3414 $this->mRights
= array_values( array_unique( $this->mRights
) );
3416 // If block disables login, we should also remove any
3417 // extra rights blocked users might have, in case the
3418 // blocked user has a pre-existing session (T129738).
3419 // This is checked here for cases where people only call
3420 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3421 // to give a better error message in the common case.
3422 $config = RequestContext
::getMain()->getConfig();
3423 // @TODO Partial blocks should not prevent the user from logging in.
3424 // see: https://phabricator.wikimedia.org/T208895
3426 $this->isLoggedIn() &&
3427 $config->get( 'BlockDisablesLogin' ) &&
3431 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3434 return $this->mRights
;
3438 * Get the list of explicit group memberships this user has.
3439 * The implicit * and user groups are not included.
3441 * @return string[] Array of internal group names (sorted since 1.33)
3443 public function getGroups() {
3445 $this->loadGroups();
3446 return array_keys( $this->mGroupMemberships
);
3450 * Get the list of explicit group memberships this user has, stored as
3451 * UserGroupMembership objects. Implicit groups are not included.
3453 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3456 public function getGroupMemberships() {
3458 $this->loadGroups();
3459 return $this->mGroupMemberships
;
3463 * Get the list of implicit group memberships this user has.
3464 * This includes all explicit groups, plus 'user' if logged in,
3465 * '*' for all accounts, and autopromoted groups
3466 * @param bool $recache Whether to avoid the cache
3467 * @return array Array of String internal group names
3469 public function getEffectiveGroups( $recache = false ) {
3470 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3471 $this->mEffectiveGroups
= array_unique( array_merge(
3472 $this->getGroups(), // explicit groups
3473 $this->getAutomaticGroups( $recache ) // implicit groups
3475 // Avoid PHP 7.1 warning of passing $this by reference
3477 // Hook for additional groups
3478 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3479 // Force reindexation of groups when a hook has unset one of them
3480 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3482 return $this->mEffectiveGroups
;
3486 * Get the list of implicit group memberships this user has.
3487 * This includes 'user' if logged in, '*' for all accounts,
3488 * and autopromoted groups
3489 * @param bool $recache Whether to avoid the cache
3490 * @return array Array of String internal group names
3492 public function getAutomaticGroups( $recache = false ) {
3493 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3494 $this->mImplicitGroups
= [ '*' ];
3495 if ( $this->getId() ) {
3496 $this->mImplicitGroups
[] = 'user';
3498 $this->mImplicitGroups
= array_unique( array_merge(
3499 $this->mImplicitGroups
,
3500 Autopromote
::getAutopromoteGroups( $this )
3504 // Assure data consistency with rights/groups,
3505 // as getEffectiveGroups() depends on this function
3506 $this->mEffectiveGroups
= null;
3509 return $this->mImplicitGroups
;
3513 * Returns the groups the user has belonged to.
3515 * The user may still belong to the returned groups. Compare with getGroups().
3517 * The function will not return groups the user had belonged to before MW 1.17
3519 * @return array Names of the groups the user has belonged to.
3521 public function getFormerGroups() {
3524 if ( is_null( $this->mFormerGroups
) ) {
3525 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3526 ?
wfGetDB( DB_MASTER
)
3527 : wfGetDB( DB_REPLICA
);
3528 $res = $db->select( 'user_former_groups',
3530 [ 'ufg_user' => $this->mId
],
3532 $this->mFormerGroups
= [];
3533 foreach ( $res as $row ) {
3534 $this->mFormerGroups
[] = $row->ufg_group
;
3538 return $this->mFormerGroups
;
3542 * Get the user's edit count.
3543 * @return int|null Null for anonymous users
3545 public function getEditCount() {
3546 if ( !$this->getId() ) {
3550 if ( $this->mEditCount
=== null ) {
3551 /* Populate the count, if it has not been populated yet */
3552 $dbr = wfGetDB( DB_REPLICA
);
3553 // check if the user_editcount field has been initialized
3554 $count = $dbr->selectField(
3555 'user', 'user_editcount',
3556 [ 'user_id' => $this->mId
],
3560 if ( $count === null ) {
3561 // it has not been initialized. do so.
3562 $count = $this->initEditCountInternal();
3564 $this->mEditCount
= $count;
3566 return (int)$this->mEditCount
;
3570 * Add the user to the given group. This takes immediate effect.
3571 * If the user is already in the group, the expiry time will be updated to the new
3572 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3575 * @param string $group Name of the group to add
3576 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3577 * wfTimestamp(), or null if the group assignment should not expire
3580 public function addGroup( $group, $expiry = null ) {
3582 $this->loadGroups();
3585 $expiry = wfTimestamp( TS_MW
, $expiry );
3588 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3592 // create the new UserGroupMembership and put it in the DB
3593 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3594 if ( !$ugm->insert( true ) ) {
3598 $this->mGroupMemberships
[$group] = $ugm;
3600 // Refresh the groups caches, and clear the rights cache so it will be
3601 // refreshed on the next call to $this->getRights().
3602 $this->getEffectiveGroups( true );
3603 $this->mRights
= null;
3605 $this->invalidateCache();
3611 * Remove the user from the given group.
3612 * This takes immediate effect.
3613 * @param string $group Name of the group to remove
3616 public function removeGroup( $group ) {
3619 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3623 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3624 // delete the membership entry
3625 if ( !$ugm ||
!$ugm->delete() ) {
3629 $this->loadGroups();
3630 unset( $this->mGroupMemberships
[$group] );
3632 // Refresh the groups caches, and clear the rights cache so it will be
3633 // refreshed on the next call to $this->getRights().
3634 $this->getEffectiveGroups( true );
3635 $this->mRights
= null;
3637 $this->invalidateCache();
3643 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3644 * only this new name and not the old isLoggedIn() variant.
3646 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3647 * anonymous or has no local account (which can happen when importing). This is equivalent to
3648 * getId() != 0 and is provided for code readability.
3651 public function isRegistered() {
3652 return $this->getId() != 0;
3656 * Get whether the user is logged in
3659 public function isLoggedIn() {
3660 return $this->isRegistered();
3664 * Get whether the user is anonymous
3667 public function isAnon() {
3668 return !$this->isRegistered();
3672 * @return bool Whether this user is flagged as being a bot role account
3675 public function isBot() {
3676 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3681 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3687 * Check if user is allowed to access a feature / make an action
3689 * @param string $permissions,... Permissions to test
3690 * @return bool True if user is allowed to perform *any* of the given actions
3692 public function isAllowedAny() {
3693 $permissions = func_get_args();
3694 foreach ( $permissions as $permission ) {
3695 if ( $this->isAllowed( $permission ) ) {
3704 * @param string $permissions,... Permissions to test
3705 * @return bool True if the user is allowed to perform *all* of the given actions
3707 public function isAllowedAll() {
3708 $permissions = func_get_args();
3709 foreach ( $permissions as $permission ) {
3710 if ( !$this->isAllowed( $permission ) ) {
3718 * Internal mechanics of testing a permission
3719 * @param string $action
3722 public function isAllowed( $action = '' ) {
3723 if ( $action === '' ) {
3724 return true; // In the spirit of DWIM
3726 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3727 // by misconfiguration: 0 == 'foo'
3728 return in_array( $action, $this->getRights(), true );
3732 * Check whether to enable recent changes patrol features for this user
3733 * @return bool True or false
3735 public function useRCPatrol() {
3736 global $wgUseRCPatrol;
3737 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3741 * Check whether to enable new pages patrol features for this user
3742 * @return bool True or false
3744 public function useNPPatrol() {
3745 global $wgUseRCPatrol, $wgUseNPPatrol;
3747 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3748 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3753 * Check whether to enable new files patrol features for this user
3754 * @return bool True or false
3756 public function useFilePatrol() {
3757 global $wgUseRCPatrol, $wgUseFilePatrol;
3759 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3760 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3765 * Get the WebRequest object to use with this object
3767 * @return WebRequest
3769 public function getRequest() {
3770 if ( $this->mRequest
) {
3771 return $this->mRequest
;
3779 * Check the watched status of an article.
3780 * @since 1.22 $checkRights parameter added
3781 * @param Title $title Title of the article to look at
3782 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3783 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3786 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3787 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3788 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3795 * @since 1.22 $checkRights parameter added
3796 * @param Title $title Title of the article to look at
3797 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3798 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3800 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3801 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3802 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3804 [ $title->getSubjectPage(), $title->getTalkPage() ]
3807 $this->invalidateCache();
3811 * Stop watching an article.
3812 * @since 1.22 $checkRights parameter added
3813 * @param Title $title Title of the article to look at
3814 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3815 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3817 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3818 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3819 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3820 $store->removeWatch( $this, $title->getSubjectPage() );
3821 $store->removeWatch( $this, $title->getTalkPage() );
3823 $this->invalidateCache();
3827 * Clear the user's notification timestamp for the given title.
3828 * If e-notif e-mails are on, they will receive notification mails on
3829 * the next change of the page if it's watched etc.
3830 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3831 * @param Title &$title Title of the article to look at
3832 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3834 public function clearNotification( &$title, $oldid = 0 ) {
3835 global $wgUseEnotif, $wgShowUpdatedMarker;
3837 // Do nothing if the database is locked to writes
3838 if ( wfReadOnly() ) {
3842 // Do nothing if not allowed to edit the watchlist
3843 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3847 // If we're working on user's talk page, we should update the talk page message indicator
3848 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3849 // Avoid PHP 7.1 warning of passing $this by reference
3851 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3855 // Try to update the DB post-send and only if needed...
3856 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3857 if ( !$this->getNewtalk() ) {
3858 return; // no notifications to clear
3861 // Delete the last notifications (they stack up)
3862 $this->setNewtalk( false );
3864 // If there is a new, unseen, revision, use its timestamp
3866 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3869 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3874 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3878 if ( $this->isAnon() ) {
3879 // Nothing else to do...
3883 // Only update the timestamp if the page is being watched.
3884 // The query to find out if it is watched is cached both in memcached and per-invocation,
3885 // and when it does have to be executed, it can be on a replica DB
3886 // If this is the user's newtalk page, we always update the timestamp
3888 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3892 MediaWikiServices
::getInstance()->getWatchedItemStore()
3893 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3897 * Resets all of the given user's page-change notification timestamps.
3898 * If e-notif e-mails are on, they will receive notification mails on
3899 * the next change of any watched page.
3900 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3902 public function clearAllNotifications() {
3903 global $wgUseEnotif, $wgShowUpdatedMarker;
3904 // Do nothing if not allowed to edit the watchlist
3905 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3909 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3910 $this->setNewtalk( false );
3914 $id = $this->getId();
3919 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3920 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3922 // We also need to clear here the "you have new message" notification for the own
3923 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3927 * Compute experienced level based on edit count and registration date.
3929 * @return string 'newcomer', 'learner', or 'experienced'
3931 public function getExperienceLevel() {
3932 global $wgLearnerEdits,
3933 $wgExperiencedUserEdits,
3934 $wgLearnerMemberSince,
3935 $wgExperiencedUserMemberSince;
3937 if ( $this->isAnon() ) {
3941 $editCount = $this->getEditCount();
3942 $registration = $this->getRegistration();
3944 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3945 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3947 if ( $editCount < $wgLearnerEdits ||
3948 $registration > $learnerRegistration ) {
3952 if ( $editCount > $wgExperiencedUserEdits &&
3953 $registration <= $experiencedRegistration
3955 return 'experienced';
3962 * Persist this user's session (e.g. set cookies)
3964 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3966 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3967 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3969 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3971 if ( $this->mId
== 0 ) {
3975 $session = $this->getRequest()->getSession();
3976 if ( $request && $session->getRequest() !== $request ) {
3977 $session = $session->sessionWithRequest( $request );
3979 $delay = $session->delaySave();
3981 if ( !$session->getUser()->equals( $this ) ) {
3982 if ( !$session->canSetUser() ) {
3983 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3984 ->warning( __METHOD__
.
3985 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3989 $session->setUser( $this );
3992 $session->setRememberUser( $rememberMe );
3993 if ( $secure !== null ) {
3994 $session->setForceHTTPS( $secure );
3997 $session->persist();
3999 ScopedCallback
::consume( $delay );
4003 * Log this user out.
4005 public function logout() {
4006 // Avoid PHP 7.1 warning of passing $this by reference
4008 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4014 * Clear the user's session, and reset the instance cache.
4017 public function doLogout() {
4018 $session = $this->getRequest()->getSession();
4019 if ( !$session->canSetUser() ) {
4020 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4021 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4022 $error = 'immutable';
4023 } elseif ( !$session->getUser()->equals( $this ) ) {
4024 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4025 ->warning( __METHOD__
.
4026 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4028 // But we still may as well make this user object anon
4029 $this->clearInstanceCache( 'defaults' );
4030 $error = 'wronguser';
4032 $this->clearInstanceCache( 'defaults' );
4033 $delay = $session->delaySave();
4034 $session->unpersist(); // Clear cookies (T127436)
4035 $session->setLoggedOutTimestamp( time() );
4036 $session->setUser( new User
);
4037 $session->set( 'wsUserID', 0 ); // Other code expects this
4038 $session->resetAllTokens();
4039 ScopedCallback
::consume( $delay );
4042 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4043 'event' => 'logout',
4044 'successful' => $error === false,
4045 'status' => $error ?
: 'success',
4050 * Save this user's settings into the database.
4051 * @todo Only rarely do all these fields need to be set!
4053 public function saveSettings() {
4054 if ( wfReadOnly() ) {
4055 // @TODO: caller should deal with this instead!
4056 // This should really just be an exception.
4057 MWExceptionHandler
::logException( new DBExpectedError(
4059 "Could not update user with ID '{$this->mId}'; DB is read-only."
4065 if ( $this->mId
== 0 ) {
4069 // Get a new user_touched that is higher than the old one.
4070 // This will be used for a CAS check as a last-resort safety
4071 // check against race conditions and replica DB lag.
4072 $newTouched = $this->newTouchedTimestamp();
4074 $dbw = wfGetDB( DB_MASTER
);
4075 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
4076 global $wgActorTableSchemaMigrationStage;
4078 $dbw->update( 'user',
4080 'user_name' => $this->mName
,
4081 'user_real_name' => $this->mRealName
,
4082 'user_email' => $this->mEmail
,
4083 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4084 'user_touched' => $dbw->timestamp( $newTouched ),
4085 'user_token' => strval( $this->mToken
),
4086 'user_email_token' => $this->mEmailToken
,
4087 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4088 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4089 'user_id' => $this->mId
,
4093 if ( !$dbw->affectedRows() ) {
4094 // Maybe the problem was a missed cache update; clear it to be safe
4095 $this->clearSharedCache( 'refresh' );
4096 // User was changed in the meantime or loaded with stale data
4097 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4098 LoggerFactory
::getInstance( 'preferences' )->warning(
4099 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4100 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4102 throw new MWException( "CAS update failed on user_touched. " .
4103 "The version of the user to be saved is older than the current version."
4107 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4110 [ 'actor_name' => $this->mName
],
4111 [ 'actor_user' => $this->mId
],
4117 $this->mTouched
= $newTouched;
4118 $this->saveOptions();
4120 Hooks
::run( 'UserSaveSettings', [ $this ] );
4121 $this->clearSharedCache( 'changed' );
4122 $this->getUserPage()->purgeSquid();
4126 * If only this user's username is known, and it exists, return the user ID.
4128 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4131 public function idForName( $flags = 0 ) {
4132 $s = trim( $this->getName() );
4137 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4138 ?
wfGetDB( DB_MASTER
)
4139 : wfGetDB( DB_REPLICA
);
4141 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4142 ?
[ 'LOCK IN SHARE MODE' ]
4145 $id = $db->selectField( 'user',
4146 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4152 * Add a user to the database, return the user object
4154 * @param string $name Username to add
4155 * @param array $params Array of Strings Non-default parameters to save to
4156 * the database as user_* fields:
4157 * - email: The user's email address.
4158 * - email_authenticated: The email authentication timestamp.
4159 * - real_name: The user's real name.
4160 * - options: An associative array of non-default options.
4161 * - token: Random authentication token. Do not set.
4162 * - registration: Registration timestamp. Do not set.
4164 * @return User|null User object, or null if the username already exists.
4166 public static function createNew( $name, $params = [] ) {
4167 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4168 if ( isset( $params[$field] ) ) {
4169 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4170 unset( $params[$field] );
4176 $user->setToken(); // init token
4177 if ( isset( $params['options'] ) ) {
4178 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4179 unset( $params['options'] );
4181 $dbw = wfGetDB( DB_MASTER
);
4183 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4186 'user_name' => $name,
4187 'user_password' => $noPass,
4188 'user_newpassword' => $noPass,
4189 'user_email' => $user->mEmail
,
4190 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4191 'user_real_name' => $user->mRealName
,
4192 'user_token' => strval( $user->mToken
),
4193 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4194 'user_editcount' => 0,
4195 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4197 foreach ( $params as $name => $value ) {
4198 $fields["user_$name"] = $value;
4201 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4202 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4203 if ( $dbw->affectedRows() ) {
4204 $newUser = self
::newFromId( $dbw->insertId() );
4205 $newUser->mName
= $fields['user_name'];
4206 $newUser->updateActorId( $dbw );
4207 // Load the user from master to avoid replica lag
4208 $newUser->load( self
::READ_LATEST
);
4217 * Add this existing user object to the database. If the user already
4218 * exists, a fatal status object is returned, and the user object is
4219 * initialised with the data from the database.
4221 * Previously, this function generated a DB error due to a key conflict
4222 * if the user already existed. Many extension callers use this function
4223 * in code along the lines of:
4225 * $user = User::newFromName( $name );
4226 * if ( !$user->isLoggedIn() ) {
4227 * $user->addToDatabase();
4229 * // do something with $user...
4231 * However, this was vulnerable to a race condition (T18020). By
4232 * initialising the user object if the user exists, we aim to support this
4233 * calling sequence as far as possible.
4235 * Note that if the user exists, this function will acquire a write lock,
4236 * so it is still advisable to make the call conditional on isLoggedIn(),
4237 * and to commit the transaction after calling.
4239 * @throws MWException
4242 public function addToDatabase() {
4244 if ( !$this->mToken
) {
4245 $this->setToken(); // init token
4248 if ( !is_string( $this->mName
) ) {
4249 throw new RuntimeException( "User name field is not set." );
4252 $this->mTouched
= $this->newTouchedTimestamp();
4254 $dbw = wfGetDB( DB_MASTER
);
4255 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4256 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4257 $dbw->insert( 'user',
4259 'user_name' => $this->mName
,
4260 'user_password' => $noPass,
4261 'user_newpassword' => $noPass,
4262 'user_email' => $this->mEmail
,
4263 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4264 'user_real_name' => $this->mRealName
,
4265 'user_token' => strval( $this->mToken
),
4266 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4267 'user_editcount' => 0,
4268 'user_touched' => $dbw->timestamp( $this->mTouched
),
4272 if ( !$dbw->affectedRows() ) {
4273 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4274 $this->mId
= $dbw->selectField(
4277 [ 'user_name' => $this->mName
],
4279 [ 'LOCK IN SHARE MODE' ]
4282 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4286 throw new MWException( $fname . ": hit a key conflict attempting " .
4287 "to insert user '{$this->mName}' row, but it was not present in select!" );
4289 return Status
::newFatal( 'userexists' );
4291 $this->mId
= $dbw->insertId();
4292 self
::$idCacheByName[$this->mName
] = $this->mId
;
4293 $this->updateActorId( $dbw );
4295 return Status
::newGood();
4297 if ( !$status->isGood() ) {
4301 // Clear instance cache other than user table data and actor, which is already accurate
4302 $this->clearInstanceCache();
4304 $this->saveOptions();
4305 return Status
::newGood();
4309 * Update the actor ID after an insert
4310 * @param IDatabase $dbw Writable database handle
4312 private function updateActorId( IDatabase
$dbw ) {
4313 global $wgActorTableSchemaMigrationStage;
4315 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4318 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4321 $this->mActorId
= (int)$dbw->insertId();
4326 * If this user is logged-in and blocked,
4327 * block any IP address they've successfully logged in from.
4328 * @return bool A block was spread
4330 public function spreadAnyEditBlock() {
4331 if ( $this->isLoggedIn() && $this->getBlock() ) {
4332 return $this->spreadBlock();
4339 * If this (non-anonymous) user is blocked,
4340 * block the IP address they've successfully logged in from.
4341 * @return bool A block was spread
4343 protected function spreadBlock() {
4344 wfDebug( __METHOD__
. "()\n" );
4346 if ( $this->mId
== 0 ) {
4350 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4351 if ( !$userblock ) {
4355 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4359 * Get whether the user is explicitly blocked from account creation.
4360 * @return bool|AbstractBlock
4362 public function isBlockedFromCreateAccount() {
4363 $this->getBlockedStatus();
4364 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4365 return $this->mBlock
;
4368 # T15611: if the IP address the user is trying to create an account from is
4369 # blocked with createaccount disabled, prevent new account creation there even
4370 # when the user is logged in
4371 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4372 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4373 null, $this->getRequest()->getIP()
4376 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4377 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4378 ?
$this->mBlockedFromCreateAccount
4383 * Get whether the user is blocked from using Special:Emailuser.
4386 public function isBlockedFromEmailuser() {
4387 $this->getBlockedStatus();
4388 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4392 * Get whether the user is blocked from using Special:Upload
4397 public function isBlockedFromUpload() {
4398 $this->getBlockedStatus();
4399 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4403 * Get whether the user is allowed to create an account.
4406 public function isAllowedToCreateAccount() {
4407 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4411 * Get this user's personal page title.
4413 * @return Title User's personal page title
4415 public function getUserPage() {
4416 return Title
::makeTitle( NS_USER
, $this->getName() );
4420 * Get this user's talk page title.
4422 * @return Title User's talk page title
4424 public function getTalkPage() {
4425 $title = $this->getUserPage();
4426 return $title->getTalkPage();
4430 * Determine whether the user is a newbie. Newbies are either
4431 * anonymous IPs, or the most recently created accounts.
4434 public function isNewbie() {
4435 return !$this->isAllowed( 'autoconfirmed' );
4439 * Check to see if the given clear-text password is one of the accepted passwords
4440 * @deprecated since 1.27, use AuthManager instead
4441 * @param string $password User password
4442 * @return bool True if the given password is correct, otherwise False
4444 public function checkPassword( $password ) {
4445 wfDeprecated( __METHOD__
, '1.27' );
4447 $manager = AuthManager
::singleton();
4448 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4449 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4451 'username' => $this->getName(),
4452 'password' => $password,
4455 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4456 switch ( $res->status
) {
4457 case AuthenticationResponse
::PASS
:
4459 case AuthenticationResponse
::FAIL
:
4460 // Hope it's not a PreAuthenticationProvider that failed...
4461 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4462 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4465 throw new BadMethodCallException(
4466 'AuthManager returned a response unsupported by ' . __METHOD__
4472 * Check if the given clear-text password matches the temporary password
4473 * sent by e-mail for password reset operations.
4475 * @deprecated since 1.27, use AuthManager instead
4476 * @param string $plaintext
4477 * @return bool True if matches, false otherwise
4479 public function checkTemporaryPassword( $plaintext ) {
4480 wfDeprecated( __METHOD__
, '1.27' );
4481 // Can't check the temporary password individually.
4482 return $this->checkPassword( $plaintext );
4486 * Initialize (if necessary) and return a session token value
4487 * which can be used in edit forms to show that the user's
4488 * login credentials aren't being hijacked with a foreign form
4492 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4493 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4494 * @return MediaWiki\Session\Token The new edit token
4496 public function getEditTokenObject( $salt = '', $request = null ) {
4497 if ( $this->isAnon() ) {
4498 return new LoggedOutEditToken();
4502 $request = $this->getRequest();
4504 return $request->getSession()->getToken( $salt );
4508 * Initialize (if necessary) and return a session token value
4509 * which can be used in edit forms to show that the user's
4510 * login credentials aren't being hijacked with a foreign form
4513 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4516 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4517 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4518 * @return string The new edit token
4520 public function getEditToken( $salt = '', $request = null ) {
4521 return $this->getEditTokenObject( $salt, $request )->toString();
4525 * Check given value against the token value stored in the session.
4526 * A match should confirm that the form was submitted from the
4527 * user's own login session, not a form submission from a third-party
4530 * @param string $val Input value to compare
4531 * @param string|array $salt Optional function-specific data for hashing
4532 * @param WebRequest|null $request Object to use or null to use $wgRequest
4533 * @param int|null $maxage Fail tokens older than this, in seconds
4534 * @return bool Whether the token matches
4536 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4537 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4541 * Check given value against the token value stored in the session,
4542 * ignoring the suffix.
4544 * @param string $val Input value to compare
4545 * @param string|array $salt Optional function-specific data for hashing
4546 * @param WebRequest|null $request Object to use or null to use $wgRequest
4547 * @param int|null $maxage Fail tokens older than this, in seconds
4548 * @return bool Whether the token matches
4550 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4551 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4552 return $this->matchEditToken( $val, $salt, $request, $maxage );
4556 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4557 * mail to the user's given address.
4559 * @param string $type Message to send, either "created", "changed" or "set"
4562 public function sendConfirmationMail( $type = 'created' ) {
4564 $expiration = null; // gets passed-by-ref and defined in next line.
4565 $token = $this->confirmationToken( $expiration );
4566 $url = $this->confirmationTokenUrl( $token );
4567 $invalidateURL = $this->invalidationTokenUrl( $token );
4568 $this->saveSettings();
4570 if ( $type == 'created' ||
$type === false ) {
4571 $message = 'confirmemail_body';
4573 } elseif ( $type === true ) {
4574 $message = 'confirmemail_body_changed';
4577 // Messages: confirmemail_body_changed, confirmemail_body_set
4578 $message = 'confirmemail_body_' . $type;
4582 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4583 'body' => wfMessage( $message,
4584 $this->getRequest()->getIP(),
4587 $wgLang->userTimeAndDate( $expiration, $this ),
4589 $wgLang->userDate( $expiration, $this ),
4590 $wgLang->userTime( $expiration, $this ) )->text(),
4596 'ip' => $this->getRequest()->getIP(),
4597 'confirmURL' => $url,
4598 'invalidateURL' => $invalidateURL,
4599 'expiration' => $expiration
4602 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4603 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4607 * Send an e-mail to this user's account. Does not check for
4608 * confirmed status or validity.
4610 * @param string $subject Message subject
4611 * @param string $body Message body
4612 * @param User|null $from Optional sending user; if unspecified, default
4613 * $wgPasswordSender will be used.
4614 * @param MailAddress|null $replyto Reply-To address
4617 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4618 global $wgPasswordSender;
4620 if ( $from instanceof User
) {
4621 $sender = MailAddress
::newFromUser( $from );
4623 $sender = new MailAddress( $wgPasswordSender,
4624 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4626 $to = MailAddress
::newFromUser( $this );
4628 return UserMailer
::send( $to, $sender, $subject, $body, [
4629 'replyTo' => $replyto,
4634 * Generate, store, and return a new e-mail confirmation code.
4635 * A hash (unsalted, since it's used as a key) is stored.
4637 * @note Call saveSettings() after calling this function to commit
4638 * this change to the database.
4640 * @param string &$expiration Accepts the expiration time
4641 * @return string New token
4643 protected function confirmationToken( &$expiration ) {
4644 global $wgUserEmailConfirmationTokenExpiry;
4646 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4647 $expiration = wfTimestamp( TS_MW
, $expires );
4649 $token = MWCryptRand
::generateHex( 32 );
4650 $hash = md5( $token );
4651 $this->mEmailToken
= $hash;
4652 $this->mEmailTokenExpires
= $expiration;
4657 * Return a URL the user can use to confirm their email address.
4658 * @param string $token Accepts the email confirmation token
4659 * @return string New token URL
4661 protected function confirmationTokenUrl( $token ) {
4662 return $this->getTokenUrl( 'ConfirmEmail', $token );
4666 * Return a URL the user can use to invalidate their email address.
4667 * @param string $token Accepts the email confirmation token
4668 * @return string New token URL
4670 protected function invalidationTokenUrl( $token ) {
4671 return $this->getTokenUrl( 'InvalidateEmail', $token );
4675 * Internal function to format the e-mail validation/invalidation URLs.
4676 * This uses a quickie hack to use the
4677 * hardcoded English names of the Special: pages, for ASCII safety.
4679 * @note Since these URLs get dropped directly into emails, using the
4680 * short English names avoids insanely long URL-encoded links, which
4681 * also sometimes can get corrupted in some browsers/mailers
4682 * (T8957 with Gmail and Internet Explorer).
4684 * @param string $page Special page
4685 * @param string $token
4686 * @return string Formatted URL
4688 protected function getTokenUrl( $page, $token ) {
4689 // Hack to bypass localization of 'Special:'
4690 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4691 return $title->getCanonicalURL();
4695 * Mark the e-mail address confirmed.
4697 * @note Call saveSettings() after calling this function to commit the change.
4701 public function confirmEmail() {
4702 // Check if it's already confirmed, so we don't touch the database
4703 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4704 if ( !$this->isEmailConfirmed() ) {
4705 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4706 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4712 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4713 * address if it was already confirmed.
4715 * @note Call saveSettings() after calling this function to commit the change.
4716 * @return bool Returns true
4718 public function invalidateEmail() {
4720 $this->mEmailToken
= null;
4721 $this->mEmailTokenExpires
= null;
4722 $this->setEmailAuthenticationTimestamp( null );
4724 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4729 * Set the e-mail authentication timestamp.
4730 * @param string $timestamp TS_MW timestamp
4732 public function setEmailAuthenticationTimestamp( $timestamp ) {
4734 $this->mEmailAuthenticated
= $timestamp;
4735 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4739 * Is this user allowed to send e-mails within limits of current
4740 * site configuration?
4743 public function canSendEmail() {
4744 global $wgEnableEmail, $wgEnableUserEmail;
4745 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4748 $canSend = $this->isEmailConfirmed();
4749 // Avoid PHP 7.1 warning of passing $this by reference
4751 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4756 * Is this user allowed to receive e-mails within limits of current
4757 * site configuration?
4760 public function canReceiveEmail() {
4761 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4765 * Is this user's e-mail address valid-looking and confirmed within
4766 * limits of the current site configuration?
4768 * @note If $wgEmailAuthentication is on, this may require the user to have
4769 * confirmed their address by returning a code or using a password
4770 * sent to the address from the wiki.
4774 public function isEmailConfirmed() {
4775 global $wgEmailAuthentication;
4777 // Avoid PHP 7.1 warning of passing $this by reference
4780 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4781 if ( $this->isAnon() ) {
4784 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4787 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4797 * Check whether there is an outstanding request for e-mail confirmation.
4800 public function isEmailConfirmationPending() {
4801 global $wgEmailAuthentication;
4802 return $wgEmailAuthentication &&
4803 !$this->isEmailConfirmed() &&
4804 $this->mEmailToken
&&
4805 $this->mEmailTokenExpires
> wfTimestamp();
4809 * Get the timestamp of account creation.
4811 * @return string|bool|null Timestamp of account creation, false for
4812 * non-existent/anonymous user accounts, or null if existing account
4813 * but information is not in database.
4815 public function getRegistration() {
4816 if ( $this->isAnon() ) {
4820 return $this->mRegistration
;
4824 * Get the timestamp of the first edit
4826 * @return string|bool Timestamp of first edit, or false for
4827 * non-existent/anonymous user accounts.
4829 public function getFirstEditTimestamp() {
4830 return $this->getEditTimestamp( true );
4834 * Get the timestamp of the latest edit
4837 * @return string|bool Timestamp of first edit, or false for
4838 * non-existent/anonymous user accounts.
4840 public function getLatestEditTimestamp() {
4841 return $this->getEditTimestamp( false );
4845 * Get the timestamp of the first or latest edit
4847 * @param bool $first True for the first edit, false for the latest one
4848 * @return string|bool Timestamp of first or latest edit, or false for
4849 * non-existent/anonymous user accounts.
4851 private function getEditTimestamp( $first ) {
4852 if ( $this->getId() == 0 ) {
4853 return false; // anons
4855 $dbr = wfGetDB( DB_REPLICA
);
4856 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4857 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4858 ?
'revactor_timestamp' : 'rev_timestamp';
4859 $sortOrder = $first ?
'ASC' : 'DESC';
4860 $time = $dbr->selectField(
4861 [ 'revision' ] +
$actorWhere['tables'],
4863 [ $actorWhere['conds'] ],
4865 [ 'ORDER BY' => "$tsField $sortOrder" ],
4866 $actorWhere['joins']
4869 return false; // no edits
4871 return wfTimestamp( TS_MW
, $time );
4875 * Get the permissions associated with a given list of groups
4877 * @param array $groups Array of Strings List of internal group names
4878 * @return array Array of Strings List of permission key names for given groups combined
4880 public static function getGroupPermissions( $groups ) {
4881 global $wgGroupPermissions, $wgRevokePermissions;
4883 // grant every granted permission first
4884 foreach ( $groups as $group ) {
4885 if ( isset( $wgGroupPermissions[$group] ) ) {
4886 $rights = array_merge( $rights,
4887 // array_filter removes empty items
4888 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4891 // now revoke the revoked permissions
4892 foreach ( $groups as $group ) {
4893 if ( isset( $wgRevokePermissions[$group] ) ) {
4894 $rights = array_diff( $rights,
4895 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4898 return array_unique( $rights );
4902 * Get all the groups who have a given permission
4904 * @param string $role Role to check
4905 * @return array Array of Strings List of internal group names with the given permission
4907 public static function getGroupsWithPermission( $role ) {
4908 global $wgGroupPermissions;
4909 $allowedGroups = [];
4910 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4911 if ( self
::groupHasPermission( $group, $role ) ) {
4912 $allowedGroups[] = $group;
4915 return $allowedGroups;
4919 * Check, if the given group has the given permission
4921 * If you're wanting to check whether all users have a permission, use
4922 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4926 * @param string $group Group to check
4927 * @param string $role Role to check
4930 public static function groupHasPermission( $group, $role ) {
4931 global $wgGroupPermissions, $wgRevokePermissions;
4932 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4933 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4937 * Check if all users may be assumed to have the given permission
4939 * We generally assume so if the right is granted to '*' and isn't revoked
4940 * on any group. It doesn't attempt to take grants or other extension
4941 * limitations on rights into account in the general case, though, as that
4942 * would require it to always return false and defeat the purpose.
4943 * Specifically, session-based rights restrictions (such as OAuth or bot
4944 * passwords) are applied based on the current session.
4947 * @param string $right Right to check
4950 public static function isEveryoneAllowed( $right ) {
4951 global $wgGroupPermissions, $wgRevokePermissions;
4954 // Use the cached results, except in unit tests which rely on
4955 // being able change the permission mid-request
4956 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4957 return $cache[$right];
4960 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4961 $cache[$right] = false;
4965 // If it's revoked anywhere, then everyone doesn't have it
4966 foreach ( $wgRevokePermissions as $rights ) {
4967 if ( isset( $rights[$right] ) && $rights[$right] ) {
4968 $cache[$right] = false;
4973 // Remove any rights that aren't allowed to the global-session user,
4974 // unless there are no sessions for this endpoint.
4975 if ( !defined( 'MW_NO_SESSION' ) ) {
4976 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4977 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4978 $cache[$right] = false;
4983 // Allow extensions to say false
4984 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4985 $cache[$right] = false;
4989 $cache[$right] = true;
4994 * Return the set of defined explicit groups.
4995 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4996 * are not included, as they are defined automatically, not in the database.
4997 * @return array Array of internal group names
4999 public static function getAllGroups() {
5000 global $wgGroupPermissions, $wgRevokePermissions;
5001 return array_values( array_diff(
5002 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5003 self
::getImplicitGroups()
5008 * Get a list of all available permissions.
5009 * @return string[] Array of permission names
5011 public static function getAllRights() {
5012 if ( self
::$mAllRights === false ) {
5013 global $wgAvailableRights;
5014 if ( count( $wgAvailableRights ) ) {
5015 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5017 self
::$mAllRights = self
::$mCoreRights;
5019 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5021 return self
::$mAllRights;
5025 * Get a list of implicit groups
5026 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
5028 * @return array Array of Strings Array of internal group names
5030 public static function getImplicitGroups() {
5031 global $wgImplicitGroups;
5032 return $wgImplicitGroups;
5036 * Returns an array of the groups that a particular group can add/remove.
5038 * @param string $group The group to check for whether it can add/remove
5039 * @return array [ 'add' => [ addablegroups ],
5040 * 'remove' => [ removablegroups ],
5041 * 'add-self' => [ addablegroups to self ],
5042 * 'remove-self' => [ removable groups from self ] ]
5044 public static function changeableByGroup( $group ) {
5045 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5054 if ( empty( $wgAddGroups[$group] ) ) {
5055 // Don't add anything to $groups
5056 } elseif ( $wgAddGroups[$group] === true ) {
5057 // You get everything
5058 $groups['add'] = self
::getAllGroups();
5059 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5060 $groups['add'] = $wgAddGroups[$group];
5063 // Same thing for remove
5064 if ( empty( $wgRemoveGroups[$group] ) ) {
5066 } elseif ( $wgRemoveGroups[$group] === true ) {
5067 $groups['remove'] = self
::getAllGroups();
5068 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5069 $groups['remove'] = $wgRemoveGroups[$group];
5072 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5073 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5074 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5075 if ( is_int( $key ) ) {
5076 $wgGroupsAddToSelf['user'][] = $value;
5081 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5082 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5083 if ( is_int( $key ) ) {
5084 $wgGroupsRemoveFromSelf['user'][] = $value;
5089 // Now figure out what groups the user can add to him/herself
5090 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5092 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5093 // No idea WHY this would be used, but it's there
5094 $groups['add-self'] = self
::getAllGroups();
5095 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5096 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5099 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5101 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5102 $groups['remove-self'] = self
::getAllGroups();
5103 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5104 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5111 * Returns an array of groups that this user can add and remove
5112 * @return array [ 'add' => [ addablegroups ],
5113 * 'remove' => [ removablegroups ],
5114 * 'add-self' => [ addablegroups to self ],
5115 * 'remove-self' => [ removable groups from self ] ]
5117 public function changeableGroups() {
5118 if ( $this->isAllowed( 'userrights' ) ) {
5119 // This group gives the right to modify everything (reverse-
5120 // compatibility with old "userrights lets you change
5122 // Using array_merge to make the groups reindexed
5123 $all = array_merge( self
::getAllGroups() );
5132 // Okay, it's not so simple, we will have to go through the arrays
5139 $addergroups = $this->getEffectiveGroups();
5141 foreach ( $addergroups as $addergroup ) {
5142 $groups = array_merge_recursive(
5143 $groups, $this->changeableByGroup( $addergroup )
5145 $groups['add'] = array_unique( $groups['add'] );
5146 $groups['remove'] = array_unique( $groups['remove'] );
5147 $groups['add-self'] = array_unique( $groups['add-self'] );
5148 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5154 * Schedule a deferred update to update the user's edit count
5156 public function incEditCount() {
5157 if ( $this->isAnon() ) {
5161 DeferredUpdates
::addUpdate(
5162 new UserEditCountUpdate( $this, 1 ),
5163 DeferredUpdates
::POSTSEND
5168 * This method should not be called outside User/UserEditCountUpdate
5172 public function setEditCountInternal( $count ) {
5173 $this->mEditCount
= $count;
5177 * Initialize user_editcount from data out of the revision table
5179 * This method should not be called outside User/UserEditCountUpdate
5181 * @return int Number of edits
5183 public function initEditCountInternal() {
5184 // Pull from a replica DB to be less cruel to servers
5185 // Accuracy isn't the point anyway here
5186 $dbr = wfGetDB( DB_REPLICA
);
5187 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5188 $count = (int)$dbr->selectField(
5189 [ 'revision' ] +
$actorWhere['tables'],
5191 [ $actorWhere['conds'] ],
5194 $actorWhere['joins']
5197 $dbw = wfGetDB( DB_MASTER
);
5200 [ 'user_editcount' => $count ],
5202 'user_id' => $this->getId(),
5203 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5212 * Get the description of a given right
5215 * @param string $right Right to query
5216 * @return string Localized description of the right
5218 public static function getRightDescription( $right ) {
5219 $key = "right-$right";
5220 $msg = wfMessage( $key );
5221 return $msg->isDisabled() ?
$right : $msg->text();
5225 * Get the name of a given grant
5228 * @param string $grant Grant to query
5229 * @return string Localized name of the grant
5231 public static function getGrantName( $grant ) {
5232 $key = "grant-$grant";
5233 $msg = wfMessage( $key );
5234 return $msg->isDisabled() ?
$grant : $msg->text();
5238 * Add a newuser log entry for this user.
5239 * Before 1.19 the return value was always true.
5241 * @deprecated since 1.27, AuthManager handles logging
5242 * @param string|bool $action Account creation type.
5243 * - String, one of the following values:
5244 * - 'create' for an anonymous user creating an account for himself.
5245 * This will force the action's performer to be the created user itself,
5246 * no matter the value of $wgUser
5247 * - 'create2' for a logged in user creating an account for someone else
5248 * - 'byemail' when the created user will receive its password by e-mail
5249 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5250 * - Boolean means whether the account was created by e-mail (deprecated):
5251 * - true will be converted to 'byemail'
5252 * - false will be converted to 'create' if this object is the same as
5253 * $wgUser and to 'create2' otherwise
5254 * @param string $reason User supplied reason
5257 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5258 return true; // disabled
5262 * Add an autocreate newuser log entry for this user
5263 * Used by things like CentralAuth and perhaps other authplugins.
5264 * Consider calling addNewUserLogEntry() directly instead.
5266 * @deprecated since 1.27, AuthManager handles logging
5269 public function addNewUserLogEntryAutoCreate() {
5270 $this->addNewUserLogEntry( 'autocreate' );
5276 * Load the user options either from cache, the database or an array
5278 * @param array|null $data Rows for the current user out of the user_properties table
5280 protected function loadOptions( $data = null ) {
5283 if ( $this->mOptionsLoaded
) {
5287 $this->mOptions
= self
::getDefaultOptions();
5289 if ( !$this->getId() ) {
5290 // For unlogged-in users, load language/variant options from request.
5291 // There's no need to do it for logged-in users: they can set preferences,
5292 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5293 // so don't override user's choice (especially when the user chooses site default).
5294 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5295 $this->mOptions
['variant'] = $variant;
5296 $this->mOptions
['language'] = $variant;
5297 $this->mOptionsLoaded
= true;
5301 // Maybe load from the object
5302 if ( !is_null( $this->mOptionOverrides
) ) {
5303 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5304 foreach ( $this->mOptionOverrides
as $key => $value ) {
5305 $this->mOptions
[$key] = $value;
5308 if ( !is_array( $data ) ) {
5309 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5310 // Load from database
5311 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5312 ?
wfGetDB( DB_MASTER
)
5313 : wfGetDB( DB_REPLICA
);
5315 $res = $dbr->select(
5317 [ 'up_property', 'up_value' ],
5318 [ 'up_user' => $this->getId() ],
5322 $this->mOptionOverrides
= [];
5324 foreach ( $res as $row ) {
5325 // Convert '0' to 0. PHP's boolean conversion considers them both
5326 // false, but e.g. JavaScript considers the former as true.
5327 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5328 // and convert all values here.
5329 if ( $row->up_value
=== '0' ) {
5332 $data[$row->up_property
] = $row->up_value
;
5336 foreach ( $data as $property => $value ) {
5337 $this->mOptionOverrides
[$property] = $value;
5338 $this->mOptions
[$property] = $value;
5342 // Replace deprecated language codes
5343 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5344 $this->mOptions
['language']
5347 $this->mOptionsLoaded
= true;
5349 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5353 * Saves the non-default options for this user, as previously set e.g. via
5354 * setOption(), in the database's "user_properties" (preferences) table.
5355 * Usually used via saveSettings().
5357 protected function saveOptions() {
5358 $this->loadOptions();
5360 // Not using getOptions(), to keep hidden preferences in database
5361 $saveOptions = $this->mOptions
;
5363 // Allow hooks to abort, for instance to save to a global profile.
5364 // Reset options to default state before saving.
5365 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5369 $userId = $this->getId();
5371 $insert_rows = []; // all the new preference rows
5372 foreach ( $saveOptions as $key => $value ) {
5373 // Don't bother storing default values
5374 $defaultOption = self
::getDefaultOption( $key );
5375 if ( ( $defaultOption === null && $value !== false && $value !== null )
5376 ||
$value != $defaultOption
5379 'up_user' => $userId,
5380 'up_property' => $key,
5381 'up_value' => $value,
5386 $dbw = wfGetDB( DB_MASTER
);
5388 $res = $dbw->select( 'user_properties',
5389 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5391 // Find prior rows that need to be removed or updated. These rows will
5392 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5394 foreach ( $res as $row ) {
5395 if ( !isset( $saveOptions[$row->up_property
] )
5396 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5398 $keysDelete[] = $row->up_property
;
5402 if ( count( $keysDelete ) ) {
5403 // Do the DELETE by PRIMARY KEY for prior rows.
5404 // In the past a very large portion of calls to this function are for setting
5405 // 'rememberpassword' for new accounts (a preference that has since been removed).
5406 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5407 // caused gap locks on [max user ID,+infinity) which caused high contention since
5408 // updates would pile up on each other as they are for higher (newer) user IDs.
5409 // It might not be necessary these days, but it shouldn't hurt either.
5410 $dbw->delete( 'user_properties',
5411 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5413 // Insert the new preference rows
5414 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5418 * Return the list of user fields that should be selected to create
5419 * a new user object.
5420 * @deprecated since 1.31, use self::getQueryInfo() instead.
5423 public static function selectFields() {
5424 wfDeprecated( __METHOD__
, '1.31' );
5432 'user_email_authenticated',
5434 'user_email_token_expires',
5435 'user_registration',
5441 * Return the tables, fields, and join conditions to be selected to create
5442 * a new user object.
5444 * @return array With three keys:
5445 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5446 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5447 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5449 public static function getQueryInfo() {
5450 global $wgActorTableSchemaMigrationStage;
5453 'tables' => [ 'user' ],
5461 'user_email_authenticated',
5463 'user_email_token_expires',
5464 'user_registration',
5470 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5471 // but it does little harm and might be needed for write callers loading a User.
5472 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5473 $ret['tables']['user_actor'] = 'actor';
5474 $ret['fields'][] = 'user_actor.actor_id';
5475 $ret['joins']['user_actor'] = [
5476 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5477 [ 'user_actor.actor_user = user_id' ]
5485 * Factory function for fatal permission-denied errors
5488 * @param string $permission User right required
5491 static function newFatalPermissionDeniedStatus( $permission ) {
5495 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5496 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5500 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5503 return Status
::newFatal( 'badaccess-group0' );
5507 * Get a new instance of this user that was loaded from the master via a locking read
5509 * Use this instead of the main context User when updating that user. This avoids races
5510 * where that user was loaded from a replica DB or even the master but without proper locks.
5512 * @return User|null Returns null if the user was not found in the DB
5515 public function getInstanceForUpdate() {
5516 if ( !$this->getId() ) {
5517 return null; // anon
5520 $user = self
::newFromId( $this->getId() );
5521 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5529 * Checks if two user objects point to the same user.
5531 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5532 * @param UserIdentity $user
5535 public function equals( UserIdentity
$user ) {
5536 // XXX it's not clear whether central ID providers are supposed to obey this
5537 return $this->getName() === $user->getName();
5541 * Checks if usertalk is allowed
5545 public function isAllowUsertalk() {
5546 return $this->mAllowUsertalk
;