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.
91 protected static $mCacheVars = [
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
106 // user_properties table
113 * String Cached results of getAllRights()
115 protected static $mAllRights = false;
117 /** Cache variables */
130 /** @var string TS_MW timestamp from the DB */
132 /** @var string TS_MW timestamp from cache */
133 protected $mQuickTouched;
137 public $mEmailAuthenticated;
139 protected $mEmailToken;
141 protected $mEmailTokenExpires;
143 protected $mRegistration;
145 protected $mEditCount;
146 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
147 protected $mGroupMemberships;
149 protected $mOptionOverrides;
153 * Bool Whether the cache variables have been loaded.
156 public $mOptionsLoaded;
159 * Array with already loaded items or true if all items have been loaded.
161 protected $mLoadedItems = [];
165 * String Initialization data source if mLoadedItems!==true. May be one of:
166 * - 'defaults' anonymous user initialised from class defaults
167 * - 'name' initialise from mName
168 * - 'id' initialise from mId
169 * - 'actor' initialise from mActorId
170 * - 'session' log in from session if possible
172 * Use the User::newFrom*() family of functions to set this.
177 * Lazy-initialized variables, invalidated with clearInstanceCache
181 protected $mDatePreference;
187 protected $mBlockreason;
189 protected $mEffectiveGroups;
191 protected $mImplicitGroups;
193 protected $mFormerGroups;
194 /** @var AbstractBlock */
195 protected $mGlobalBlock;
203 /** @var WebRequest */
206 /** @var AbstractBlock */
210 protected $mAllowUsertalk;
212 /** @var AbstractBlock */
213 private $mBlockedFromCreateAccount = false;
215 /** @var int User::READ_* constant bitfield used to load data */
216 protected $queryFlagsUsed = self
::READ_NORMAL
;
218 public static $idCacheByName = [];
221 * Lightweight constructor for an anonymous user.
222 * Use the User::newFrom* factory functions for other kinds of users.
226 * @see newFromActorId()
227 * @see newFromConfirmationCode()
228 * @see newFromSession()
231 public function __construct() {
232 $this->clearInstanceCache( 'defaults' );
238 public function __toString() {
239 return (string)$this->getName();
242 public function __get( $name ) {
243 // A shortcut for $mRights deprecation phase
244 if ( $name === 'mRights' ) {
245 return $this->getRights();
249 public function __set( $name, $value ) {
250 // A shortcut for $mRights deprecation phase, only known legitimate use was for
251 // testing purposes, other uses seem bad in principle
252 if ( $name === 'mRights' ) {
253 MediaWikiServices
::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
255 is_null( $value ) ?
[] : $value
261 * Test if it's safe to load this User object.
263 * You should typically check this before using $wgUser or
264 * RequestContext::getUser in a method that might be called before the
265 * system has been fully initialized. If the object is unsafe, you should
266 * use an anonymous user:
268 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
274 public function isSafeToLoad() {
275 global $wgFullyInitialised;
277 // The user is safe to load if:
278 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
279 // * mLoadedItems === true (already loaded)
280 // * mFrom !== 'session' (sessions not involved at all)
282 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
283 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
287 * Load the user table data for this object from the source given by mFrom.
289 * @param int $flags User::READ_* constant bitfield
291 public function load( $flags = self
::READ_NORMAL
) {
292 global $wgFullyInitialised;
294 if ( $this->mLoadedItems
=== true ) {
298 // Set it now to avoid infinite recursion in accessors
299 $oldLoadedItems = $this->mLoadedItems
;
300 $this->mLoadedItems
= true;
301 $this->queryFlagsUsed
= $flags;
303 // If this is called too early, things are likely to break.
304 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
305 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
306 ->warning( 'User::loadFromSession called before the end of Setup.php', [
307 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
309 $this->loadDefaults();
310 $this->mLoadedItems
= $oldLoadedItems;
314 switch ( $this->mFrom
) {
316 $this->loadDefaults();
319 // Make sure this thread sees its own changes
320 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
321 if ( $lb->hasOrMadeRecentMasterChanges() ) {
322 $flags |
= self
::READ_LATEST
;
323 $this->queryFlagsUsed
= $flags;
326 $this->mId
= self
::idFromName( $this->mName
, $flags );
328 // Nonexistent user placeholder object
329 $this->loadDefaults( $this->mName
);
331 $this->loadFromId( $flags );
335 // Make sure this thread sees its own changes, if the ID isn't 0
336 if ( $this->mId
!= 0 ) {
337 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
338 if ( $lb->hasOrMadeRecentMasterChanges() ) {
339 $flags |
= self
::READ_LATEST
;
340 $this->queryFlagsUsed
= $flags;
344 $this->loadFromId( $flags );
347 // Make sure this thread sees its own changes
348 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
349 if ( $lb->hasOrMadeRecentMasterChanges() ) {
350 $flags |
= self
::READ_LATEST
;
351 $this->queryFlagsUsed
= $flags;
354 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
355 $row = wfGetDB( $index )->selectRow(
357 [ 'actor_user', 'actor_name' ],
358 [ 'actor_id' => $this->mActorId
],
365 $this->loadDefaults();
366 } elseif ( $row->actor_user
) {
367 $this->mId
= $row->actor_user
;
368 $this->loadFromId( $flags );
370 $this->loadDefaults( $row->actor_name
);
374 if ( !$this->loadFromSession() ) {
375 // Loading from session failed. Load defaults.
376 $this->loadDefaults();
378 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
381 throw new UnexpectedValueException(
382 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
387 * Load user table data, given mId has already been set.
388 * @param int $flags User::READ_* constant bitfield
389 * @return bool False if the ID does not exist, true otherwise
391 public function loadFromId( $flags = self
::READ_NORMAL
) {
392 if ( $this->mId
== 0 ) {
393 // Anonymous users are not in the database (don't need cache)
394 $this->loadDefaults();
398 // Try cache (unless this needs data from the master DB).
399 // NOTE: if this thread called saveSettings(), the cache was cleared.
400 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
402 if ( !$this->loadFromDatabase( $flags ) ) {
403 // Can't load from ID
407 $this->loadFromCache();
410 $this->mLoadedItems
= true;
411 $this->queryFlagsUsed
= $flags;
418 * @param string $wikiId
421 public static function purge( $wikiId, $userId ) {
422 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
423 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
424 $cache->delete( $key );
429 * @param WANObjectCache $cache
432 protected function getCacheKey( WANObjectCache
$cache ) {
433 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
435 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
439 * @param WANObjectCache $cache
443 public function getMutableCacheKeys( WANObjectCache
$cache ) {
444 $id = $this->getId();
446 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
450 * Load user data from shared cache, given mId has already been set.
455 protected function loadFromCache() {
456 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
457 $data = $cache->getWithSetCallback(
458 $this->getCacheKey( $cache ),
460 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
461 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
462 wfDebug( "User: cache miss for user {$this->mId}\n" );
464 $this->loadFromDatabase( self
::READ_NORMAL
);
466 $this->loadOptions();
469 foreach ( self
::$mCacheVars as $name ) {
470 $data[$name] = $this->$name;
473 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
475 // if a user group membership is about to expire, the cache needs to
476 // expire at that time (T163691)
477 foreach ( $this->mGroupMemberships
as $ugm ) {
478 if ( $ugm->getExpiry() ) {
479 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
480 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
481 $ttl = $secondsUntilExpiry;
488 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
491 // Restore from cache
492 foreach ( self
::$mCacheVars as $name ) {
493 $this->$name = $data[$name];
499 /** @name newFrom*() static factory methods */
503 * Static factory method for creation from username.
505 * This is slightly less efficient than newFromId(), so use newFromId() if
506 * you have both an ID and a name handy.
508 * @param string $name Username, validated by Title::newFromText()
509 * @param string|bool $validate Validate username. Takes the same parameters as
510 * User::getCanonicalName(), except that true is accepted as an alias
511 * for 'valid', for BC.
513 * @return User|bool User object, or false if the username is invalid
514 * (e.g. if it contains illegal characters or is an IP address). If the
515 * username is not present in the database, the result will be a user object
516 * with a name, zero user ID and default settings.
518 public static function newFromName( $name, $validate = 'valid' ) {
519 if ( $validate === true ) {
522 $name = self
::getCanonicalName( $name, $validate );
523 if ( $name === false ) {
527 // Create unloaded user object
531 $u->setItemLoaded( 'name' );
537 * Static factory method for creation from a given user ID.
539 * @param int $id Valid user ID
540 * @return User The corresponding User object
542 public static function newFromId( $id ) {
546 $u->setItemLoaded( 'id' );
551 * Static factory method for creation from a given actor ID.
554 * @param int $id Valid actor ID
555 * @return User The corresponding User object
557 public static function newFromActorId( $id ) {
558 global $wgActorTableSchemaMigrationStage;
560 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
561 // but it does little harm and might be needed for write callers loading a User.
562 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
563 throw new BadMethodCallException(
564 'Cannot use ' . __METHOD__
565 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
572 $u->setItemLoaded( 'actor' );
577 * Returns a User object corresponding to the given UserIdentity.
581 * @param UserIdentity $identity
585 public static function newFromIdentity( UserIdentity
$identity ) {
586 if ( $identity instanceof User
) {
590 return self
::newFromAnyId(
591 $identity->getId() === 0 ?
null : $identity->getId(),
592 $identity->getName() === '' ?
null : $identity->getName(),
593 $identity->getActorId() === 0 ?
null : $identity->getActorId()
598 * Static factory method for creation from an ID, name, and/or actor ID
600 * This does not check that the ID, name, and actor ID all correspond to
604 * @param int|null $userId User ID, if known
605 * @param string|null $userName User name, if known
606 * @param int|null $actorId Actor ID, if known
607 * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none
610 public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) {
611 global $wgActorTableSchemaMigrationStage;
613 // Stop-gap solution for the problem described in T222212.
614 // Force the User ID and Actor ID to zero for users loaded from the database
615 // of another wiki, to prevent subtle data corruption and confusing failure modes.
616 if ( $wikiId !== false ) {
622 $user->mFrom
= 'defaults';
624 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
625 // but it does little harm and might be needed for write callers loading a User.
626 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
627 $user->mActorId
= (int)$actorId;
628 if ( $user->mActorId
!== 0 ) {
629 $user->mFrom
= 'actor';
631 $user->setItemLoaded( 'actor' );
634 if ( $userName !== null && $userName !== '' ) {
635 $user->mName
= $userName;
636 $user->mFrom
= 'name';
637 $user->setItemLoaded( 'name' );
640 if ( $userId !== null ) {
641 $user->mId
= (int)$userId;
642 if ( $user->mId
!== 0 ) {
645 $user->setItemLoaded( 'id' );
648 if ( $user->mFrom
=== 'defaults' ) {
649 throw new InvalidArgumentException(
650 'Cannot create a user with no name, no ID, and no actor ID'
658 * Factory method to fetch whichever user has a given email confirmation code.
659 * This code is generated when an account is created or its e-mail address
662 * If the code is invalid or has expired, returns NULL.
664 * @param string $code Confirmation code
665 * @param int $flags User::READ_* bitfield
668 public static function newFromConfirmationCode( $code, $flags = 0 ) {
669 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
670 ?
wfGetDB( DB_MASTER
)
671 : wfGetDB( DB_REPLICA
);
673 $id = $db->selectField(
677 'user_email_token' => md5( $code ),
678 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
682 return $id ? self
::newFromId( $id ) : null;
686 * Create a new user object using data from session. If the login
687 * credentials are invalid, the result is an anonymous user.
689 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
692 public static function newFromSession( WebRequest
$request = null ) {
694 $user->mFrom
= 'session';
695 $user->mRequest
= $request;
700 * Create a new user object from a user row.
701 * The row should have the following fields from the user table in it:
702 * - either user_name or user_id to load further data if needed (or both)
704 * - all other fields (email, etc.)
705 * It is useless to provide the remaining fields if either user_id,
706 * user_name and user_real_name are not provided because the whole row
707 * will be loaded once more from the database when accessing them.
709 * @param stdClass $row A row from the user table
710 * @param array|null $data Further data to load into the object
711 * (see User::loadFromRow for valid keys)
714 public static function newFromRow( $row, $data = null ) {
716 $user->loadFromRow( $row, $data );
721 * Static factory method for creation of a "system" user from username.
723 * A "system" user is an account that's used to attribute logged actions
724 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
725 * might include the 'Maintenance script' or 'Conversion script' accounts
726 * used by various scripts in the maintenance/ directory or accounts such
727 * as 'MediaWiki message delivery' used by the MassMessage extension.
729 * This can optionally create the user if it doesn't exist, and "steal" the
730 * account if it does exist.
732 * "Stealing" an existing user is intended to make it impossible for normal
733 * authentication processes to use the account, effectively disabling the
734 * account for normal use:
735 * - Email is invalidated, to prevent account recovery by emailing a
736 * temporary password and to disassociate the account from the existing
738 * - The token is set to a magic invalid value, to kill existing sessions
739 * and to prevent $this->setToken() calls from resetting the token to a
741 * - SessionManager is instructed to prevent new sessions for the user, to
742 * do things like deauthorizing OAuth consumers.
743 * - AuthManager is instructed to revoke access, to invalidate or remove
744 * passwords and other credentials.
746 * @param string $name Username
747 * @param array $options Options are:
748 * - validate: As for User::getCanonicalName(), default 'valid'
749 * - create: Whether to create the user if it doesn't already exist, default true
750 * - steal: Whether to "disable" the account for normal use if it already
751 * exists, default false
755 public static function newSystemUser( $name, $options = [] ) {
757 'validate' => 'valid',
762 $name = self
::getCanonicalName( $name, $options['validate'] );
763 if ( $name === false ) {
767 $dbr = wfGetDB( DB_REPLICA
);
768 $userQuery = self
::getQueryInfo();
769 $row = $dbr->selectRow(
770 $userQuery['tables'],
771 $userQuery['fields'],
772 [ 'user_name' => $name ],
778 // Try the master database...
779 $dbw = wfGetDB( DB_MASTER
);
780 $row = $dbw->selectRow(
781 $userQuery['tables'],
782 $userQuery['fields'],
783 [ 'user_name' => $name ],
791 // No user. Create it?
792 return $options['create']
793 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
797 $user = self
::newFromRow( $row );
799 // A user is considered to exist as a non-system user if it can
800 // authenticate, or has an email set, or has a non-invalid token.
801 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
802 AuthManager
::singleton()->userCanAuthenticate( $name )
804 // User exists. Steal it?
805 if ( !$options['steal'] ) {
809 AuthManager
::singleton()->revokeAccessForUser( $name );
811 $user->invalidateEmail();
812 $user->mToken
= self
::INVALID_TOKEN
;
813 $user->saveSettings();
814 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
823 * Get the username corresponding to a given user ID
824 * @param int $id User ID
825 * @return string|bool The corresponding username
827 public static function whoIs( $id ) {
828 return UserCache
::singleton()->getProp( $id, 'name' );
832 * Get the real name of a user given their user ID
834 * @param int $id User ID
835 * @return string|bool The corresponding user's real name
837 public static function whoIsReal( $id ) {
838 return UserCache
::singleton()->getProp( $id, 'real_name' );
842 * Get database id given a user name
843 * @param string $name Username
844 * @param int $flags User::READ_* constant bitfield
845 * @return int|null The corresponding user's ID, or null if user is nonexistent
847 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
848 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
849 $name = (string)$name;
850 $nt = Title
::makeTitleSafe( NS_USER
, $name );
851 if ( is_null( $nt ) ) {
856 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
857 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
860 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
861 $db = wfGetDB( $index );
866 [ 'user_name' => $nt->getText() ],
871 if ( $s === false ) {
874 $result = (int)$s->user_id
;
877 self
::$idCacheByName[$name] = $result;
879 if ( count( self
::$idCacheByName ) > 1000 ) {
880 self
::$idCacheByName = [];
887 * Reset the cache used in idFromName(). For use in tests.
889 public static function resetIdByNameCache() {
890 self
::$idCacheByName = [];
894 * Does the string match an anonymous IP address?
896 * This function exists for username validation, in order to reject
897 * usernames which are similar in form to IP addresses. Strings such
898 * as 300.300.300.300 will return true because it looks like an IP
899 * address, despite not being strictly valid.
901 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
902 * address because the usemod software would "cloak" anonymous IP
903 * addresses like this, if we allowed accounts like this to be created
904 * new users could get the old edits of these anonymous users.
906 * @param string $name Name to match
909 public static function isIP( $name ) {
910 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
911 || IP
::isIPv6( $name );
915 * Is the user an IP range?
920 public function isIPRange() {
921 return IP
::isValidRange( $this->mName
);
925 * Is the input a valid username?
927 * Checks if the input is a valid username, we don't want an empty string,
928 * an IP address, anything that contains slashes (would mess up subpages),
929 * is longer than the maximum allowed username size or doesn't begin with
932 * @param string $name Name to match
935 public static function isValidUserName( $name ) {
936 global $wgMaxNameChars;
939 || self
::isIP( $name )
940 ||
strpos( $name, '/' ) !== false
941 ||
strlen( $name ) > $wgMaxNameChars
942 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
947 // Ensure that the name can't be misresolved as a different title,
948 // such as with extra namespace keys at the start.
949 $parsed = Title
::newFromText( $name );
950 if ( is_null( $parsed )
951 ||
$parsed->getNamespace()
952 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
956 // Check an additional blacklist of troublemaker characters.
957 // Should these be merged into the title char list?
958 $unicodeBlacklist = '/[' .
959 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
960 '\x{00a0}' . # non-breaking space
961 '\x{2000}-\x{200f}' . # various whitespace
962 '\x{2028}-\x{202f}' . # breaks and control chars
963 '\x{3000}' . # ideographic space
964 '\x{e000}-\x{f8ff}' . # private use
966 if ( preg_match( $unicodeBlacklist, $name ) ) {
974 * Usernames which fail to pass this function will be blocked
975 * from user login and new account registrations, but may be used
976 * internally by batch processes.
978 * If an account already exists in this form, login will be blocked
979 * by a failure to pass this function.
981 * @param string $name Name to match
984 public static function isUsableName( $name ) {
985 global $wgReservedUsernames;
986 // Must be a valid username, obviously ;)
987 if ( !self
::isValidUserName( $name ) ) {
991 static $reservedUsernames = false;
992 if ( !$reservedUsernames ) {
993 $reservedUsernames = $wgReservedUsernames;
994 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
997 // Certain names may be reserved for batch processes.
998 foreach ( $reservedUsernames as $reserved ) {
999 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1000 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1002 if ( $reserved == $name ) {
1010 * Return the users who are members of the given group(s). In case of multiple groups,
1011 * users who are members of at least one of them are returned.
1013 * @param string|array $groups A single group name or an array of group names
1014 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1015 * records; larger values are ignored.
1016 * @param int|null $after ID the user to start after
1017 * @return UserArrayFromResult
1019 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1020 if ( $groups === [] ) {
1021 return UserArrayFromResult
::newFromIDs( [] );
1024 $groups = array_unique( (array)$groups );
1025 $limit = min( 5000, $limit );
1027 $conds = [ 'ug_group' => $groups ];
1028 if ( $after !== null ) {
1029 $conds[] = 'ug_user > ' . (int)$after;
1032 $dbr = wfGetDB( DB_REPLICA
);
1033 $ids = $dbr->selectFieldValues(
1040 'ORDER BY' => 'ug_user',
1044 return UserArray
::newFromIDs( $ids );
1048 * Usernames which fail to pass this function will be blocked
1049 * from new account registrations, but may be used internally
1050 * either by batch processes or by user accounts which have
1051 * already been created.
1053 * Additional blacklisting may be added here rather than in
1054 * isValidUserName() to avoid disrupting existing accounts.
1056 * @param string $name String to match
1059 public static function isCreatableName( $name ) {
1060 global $wgInvalidUsernameCharacters;
1062 // Ensure that the username isn't longer than 235 bytes, so that
1063 // (at least for the builtin skins) user javascript and css files
1064 // will work. (T25080)
1065 if ( strlen( $name ) > 235 ) {
1066 wfDebugLog( 'username', __METHOD__
.
1067 ": '$name' invalid due to length" );
1071 // Preg yells if you try to give it an empty string
1072 if ( $wgInvalidUsernameCharacters !== '' &&
1073 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1075 wfDebugLog( 'username', __METHOD__
.
1076 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1080 return self
::isUsableName( $name );
1084 * Is the input a valid password for this user?
1086 * @param string $password Desired password
1089 public function isValidPassword( $password ) {
1090 // simple boolean wrapper for checkPasswordValidity
1091 return $this->checkPasswordValidity( $password )->isGood();
1095 * Check if this is a valid password for this user
1097 * Returns a Status object with a set of messages describing
1098 * problems with the password. If the return status is fatal,
1099 * the action should be refused and the password should not be
1100 * checked at all (this is mainly meant for DoS mitigation).
1101 * If the return value is OK but not good, the password can be checked,
1102 * but the user should not be able to set their password to this.
1103 * The value of the returned Status object will be an array which
1104 * can have the following fields:
1105 * - forceChange (bool): if set to true, the user should not be
1106 * allowed to log with this password unless they change it during
1107 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1108 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1109 * a password change on login.
1111 * @param string $password Desired password
1115 public function checkPasswordValidity( $password ) {
1116 global $wgPasswordPolicy;
1118 $upp = new UserPasswordPolicy(
1119 $wgPasswordPolicy['policies'],
1120 $wgPasswordPolicy['checks']
1123 $status = Status
::newGood( [] );
1124 $result = false; // init $result to false for the internal checks
1126 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1127 $status->error( $result );
1131 if ( $result === false ) {
1132 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1136 if ( $result === true ) {
1140 $status->error( $result );
1141 return $status; // the isValidPassword hook set a string $result and returned true
1145 * Given unvalidated user input, return a canonical username, or false if
1146 * the username is invalid.
1147 * @param string $name User input
1148 * @param string|bool $validate Type of validation to use:
1149 * - false No validation
1150 * - 'valid' Valid for batch processes
1151 * - 'usable' Valid for batch processes and login
1152 * - 'creatable' Valid for batch processes, login and account creation
1154 * @throws InvalidArgumentException
1155 * @return bool|string
1157 public static function getCanonicalName( $name, $validate = 'valid' ) {
1158 // Force usernames to capital
1159 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1161 # Reject names containing '#'; these will be cleaned up
1162 # with title normalisation, but then it's too late to
1164 if ( strpos( $name, '#' ) !== false ) {
1168 // Clean up name according to title rules,
1169 // but only when validation is requested (T14654)
1170 $t = ( $validate !== false ) ?
1171 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1172 // Check for invalid titles
1173 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1177 $name = $t->getText();
1179 switch ( $validate ) {
1183 if ( !self
::isValidUserName( $name ) ) {
1188 if ( !self
::isUsableName( $name ) ) {
1193 if ( !self
::isCreatableName( $name ) ) {
1198 throw new InvalidArgumentException(
1199 'Invalid parameter value for $validate in ' . __METHOD__
);
1205 * Set cached properties to default.
1207 * @note This no longer clears uncached lazy-initialised properties;
1208 * the constructor does that instead.
1210 * @param string|bool $name
1212 public function loadDefaults( $name = false ) {
1214 $this->mName
= $name;
1215 $this->mActorId
= null;
1216 $this->mRealName
= '';
1218 $this->mOptionOverrides
= null;
1219 $this->mOptionsLoaded
= false;
1221 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1222 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1223 if ( $loggedOut !== 0 ) {
1224 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1226 $this->mTouched
= '1'; # Allow any pages to be cached
1229 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1230 $this->mEmailAuthenticated
= null;
1231 $this->mEmailToken
= '';
1232 $this->mEmailTokenExpires
= null;
1233 $this->mRegistration
= wfTimestamp( TS_MW
);
1234 $this->mGroupMemberships
= [];
1236 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1240 * Return whether an item has been loaded.
1242 * @param string $item Item to check. Current possibilities:
1246 * @param string $all 'all' to check if the whole object has been loaded
1247 * or any other string to check if only the item is available (e.g.
1251 public function isItemLoaded( $item, $all = 'all' ) {
1252 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1253 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1257 * Set that an item has been loaded
1259 * @param string $item
1261 protected function setItemLoaded( $item ) {
1262 if ( is_array( $this->mLoadedItems
) ) {
1263 $this->mLoadedItems
[$item] = true;
1268 * Load user data from the session.
1270 * @return bool True if the user is logged in, false otherwise.
1272 private function loadFromSession() {
1275 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1276 if ( $result !== null ) {
1280 // MediaWiki\Session\Session already did the necessary authentication of the user
1281 // returned here, so just use it if applicable.
1282 $session = $this->getRequest()->getSession();
1283 $user = $session->getUser();
1284 if ( $user->isLoggedIn() ) {
1285 $this->loadFromUserObject( $user );
1286 if ( $user->getBlock() ) {
1287 // If this user is autoblocked, set a cookie to track the block. This has to be done on
1288 // every session load, because an autoblocked editor might not edit again from the same
1289 // IP address after being blocked.
1290 $this->trackBlockWithCookie();
1293 // Other code expects these to be set in the session, so set them.
1294 $session->set( 'wsUserID', $this->getId() );
1295 $session->set( 'wsUserName', $this->getName() );
1296 $session->set( 'wsToken', $this->getToken() );
1305 * Set the 'BlockID' cookie depending on block type and user authentication status.
1307 public function trackBlockWithCookie() {
1308 $block = $this->getBlock();
1310 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null
1311 && $block->shouldTrackWithCookie( $this->isAnon() )
1313 $block->setCookie( $this->getRequest()->response() );
1318 * Load user and user_group data from the database.
1319 * $this->mId must be set, this is how the user is identified.
1321 * @param int $flags User::READ_* constant bitfield
1322 * @return bool True if the user exists, false if the user is anonymous
1324 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1326 $this->mId
= intval( $this->mId
);
1328 if ( !$this->mId
) {
1329 // Anonymous users are not in the database
1330 $this->loadDefaults();
1334 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1335 $db = wfGetDB( $index );
1337 $userQuery = self
::getQueryInfo();
1338 $s = $db->selectRow(
1339 $userQuery['tables'],
1340 $userQuery['fields'],
1341 [ 'user_id' => $this->mId
],
1347 $this->queryFlagsUsed
= $flags;
1348 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1350 if ( $s !== false ) {
1351 // Initialise user table data
1352 $this->loadFromRow( $s );
1353 $this->mGroupMemberships
= null; // deferred
1354 $this->getEditCount(); // revalidation for nulls
1360 $this->loadDefaults();
1366 * Initialize this object from a row from the user table.
1368 * @param stdClass $row Row from the user table to load.
1369 * @param array|null $data Further user data to load into the object
1371 * user_groups Array of arrays or stdClass result rows out of the user_groups
1372 * table. Previously you were supposed to pass an array of strings
1373 * here, but we also need expiry info nowadays, so an array of
1374 * strings is ignored.
1375 * user_properties Array with properties out of the user_properties table
1377 protected function loadFromRow( $row, $data = null ) {
1378 global $wgActorTableSchemaMigrationStage;
1380 if ( !is_object( $row ) ) {
1381 throw new InvalidArgumentException( '$row must be an object' );
1386 $this->mGroupMemberships
= null; // deferred
1388 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1389 // but it does little harm and might be needed for write callers loading a User.
1390 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1391 if ( isset( $row->actor_id
) ) {
1392 $this->mActorId
= (int)$row->actor_id
;
1393 if ( $this->mActorId
!== 0 ) {
1394 $this->mFrom
= 'actor';
1396 $this->setItemLoaded( 'actor' );
1402 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1403 $this->mName
= $row->user_name
;
1404 $this->mFrom
= 'name';
1405 $this->setItemLoaded( 'name' );
1410 if ( isset( $row->user_real_name
) ) {
1411 $this->mRealName
= $row->user_real_name
;
1412 $this->setItemLoaded( 'realname' );
1417 if ( isset( $row->user_id
) ) {
1418 $this->mId
= intval( $row->user_id
);
1419 if ( $this->mId
!== 0 ) {
1420 $this->mFrom
= 'id';
1422 $this->setItemLoaded( 'id' );
1427 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1428 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1431 if ( isset( $row->user_editcount
) ) {
1432 $this->mEditCount
= $row->user_editcount
;
1437 if ( isset( $row->user_touched
) ) {
1438 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1443 if ( isset( $row->user_token
) ) {
1444 // The definition for the column is binary(32), so trim the NULs
1445 // that appends. The previous definition was char(32), so trim
1447 $this->mToken
= rtrim( $row->user_token
, " \0" );
1448 if ( $this->mToken
=== '' ) {
1449 $this->mToken
= null;
1455 if ( isset( $row->user_email
) ) {
1456 $this->mEmail
= $row->user_email
;
1457 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1458 $this->mEmailToken
= $row->user_email_token
;
1459 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1460 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1466 $this->mLoadedItems
= true;
1469 if ( is_array( $data ) ) {
1470 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1471 if ( $data['user_groups'] === [] ) {
1472 $this->mGroupMemberships
= [];
1474 $firstGroup = reset( $data['user_groups'] );
1475 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1476 $this->mGroupMemberships
= [];
1477 foreach ( $data['user_groups'] as $row ) {
1478 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1479 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1484 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1485 $this->loadOptions( $data['user_properties'] );
1491 * Load the data for this user object from another user object.
1495 protected function loadFromUserObject( $user ) {
1497 foreach ( self
::$mCacheVars as $var ) {
1498 $this->$var = $user->$var;
1503 * Load the groups from the database if they aren't already loaded.
1505 private function loadGroups() {
1506 if ( is_null( $this->mGroupMemberships
) ) {
1507 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1508 ?
wfGetDB( DB_MASTER
)
1509 : wfGetDB( DB_REPLICA
);
1510 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1516 * Add the user to the group if he/she meets given criteria.
1518 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1519 * possible to remove manually via Special:UserRights. In such case it
1520 * will not be re-added automatically. The user will also not lose the
1521 * group if they no longer meet the criteria.
1523 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1525 * @return array Array of groups the user has been promoted to.
1527 * @see $wgAutopromoteOnce
1529 public function addAutopromoteOnceGroups( $event ) {
1530 global $wgAutopromoteOnceLogInRC;
1532 if ( wfReadOnly() ||
!$this->getId() ) {
1536 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1537 if ( $toPromote === [] ) {
1541 if ( !$this->checkAndSetTouched() ) {
1542 return []; // raced out (bug T48834)
1545 $oldGroups = $this->getGroups(); // previous groups
1546 $oldUGMs = $this->getGroupMemberships();
1547 foreach ( $toPromote as $group ) {
1548 $this->addGroup( $group );
1550 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1551 $newUGMs = $this->getGroupMemberships();
1553 // update groups in external authentication database
1554 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1556 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1557 $logEntry->setPerformer( $this );
1558 $logEntry->setTarget( $this->getUserPage() );
1559 $logEntry->setParameters( [
1560 '4::oldgroups' => $oldGroups,
1561 '5::newgroups' => $newGroups,
1563 $logid = $logEntry->insert();
1564 if ( $wgAutopromoteOnceLogInRC ) {
1565 $logEntry->publish( $logid );
1572 * Builds update conditions. Additional conditions may be added to $conditions to
1573 * protected against race conditions using a compare-and-set (CAS) mechanism
1574 * based on comparing $this->mTouched with the user_touched field.
1576 * @param IDatabase $db
1577 * @param array $conditions WHERE conditions for use with Database::update
1578 * @return array WHERE conditions for use with Database::update
1580 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1581 if ( $this->mTouched
) {
1582 // CAS check: only update if the row wasn't changed sicne it was loaded.
1583 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1590 * Bump user_touched if it didn't change since this object was loaded
1592 * On success, the mTouched field is updated.
1593 * The user serialization cache is always cleared.
1595 * @return bool Whether user_touched was actually updated
1598 protected function checkAndSetTouched() {
1601 if ( !$this->mId
) {
1602 return false; // anon
1605 // Get a new user_touched that is higher than the old one
1606 $newTouched = $this->newTouchedTimestamp();
1608 $dbw = wfGetDB( DB_MASTER
);
1609 $dbw->update( 'user',
1610 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1611 $this->makeUpdateConditions( $dbw, [
1612 'user_id' => $this->mId
,
1616 $success = ( $dbw->affectedRows() > 0 );
1619 $this->mTouched
= $newTouched;
1620 $this->clearSharedCache( 'changed' );
1622 // Clears on failure too since that is desired if the cache is stale
1623 $this->clearSharedCache( 'refresh' );
1630 * Clear various cached data stored in this object. The cache of the user table
1631 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1633 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1634 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1636 public function clearInstanceCache( $reloadFrom = false ) {
1637 global $wgFullyInitialised;
1639 $this->mNewtalk
= -1;
1640 $this->mDatePreference
= null;
1641 $this->mBlockedby
= -1; # Unset
1642 $this->mHash
= false;
1643 $this->mEffectiveGroups
= null;
1644 $this->mImplicitGroups
= null;
1645 $this->mGroupMemberships
= null;
1646 $this->mOptions
= null;
1647 $this->mOptionsLoaded
= false;
1648 $this->mEditCount
= null;
1650 // Replacement of former `$this->mRights = null` line
1651 if ( $wgFullyInitialised && $this->mFrom
) {
1652 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache(
1657 if ( $reloadFrom ) {
1658 $this->mLoadedItems
= [];
1659 $this->mFrom
= $reloadFrom;
1663 /** @var array|null */
1664 private static $defOpt = null;
1665 /** @var string|null */
1666 private static $defOptLang = null;
1669 * Reset the process cache of default user options. This is only necessary
1670 * if the wiki configuration has changed since defaults were calculated,
1671 * and as such should only be performed inside the testing suite that
1672 * regularly changes wiki configuration.
1674 public static function resetGetDefaultOptionsForTestsOnly() {
1675 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1676 self
::$defOpt = null;
1677 self
::$defOptLang = null;
1681 * Combine the language default options with any site-specific options
1682 * and add the default language variants.
1684 * @return array Array of String options
1686 public static function getDefaultOptions() {
1687 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1689 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1690 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1691 // The content language does not change (and should not change) mid-request, but the
1692 // unit tests change it anyway, and expect this method to return values relevant to the
1693 // current content language.
1694 return self
::$defOpt;
1697 self
::$defOpt = $wgDefaultUserOptions;
1698 // Default language setting
1699 self
::$defOptLang = $contLang->getCode();
1700 self
::$defOpt['language'] = self
::$defOptLang;
1701 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1702 if ( $langCode === $contLang->getCode() ) {
1703 self
::$defOpt['variant'] = $langCode;
1705 self
::$defOpt["variant-$langCode"] = $langCode;
1709 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1710 // since extensions may change the set of searchable namespaces depending
1711 // on user groups/permissions.
1712 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1713 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1715 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1717 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1719 return self
::$defOpt;
1723 * Get a given default option value.
1725 * @param string $opt Name of option to retrieve
1726 * @return string Default option value
1728 public static function getDefaultOption( $opt ) {
1729 $defOpts = self
::getDefaultOptions();
1730 return $defOpts[$opt] ??
null;
1734 * Get blocking information
1736 * TODO: Move this into the BlockManager, along with block-related properties.
1738 * @param bool $fromReplica Whether to check the replica DB first.
1739 * To improve performance, non-critical checks are done against replica DBs.
1740 * Check when actually saving should be done against master.
1742 private function getBlockedStatus( $fromReplica = true ) {
1743 if ( $this->mBlockedby
!= -1 ) {
1747 wfDebug( __METHOD__
. ": checking...\n" );
1749 // Initialize data...
1750 // Otherwise something ends up stomping on $this->mBlockedby when
1751 // things get lazy-loaded later, causing false positive block hits
1752 // due to -1 !== 0. Probably session-related... Nothing should be
1753 // overwriting mBlockedby, surely?
1756 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1761 if ( $block instanceof AbstractBlock
) {
1762 wfDebug( __METHOD__
. ": Found block.\n" );
1763 $this->mBlock
= $block;
1764 $this->mBlockedby
= $block->getByName();
1765 $this->mBlockreason
= $block->getReason();
1766 $this->mHideName
= $block->getHideName();
1767 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1769 $this->mBlock
= null;
1770 $this->mBlockedby
= '';
1771 $this->mBlockreason
= '';
1772 $this->mHideName
= 0;
1773 $this->mAllowUsertalk
= false;
1776 // Avoid PHP 7.1 warning of passing $this by reference
1779 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1783 * Whether the given IP is in a DNS blacklist.
1785 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1786 * @param string $ip IP to check
1787 * @param bool $checkWhitelist Whether to check the whitelist first
1788 * @return bool True if blacklisted.
1790 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1791 return MediaWikiServices
::getInstance()->getBlockManager()
1792 ->isDnsBlacklisted( $ip, $checkWhitelist );
1796 * Whether the given IP is in a given DNS blacklist.
1798 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1799 * @param string $ip IP to check
1800 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1801 * @return bool True if blacklisted.
1803 public function inDnsBlacklist( $ip, $bases ) {
1804 wfDeprecated( __METHOD__
, '1.34' );
1807 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1808 if ( IP
::isIPv4( $ip ) ) {
1809 // Reverse IP, T23255
1810 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1812 foreach ( (array)$bases as $base ) {
1814 // If we have an access key, use that too (ProjectHoneypot, etc.)
1816 if ( is_array( $base ) ) {
1817 if ( count( $base ) >= 2 ) {
1818 // Access key is 1, base URL is 0
1819 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1821 $host = "$ipReversed.{$base[0]}";
1823 $basename = $base[0];
1825 $host = "$ipReversed.$base";
1829 $ipList = gethostbynamel( $host );
1832 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1837 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1845 * Check if an IP address is in the local proxy list
1847 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1851 public static function isLocallyBlockedProxy( $ip ) {
1852 wfDeprecated( __METHOD__
, '1.34' );
1854 global $wgProxyList;
1856 if ( !$wgProxyList ) {
1860 if ( !is_array( $wgProxyList ) ) {
1861 // Load values from the specified file
1862 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1865 $resultProxyList = [];
1866 $deprecatedIPEntries = [];
1868 // backward compatibility: move all ip addresses in keys to values
1869 foreach ( $wgProxyList as $key => $value ) {
1870 $keyIsIP = IP
::isIPAddress( $key );
1871 $valueIsIP = IP
::isIPAddress( $value );
1872 if ( $keyIsIP && !$valueIsIP ) {
1873 $deprecatedIPEntries[] = $key;
1874 $resultProxyList[] = $key;
1875 } elseif ( $keyIsIP && $valueIsIP ) {
1876 $deprecatedIPEntries[] = $key;
1877 $resultProxyList[] = $key;
1878 $resultProxyList[] = $value;
1880 $resultProxyList[] = $value;
1884 if ( $deprecatedIPEntries ) {
1886 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1887 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1890 $proxyListIPSet = new IPSet( $resultProxyList );
1891 return $proxyListIPSet->match( $ip );
1895 * Is this user subject to rate limiting?
1897 * @return bool True if rate limited
1899 public function isPingLimitable() {
1900 global $wgRateLimitsExcludedIPs;
1901 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1902 // No other good way currently to disable rate limits
1903 // for specific IPs. :P
1904 // But this is a crappy hack and should die.
1907 return !$this->isAllowed( 'noratelimit' );
1911 * Primitive rate limits: enforce maximum actions per time period
1912 * to put a brake on flooding.
1914 * The method generates both a generic profiling point and a per action one
1915 * (suffix being "-$action".
1917 * @note When using a shared cache like memcached, IP-address
1918 * last-hit counters will be shared across wikis.
1920 * @param string $action Action to enforce; 'edit' if unspecified
1921 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1922 * @return bool True if a rate limiter was tripped
1924 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1925 // Avoid PHP 7.1 warning of passing $this by reference
1927 // Call the 'PingLimiter' hook
1929 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1933 global $wgRateLimits;
1934 if ( !isset( $wgRateLimits[$action] ) ) {
1938 $limits = array_merge(
1939 [ '&can-bypass' => true ],
1940 $wgRateLimits[$action]
1943 // Some groups shouldn't trigger the ping limiter, ever
1944 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1949 $id = $this->getId();
1951 $isNewbie = $this->isNewbie();
1952 $cache = ObjectCache
::getLocalClusterInstance();
1956 if ( isset( $limits['anon'] ) ) {
1957 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1959 } elseif ( isset( $limits['user'] ) ) {
1960 // limits for logged-in users
1961 $userLimit = $limits['user'];
1964 // limits for anons and for newbie logged-in users
1967 if ( isset( $limits['ip'] ) ) {
1968 $ip = $this->getRequest()->getIP();
1969 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1971 // subnet-based limits
1972 if ( isset( $limits['subnet'] ) ) {
1973 $ip = $this->getRequest()->getIP();
1974 $subnet = IP
::getSubnet( $ip );
1975 if ( $subnet !== false ) {
1976 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1981 // Check for group-specific permissions
1982 // If more than one group applies, use the group with the highest limit ratio (max/period)
1983 foreach ( $this->getGroups() as $group ) {
1984 if ( isset( $limits[$group] ) ) {
1985 if ( $userLimit === false
1986 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1988 $userLimit = $limits[$group];
1993 // limits for newbie logged-in users (override all the normal user limits)
1994 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1995 $userLimit = $limits['newbie'];
1998 // Set the user limit key
1999 if ( $userLimit !== false ) {
2000 // phan is confused because &can-bypass's value is a bool, so it assumes
2001 // that $userLimit is also a bool here.
2002 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2003 list( $max, $period ) = $userLimit;
2004 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2005 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2008 // ip-based limits for all ping-limitable users
2009 if ( isset( $limits['ip-all'] ) ) {
2010 $ip = $this->getRequest()->getIP();
2011 // ignore if user limit is more permissive
2012 if ( $isNewbie ||
$userLimit === false
2013 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2014 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2018 // subnet-based limits for all ping-limitable users
2019 if ( isset( $limits['subnet-all'] ) ) {
2020 $ip = $this->getRequest()->getIP();
2021 $subnet = IP
::getSubnet( $ip );
2022 if ( $subnet !== false ) {
2023 // ignore if user limit is more permissive
2024 if ( $isNewbie ||
$userLimit === false
2025 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2026 > $userLimit[0] / $userLimit[1] ) {
2027 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2033 foreach ( $keys as $key => $limit ) {
2034 // phan is confused because &can-bypass's value is a bool, so it assumes
2035 // that $userLimit is also a bool here.
2036 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2037 list( $max, $period ) = $limit;
2038 $summary = "(limit $max in {$period}s)";
2039 $count = $cache->get( $key );
2042 if ( $count >= $max ) {
2043 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2044 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2047 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2050 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2051 if ( $incrBy > 0 ) {
2052 $cache->add( $key, 0, intval( $period ) ); // first ping
2055 if ( $incrBy > 0 ) {
2056 $cache->incr( $key, $incrBy );
2064 * Check if user is blocked
2066 * @deprecated since 1.34, use User::getBlock() or
2067 * PermissionManager::isBlockedFrom() or
2068 * PermissionManager::userCan() instead.
2070 * @param bool $fromReplica Whether to check the replica DB instead of
2071 * the master. Hacked from false due to horrible probs on site.
2072 * @return bool True if blocked, false otherwise
2074 public function isBlocked( $fromReplica = true ) {
2075 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2076 $this->getBlock()->appliesToRight( 'edit' );
2080 * Get the block affecting the user, or null if the user is not blocked
2082 * @param bool $fromReplica Whether to check the replica DB instead of the master
2083 * @return AbstractBlock|null
2085 public function getBlock( $fromReplica = true ) {
2086 $this->getBlockedStatus( $fromReplica );
2087 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2091 * Check if user is blocked from editing a particular article
2093 * @param Title $title Title to check
2094 * @param bool $fromReplica Whether to check the replica DB instead of the master
2097 * @deprecated since 1.33,
2098 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2101 public function isBlockedFrom( $title, $fromReplica = false ) {
2102 return MediaWikiServices
::getInstance()->getPermissionManager()
2103 ->isBlockedFrom( $this, $title, $fromReplica );
2107 * If user is blocked, return the name of the user who placed the block
2108 * @return string Name of blocker
2110 public function blockedBy() {
2111 $this->getBlockedStatus();
2112 return $this->mBlockedby
;
2116 * If user is blocked, return the specified reason for the block
2117 * @return string Blocking reason
2119 public function blockedFor() {
2120 $this->getBlockedStatus();
2121 return $this->mBlockreason
;
2125 * If user is blocked, return the ID for the block
2126 * @return int Block ID
2128 public function getBlockId() {
2129 $this->getBlockedStatus();
2130 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2134 * Check if user is blocked on all wikis.
2135 * Do not use for actual edit permission checks!
2136 * This is intended for quick UI checks.
2138 * @param string $ip IP address, uses current client if none given
2139 * @return bool True if blocked, false otherwise
2141 public function isBlockedGlobally( $ip = '' ) {
2142 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2146 * Check if user is blocked on all wikis.
2147 * Do not use for actual edit permission checks!
2148 * This is intended for quick UI checks.
2150 * @param string $ip IP address, uses current client if none given
2151 * @return AbstractBlock|null Block object if blocked, null otherwise
2152 * @throws FatalError
2153 * @throws MWException
2155 public function getGlobalBlock( $ip = '' ) {
2156 if ( $this->mGlobalBlock
!== null ) {
2157 return $this->mGlobalBlock ?
: null;
2159 // User is already an IP?
2160 if ( IP
::isIPAddress( $this->getName() ) ) {
2161 $ip = $this->getName();
2163 $ip = $this->getRequest()->getIP();
2165 // Avoid PHP 7.1 warning of passing $this by reference
2169 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2171 if ( $blocked && $block === null ) {
2172 // back-compat: UserIsBlockedGlobally didn't have $block param first
2173 $block = new SystemBlock( [
2175 'systemBlock' => 'global-block'
2179 $this->mGlobalBlock
= $blocked ?
$block : false;
2180 return $this->mGlobalBlock ?
: null;
2184 * Check if user account is locked
2186 * @return bool True if locked, false otherwise
2188 public function isLocked() {
2189 if ( $this->mLocked
!== null ) {
2190 return $this->mLocked
;
2193 $this->mLocked
= false;
2194 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2195 return $this->mLocked
;
2199 * Check if user account is hidden
2201 * @return bool True if hidden, false otherwise
2203 public function isHidden() {
2204 if ( $this->mHideName
!== null ) {
2205 return (bool)$this->mHideName
;
2207 $this->getBlockedStatus();
2208 if ( !$this->mHideName
) {
2210 $this->mHideName
= false;
2211 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2213 return (bool)$this->mHideName
;
2217 * Get the user's ID.
2218 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2220 public function getId() {
2221 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2222 // Special case, we know the user is anonymous
2226 if ( !$this->isItemLoaded( 'id' ) ) {
2227 // Don't load if this was initialized from an ID
2231 return (int)$this->mId
;
2235 * Set the user and reload all fields according to a given ID
2236 * @param int $v User ID to reload
2238 public function setId( $v ) {
2240 $this->clearInstanceCache( 'id' );
2244 * Get the user name, or the IP of an anonymous user
2245 * @return string User's name or IP address
2247 public function getName() {
2248 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2249 // Special case optimisation
2250 return $this->mName
;
2254 if ( $this->mName
=== false ) {
2256 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2259 return $this->mName
;
2263 * Set the user name.
2265 * This does not reload fields from the database according to the given
2266 * name. Rather, it is used to create a temporary "nonexistent user" for
2267 * later addition to the database. It can also be used to set the IP
2268 * address for an anonymous user to something other than the current
2271 * @note User::newFromName() has roughly the same function, when the named user
2273 * @param string $str New user name to set
2275 public function setName( $str ) {
2277 $this->mName
= $str;
2281 * Get the user's actor ID.
2283 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2284 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2286 public function getActorId( IDatabase
$dbw = null ) {
2287 global $wgActorTableSchemaMigrationStage;
2289 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2290 // but it does little harm and might be needed for write callers loading a User.
2291 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2295 if ( !$this->isItemLoaded( 'actor' ) ) {
2299 // Currently $this->mActorId might be null if $this was loaded from a
2300 // cache entry that was written when $wgActorTableSchemaMigrationStage
2301 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2302 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2303 // has been removed), that condition may be removed.
2304 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2306 'actor_user' => $this->getId() ?
: null,
2307 'actor_name' => (string)$this->getName(),
2310 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2311 throw new CannotCreateActorException(
2312 'Cannot create an actor for a usable name that is not an existing user'
2315 if ( $q['actor_name'] === '' ) {
2316 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2318 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2319 if ( $dbw->affectedRows() ) {
2320 $this->mActorId
= (int)$dbw->insertId();
2323 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2324 $this->mActorId
= (int)$dbw->selectField(
2329 [ 'LOCK IN SHARE MODE' ]
2331 if ( !$this->mActorId
) {
2332 throw new CannotCreateActorException(
2333 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2337 $this->invalidateCache();
2339 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2340 $db = wfGetDB( $index );
2341 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2343 $this->setItemLoaded( 'actor' );
2346 return (int)$this->mActorId
;
2350 * Get the user's name escaped by underscores.
2351 * @return string Username escaped by underscores.
2353 public function getTitleKey() {
2354 return str_replace( ' ', '_', $this->getName() );
2358 * Check if the user has new messages.
2359 * @return bool True if the user has new messages
2361 public function getNewtalk() {
2364 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2365 if ( $this->mNewtalk
=== -1 ) {
2366 $this->mNewtalk
= false; # reset talk page status
2368 // Check memcached separately for anons, who have no
2369 // entire User object stored in there.
2370 if ( !$this->mId
) {
2371 global $wgDisableAnonTalk;
2372 if ( $wgDisableAnonTalk ) {
2373 // Anon newtalk disabled by configuration.
2374 $this->mNewtalk
= false;
2376 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2379 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2383 return (bool)$this->mNewtalk
;
2387 * Return the data needed to construct links for new talk page message
2388 * alerts. If there are new messages, this will return an associative array
2389 * with the following data:
2390 * wiki: The database name of the wiki
2391 * link: Root-relative link to the user's talk page
2392 * rev: The last talk page revision that the user has seen or null. This
2393 * is useful for building diff links.
2394 * If there are no new messages, it returns an empty array.
2395 * @note This function was designed to accomodate multiple talk pages, but
2396 * currently only returns a single link and revision.
2399 public function getNewMessageLinks() {
2400 // Avoid PHP 7.1 warning of passing $this by reference
2403 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2407 if ( !$this->getNewtalk() ) {
2410 $utp = $this->getTalkPage();
2411 $dbr = wfGetDB( DB_REPLICA
);
2412 // Get the "last viewed rev" timestamp from the oldest message notification
2413 $timestamp = $dbr->selectField( 'user_newtalk',
2414 'MIN(user_last_timestamp)',
2415 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2417 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2420 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2421 'link' => $utp->getLocalURL(),
2428 * Get the revision ID for the last talk page revision viewed by the talk
2430 * @return int|null Revision ID or null
2432 public function getNewMessageRevisionId() {
2433 $newMessageRevisionId = null;
2434 $newMessageLinks = $this->getNewMessageLinks();
2436 // Note: getNewMessageLinks() never returns more than a single link
2437 // and it is always for the same wiki, but we double-check here in
2438 // case that changes some time in the future.
2439 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2440 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2441 && $newMessageLinks[0]['rev']
2443 /** @var Revision $newMessageRevision */
2444 $newMessageRevision = $newMessageLinks[0]['rev'];
2445 $newMessageRevisionId = $newMessageRevision->getId();
2448 return $newMessageRevisionId;
2452 * Internal uncached check for new messages
2455 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2456 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2457 * @return bool True if the user has new messages
2459 protected function checkNewtalk( $field, $id ) {
2460 $dbr = wfGetDB( DB_REPLICA
);
2462 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2464 return $ok !== false;
2468 * Add or update the new messages flag
2469 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2470 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2471 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2472 * @return bool True if successful, false otherwise
2474 protected function updateNewtalk( $field, $id, $curRev = null ) {
2475 // Get timestamp of the talk page revision prior to the current one
2476 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2477 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2478 // Mark the user as having new messages since this revision
2479 $dbw = wfGetDB( DB_MASTER
);
2480 $dbw->insert( 'user_newtalk',
2481 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2484 if ( $dbw->affectedRows() ) {
2485 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2489 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2494 * Clear the new messages flag for the given user
2495 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2496 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2497 * @return bool True if successful, false otherwise
2499 protected function deleteNewtalk( $field, $id ) {
2500 $dbw = wfGetDB( DB_MASTER
);
2501 $dbw->delete( 'user_newtalk',
2504 if ( $dbw->affectedRows() ) {
2505 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2509 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2514 * Update the 'You have new messages!' status.
2515 * @param bool $val Whether the user has new messages
2516 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2517 * page. Ignored if null or !$val.
2519 public function setNewtalk( $val, $curRev = null ) {
2520 if ( wfReadOnly() ) {
2525 $this->mNewtalk
= $val;
2527 if ( $this->isAnon() ) {
2529 $id = $this->getName();
2532 $id = $this->getId();
2536 $changed = $this->updateNewtalk( $field, $id, $curRev );
2538 $changed = $this->deleteNewtalk( $field, $id );
2542 $this->invalidateCache();
2547 * Generate a current or new-future timestamp to be stored in the
2548 * user_touched field when we update things.
2550 * @return string Timestamp in TS_MW format
2552 private function newTouchedTimestamp() {
2554 if ( $this->mTouched
) {
2555 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2558 return wfTimestamp( TS_MW
, $time );
2562 * Clear user data from memcached
2564 * Use after applying updates to the database; caller's
2565 * responsibility to update user_touched if appropriate.
2567 * Called implicitly from invalidateCache() and saveSettings().
2569 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2571 public function clearSharedCache( $mode = 'refresh' ) {
2572 if ( !$this->getId() ) {
2576 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2577 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2578 $key = $this->getCacheKey( $cache );
2580 if ( $mode === 'refresh' ) {
2581 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2583 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2584 function () use ( $cache, $key ) {
2585 $cache->delete( $key );
2593 * Immediately touch the user data cache for this account
2595 * Calls touch() and removes account data from memcached
2597 public function invalidateCache() {
2599 $this->clearSharedCache( 'changed' );
2603 * Update the "touched" timestamp for the user
2605 * This is useful on various login/logout events when making sure that
2606 * a browser or proxy that has multiple tenants does not suffer cache
2607 * pollution where the new user sees the old users content. The value
2608 * of getTouched() is checked when determining 304 vs 200 responses.
2609 * Unlike invalidateCache(), this preserves the User object cache and
2610 * avoids database writes.
2614 public function touch() {
2615 $id = $this->getId();
2617 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2618 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2619 $cache->touchCheckKey( $key );
2620 $this->mQuickTouched
= null;
2625 * Validate the cache for this account.
2626 * @param string $timestamp A timestamp in TS_MW format
2629 public function validateCache( $timestamp ) {
2630 return ( $timestamp >= $this->getTouched() );
2634 * Get the user touched timestamp
2636 * Use this value only to validate caches via inequalities
2637 * such as in the case of HTTP If-Modified-Since response logic
2639 * @return string TS_MW Timestamp
2641 public function getTouched() {
2645 if ( $this->mQuickTouched
=== null ) {
2646 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2647 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2649 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2652 return max( $this->mTouched
, $this->mQuickTouched
);
2655 return $this->mTouched
;
2659 * Get the user_touched timestamp field (time of last DB updates)
2660 * @return string TS_MW Timestamp
2663 public function getDBTouched() {
2666 return $this->mTouched
;
2670 * Set the password and reset the random token.
2671 * Calls through to authentication plugin if necessary;
2672 * will have no effect if the auth plugin refuses to
2673 * pass the change through or if the legal password
2676 * As a special case, setting the password to null
2677 * wipes it, so the account cannot be logged in until
2678 * a new password is set, for instance via e-mail.
2680 * @deprecated since 1.27, use AuthManager instead
2681 * @param string $str New password to set
2682 * @throws PasswordError On failure
2685 public function setPassword( $str ) {
2686 wfDeprecated( __METHOD__
, '1.27' );
2687 return $this->setPasswordInternal( $str );
2691 * Set the password and reset the random token unconditionally.
2693 * @deprecated since 1.27, use AuthManager instead
2694 * @param string|null $str New password to set or null to set an invalid
2695 * password hash meaning that the user will not be able to log in
2696 * through the web interface.
2698 public function setInternalPassword( $str ) {
2699 wfDeprecated( __METHOD__
, '1.27' );
2700 $this->setPasswordInternal( $str );
2704 * Actually set the password and such
2705 * @since 1.27 cannot set a password for a user not in the database
2706 * @param string|null $str New password to set or null to set an invalid
2707 * password hash meaning that the user will not be able to log in
2708 * through the web interface.
2709 * @return bool Success
2711 private function setPasswordInternal( $str ) {
2712 $manager = AuthManager
::singleton();
2714 // If the user doesn't exist yet, fail
2715 if ( !$manager->userExists( $this->getName() ) ) {
2716 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2719 $status = $this->changeAuthenticationData( [
2720 'username' => $this->getName(),
2724 if ( !$status->isGood() ) {
2725 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2726 ->info( __METHOD__
. ': Password change rejected: '
2727 . $status->getWikiText( null, null, 'en' ) );
2731 $this->setOption( 'watchlisttoken', false );
2732 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2738 * Changes credentials of the user.
2740 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2741 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2742 * e.g. when no provider handled the change.
2744 * @param array $data A set of authentication data in fieldname => value format. This is the
2745 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2749 public function changeAuthenticationData( array $data ) {
2750 $manager = AuthManager
::singleton();
2751 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2752 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2754 $status = Status
::newGood( 'ignored' );
2755 foreach ( $reqs as $req ) {
2756 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2758 if ( $status->getValue() === 'ignored' ) {
2759 $status->warning( 'authenticationdatachange-ignored' );
2762 if ( $status->isGood() ) {
2763 foreach ( $reqs as $req ) {
2764 $manager->changeAuthenticationData( $req );
2771 * Get the user's current token.
2772 * @param bool $forceCreation Force the generation of a new token if the
2773 * user doesn't have one (default=true for backwards compatibility).
2774 * @return string|null Token
2776 public function getToken( $forceCreation = true ) {
2777 global $wgAuthenticationTokenVersion;
2780 if ( !$this->mToken
&& $forceCreation ) {
2784 if ( !$this->mToken
) {
2785 // The user doesn't have a token, return null to indicate that.
2789 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2790 // We return a random value here so existing token checks are very
2792 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2795 if ( $wgAuthenticationTokenVersion === null ) {
2796 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2797 return $this->mToken
;
2800 // $wgAuthenticationTokenVersion in use, so hmac it.
2801 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2803 // The raw hash can be overly long. Shorten it up.
2804 $len = max( 32, self
::TOKEN_LENGTH
);
2805 if ( strlen( $ret ) < $len ) {
2806 // Should never happen, even md5 is 128 bits
2807 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2810 return substr( $ret, -$len );
2814 * Set the random token (used for persistent authentication)
2815 * Called from loadDefaults() among other places.
2817 * @param string|bool $token If specified, set the token to this value
2819 public function setToken( $token = false ) {
2821 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2822 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2823 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2824 } elseif ( !$token ) {
2825 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2827 $this->mToken
= $token;
2832 * Set the password for a password reminder or new account email
2834 * @deprecated Removed in 1.27. Use PasswordReset instead.
2835 * @param string $str New password to set or null to set an invalid
2836 * password hash meaning that the user will not be able to use it
2837 * @param bool $throttle If true, reset the throttle timestamp to the present
2839 public function setNewpassword( $str, $throttle = true ) {
2840 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2844 * Get the user's e-mail address
2845 * @return string User's email address
2847 public function getEmail() {
2849 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2850 return $this->mEmail
;
2854 * Get the timestamp of the user's e-mail authentication
2855 * @return string TS_MW timestamp
2857 public function getEmailAuthenticationTimestamp() {
2859 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2860 return $this->mEmailAuthenticated
;
2864 * Set the user's e-mail address
2865 * @param string $str New e-mail address
2867 public function setEmail( $str ) {
2869 if ( $str == $this->mEmail
) {
2872 $this->invalidateEmail();
2873 $this->mEmail
= $str;
2874 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2878 * Set the user's e-mail address and a confirmation mail if needed.
2881 * @param string $str New e-mail address
2884 public function setEmailWithConfirmation( $str ) {
2885 global $wgEnableEmail, $wgEmailAuthentication;
2887 if ( !$wgEnableEmail ) {
2888 return Status
::newFatal( 'emaildisabled' );
2891 $oldaddr = $this->getEmail();
2892 if ( $str === $oldaddr ) {
2893 return Status
::newGood( true );
2896 $type = $oldaddr != '' ?
'changed' : 'set';
2897 $notificationResult = null;
2899 if ( $wgEmailAuthentication && $type === 'changed' ) {
2900 // Send the user an email notifying the user of the change in registered
2901 // email address on their previous email address
2902 $change = $str != '' ?
'changed' : 'removed';
2903 $notificationResult = $this->sendMail(
2904 wfMessage( 'notificationemail_subject_' . $change )->text(),
2905 wfMessage( 'notificationemail_body_' . $change,
2906 $this->getRequest()->getIP(),
2912 $this->setEmail( $str );
2914 if ( $str !== '' && $wgEmailAuthentication ) {
2915 // Send a confirmation request to the new address if needed
2916 $result = $this->sendConfirmationMail( $type );
2918 if ( $notificationResult !== null ) {
2919 $result->merge( $notificationResult );
2922 if ( $result->isGood() ) {
2923 // Say to the caller that a confirmation and notification mail has been sent
2924 $result->value
= 'eauth';
2927 $result = Status
::newGood( true );
2934 * Get the user's real name
2935 * @return string User's real name
2937 public function getRealName() {
2938 if ( !$this->isItemLoaded( 'realname' ) ) {
2942 return $this->mRealName
;
2946 * Set the user's real name
2947 * @param string $str New real name
2949 public function setRealName( $str ) {
2951 $this->mRealName
= $str;
2955 * Get the user's current setting for a given option.
2957 * @param string $oname The option to check
2958 * @param string|array|null $defaultOverride A default value returned if the option does not exist
2959 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2960 * @return string|array|int|null User's current value for the option
2961 * @see getBoolOption()
2962 * @see getIntOption()
2964 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2965 global $wgHiddenPrefs;
2966 $this->loadOptions();
2968 # We want 'disabled' preferences to always behave as the default value for
2969 # users, even if they have set the option explicitly in their settings (ie they
2970 # set it, and then it was disabled removing their ability to change it). But
2971 # we don't want to erase the preferences in the database in case the preference
2972 # is re-enabled again. So don't touch $mOptions, just override the returned value
2973 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2974 return self
::getDefaultOption( $oname );
2977 if ( array_key_exists( $oname, $this->mOptions
) ) {
2978 return $this->mOptions
[$oname];
2981 return $defaultOverride;
2985 * Get all user's options
2987 * @param int $flags Bitwise combination of:
2988 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2989 * to the default value. (Since 1.25)
2992 public function getOptions( $flags = 0 ) {
2993 global $wgHiddenPrefs;
2994 $this->loadOptions();
2995 $options = $this->mOptions
;
2997 # We want 'disabled' preferences to always behave as the default value for
2998 # users, even if they have set the option explicitly in their settings (ie they
2999 # set it, and then it was disabled removing their ability to change it). But
3000 # we don't want to erase the preferences in the database in case the preference
3001 # is re-enabled again. So don't touch $mOptions, just override the returned value
3002 foreach ( $wgHiddenPrefs as $pref ) {
3003 $default = self
::getDefaultOption( $pref );
3004 if ( $default !== null ) {
3005 $options[$pref] = $default;
3009 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3010 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3017 * Get the user's current setting for a given option, as a boolean value.
3019 * @param string $oname The option to check
3020 * @return bool User's current value for the option
3023 public function getBoolOption( $oname ) {
3024 return (bool)$this->getOption( $oname );
3028 * Get the user's current setting for a given option, as an integer value.
3030 * @param string $oname The option to check
3031 * @param int $defaultOverride A default value returned if the option does not exist
3032 * @return int User's current value for the option
3035 public function getIntOption( $oname, $defaultOverride = 0 ) {
3036 $val = $this->getOption( $oname );
3038 $val = $defaultOverride;
3040 return intval( $val );
3044 * Set the given option for a user.
3046 * You need to call saveSettings() to actually write to the database.
3048 * @param string $oname The option to set
3049 * @param mixed $val New value to set
3051 public function setOption( $oname, $val ) {
3052 $this->loadOptions();
3054 // Explicitly NULL values should refer to defaults
3055 if ( is_null( $val ) ) {
3056 $val = self
::getDefaultOption( $oname );
3059 $this->mOptions
[$oname] = $val;
3063 * Get a token stored in the preferences (like the watchlist one),
3064 * resetting it if it's empty (and saving changes).
3066 * @param string $oname The option name to retrieve the token from
3067 * @return string|bool User's current value for the option, or false if this option is disabled.
3068 * @see resetTokenFromOption()
3070 * @deprecated since 1.26 Applications should use the OAuth extension
3072 public function getTokenFromOption( $oname ) {
3073 global $wgHiddenPrefs;
3075 $id = $this->getId();
3076 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3080 $token = $this->getOption( $oname );
3082 // Default to a value based on the user token to avoid space
3083 // wasted on storing tokens for all users. When this option
3084 // is set manually by the user, only then is it stored.
3085 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3092 * Reset a token stored in the preferences (like the watchlist one).
3093 * *Does not* save user's preferences (similarly to setOption()).
3095 * @param string $oname The option name to reset the token in
3096 * @return string|bool New token value, or false if this option is disabled.
3097 * @see getTokenFromOption()
3100 public function resetTokenFromOption( $oname ) {
3101 global $wgHiddenPrefs;
3102 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3106 $token = MWCryptRand
::generateHex( 40 );
3107 $this->setOption( $oname, $token );
3112 * Return a list of the types of user options currently returned by
3113 * User::getOptionKinds().
3115 * Currently, the option kinds are:
3116 * - 'registered' - preferences which are registered in core MediaWiki or
3117 * by extensions using the UserGetDefaultOptions hook.
3118 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3119 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3120 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3121 * be used by user scripts.
3122 * - 'special' - "preferences" that are not accessible via User::getOptions
3123 * or User::setOptions.
3124 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3125 * These are usually legacy options, removed in newer versions.
3127 * The API (and possibly others) use this function to determine the possible
3128 * option types for validation purposes, so make sure to update this when a
3129 * new option kind is added.
3131 * @see User::getOptionKinds
3132 * @return array Option kinds
3134 public static function listOptionKinds() {
3137 'registered-multiselect',
3138 'registered-checkmatrix',
3146 * Return an associative array mapping preferences keys to the kind of a preference they're
3147 * used for. Different kinds are handled differently when setting or reading preferences.
3149 * See User::listOptionKinds for the list of valid option types that can be provided.
3151 * @see User::listOptionKinds
3152 * @param IContextSource $context
3153 * @param array|null $options Assoc. array with options keys to check as keys.
3154 * Defaults to $this->mOptions.
3155 * @return array The key => kind mapping data
3157 public function getOptionKinds( IContextSource
$context, $options = null ) {
3158 $this->loadOptions();
3159 if ( $options === null ) {
3160 $options = $this->mOptions
;
3163 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3164 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3167 // Pull out the "special" options, so they don't get converted as
3168 // multiselect or checkmatrix.
3169 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3170 foreach ( $specialOptions as $name => $value ) {
3171 unset( $prefs[$name] );
3174 // Multiselect and checkmatrix options are stored in the database with
3175 // one key per option, each having a boolean value. Extract those keys.
3176 $multiselectOptions = [];
3177 foreach ( $prefs as $name => $info ) {
3178 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3179 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3180 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3181 $prefix = $info['prefix'] ??
$name;
3183 foreach ( $opts as $value ) {
3184 $multiselectOptions["$prefix$value"] = true;
3187 unset( $prefs[$name] );
3190 $checkmatrixOptions = [];
3191 foreach ( $prefs as $name => $info ) {
3192 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3193 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3194 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3195 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3196 $prefix = $info['prefix'] ??
$name;
3198 foreach ( $columns as $column ) {
3199 foreach ( $rows as $row ) {
3200 $checkmatrixOptions["$prefix$column-$row"] = true;
3204 unset( $prefs[$name] );
3208 // $value is ignored
3209 foreach ( $options as $key => $value ) {
3210 if ( isset( $prefs[$key] ) ) {
3211 $mapping[$key] = 'registered';
3212 } elseif ( isset( $multiselectOptions[$key] ) ) {
3213 $mapping[$key] = 'registered-multiselect';
3214 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3215 $mapping[$key] = 'registered-checkmatrix';
3216 } elseif ( isset( $specialOptions[$key] ) ) {
3217 $mapping[$key] = 'special';
3218 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3219 $mapping[$key] = 'userjs';
3221 $mapping[$key] = 'unused';
3229 * Reset certain (or all) options to the site defaults
3231 * The optional parameter determines which kinds of preferences will be reset.
3232 * Supported values are everything that can be reported by getOptionKinds()
3233 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3235 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3236 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3237 * for backwards-compatibility.
3238 * @param IContextSource|null $context Context source used when $resetKinds
3239 * does not contain 'all', passed to getOptionKinds().
3240 * Defaults to RequestContext::getMain() when null.
3242 public function resetOptions(
3243 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3244 IContextSource
$context = null
3247 $defaultOptions = self
::getDefaultOptions();
3249 if ( !is_array( $resetKinds ) ) {
3250 $resetKinds = [ $resetKinds ];
3253 if ( in_array( 'all', $resetKinds ) ) {
3254 $newOptions = $defaultOptions;
3256 if ( $context === null ) {
3257 $context = RequestContext
::getMain();
3260 $optionKinds = $this->getOptionKinds( $context );
3261 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3264 // Use default values for the options that should be deleted, and
3265 // copy old values for the ones that shouldn't.
3266 foreach ( $this->mOptions
as $key => $value ) {
3267 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3268 if ( array_key_exists( $key, $defaultOptions ) ) {
3269 $newOptions[$key] = $defaultOptions[$key];
3272 $newOptions[$key] = $value;
3277 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3279 $this->mOptions
= $newOptions;
3280 $this->mOptionsLoaded
= true;
3284 * Get the user's preferred date format.
3285 * @return string User's preferred date format
3287 public function getDatePreference() {
3288 // Important migration for old data rows
3289 if ( is_null( $this->mDatePreference
) ) {
3291 $value = $this->getOption( 'date' );
3292 $map = $wgLang->getDatePreferenceMigrationMap();
3293 if ( isset( $map[$value] ) ) {
3294 $value = $map[$value];
3296 $this->mDatePreference
= $value;
3298 return $this->mDatePreference
;
3302 * Determine based on the wiki configuration and the user's options,
3303 * whether this user must be over HTTPS no matter what.
3307 public function requiresHTTPS() {
3308 global $wgSecureLogin;
3309 if ( !$wgSecureLogin ) {
3313 $https = $this->getBoolOption( 'prefershttps' );
3314 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3316 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3323 * Get the user preferred stub threshold
3327 public function getStubThreshold() {
3328 global $wgMaxArticleSize; # Maximum article size, in Kb
3329 $threshold = $this->getIntOption( 'stubthreshold' );
3330 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3331 // If they have set an impossible value, disable the preference
3332 // so we can use the parser cache again.
3339 * Get the permissions this user has.
3340 * @return string[] permission names
3342 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
3343 * ->getUserPermissions(..) instead
3346 public function getRights() {
3347 return MediaWikiServices
::getInstance()->getPermissionManager()->getUserPermissions( $this );
3351 * Get the list of explicit group memberships this user has.
3352 * The implicit * and user groups are not included.
3354 * @return string[] Array of internal group names (sorted since 1.33)
3356 public function getGroups() {
3358 $this->loadGroups();
3359 return array_keys( $this->mGroupMemberships
);
3363 * Get the list of explicit group memberships this user has, stored as
3364 * UserGroupMembership objects. Implicit groups are not included.
3366 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3369 public function getGroupMemberships() {
3371 $this->loadGroups();
3372 return $this->mGroupMemberships
;
3376 * Get the list of implicit group memberships this user has.
3377 * This includes all explicit groups, plus 'user' if logged in,
3378 * '*' for all accounts, and autopromoted groups
3379 * @param bool $recache Whether to avoid the cache
3380 * @return array Array of String internal group names
3382 public function getEffectiveGroups( $recache = false ) {
3383 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3384 $this->mEffectiveGroups
= array_unique( array_merge(
3385 $this->getGroups(), // explicit groups
3386 $this->getAutomaticGroups( $recache ) // implicit groups
3388 // Avoid PHP 7.1 warning of passing $this by reference
3390 // Hook for additional groups
3391 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3392 // Force reindexation of groups when a hook has unset one of them
3393 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3395 return $this->mEffectiveGroups
;
3399 * Get the list of implicit group memberships this user has.
3400 * This includes 'user' if logged in, '*' for all accounts,
3401 * and autopromoted groups
3402 * @param bool $recache Whether to avoid the cache
3403 * @return array Array of String internal group names
3405 public function getAutomaticGroups( $recache = false ) {
3406 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3407 $this->mImplicitGroups
= [ '*' ];
3408 if ( $this->getId() ) {
3409 $this->mImplicitGroups
[] = 'user';
3411 $this->mImplicitGroups
= array_unique( array_merge(
3412 $this->mImplicitGroups
,
3413 Autopromote
::getAutopromoteGroups( $this )
3417 // Assure data consistency with rights/groups,
3418 // as getEffectiveGroups() depends on this function
3419 $this->mEffectiveGroups
= null;
3422 return $this->mImplicitGroups
;
3426 * Returns the groups the user has belonged to.
3428 * The user may still belong to the returned groups. Compare with getGroups().
3430 * The function will not return groups the user had belonged to before MW 1.17
3432 * @return array Names of the groups the user has belonged to.
3434 public function getFormerGroups() {
3437 if ( is_null( $this->mFormerGroups
) ) {
3438 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3439 ?
wfGetDB( DB_MASTER
)
3440 : wfGetDB( DB_REPLICA
);
3441 $res = $db->select( 'user_former_groups',
3443 [ 'ufg_user' => $this->mId
],
3445 $this->mFormerGroups
= [];
3446 foreach ( $res as $row ) {
3447 $this->mFormerGroups
[] = $row->ufg_group
;
3451 return $this->mFormerGroups
;
3455 * Get the user's edit count.
3456 * @return int|null Null for anonymous users
3458 public function getEditCount() {
3459 if ( !$this->getId() ) {
3463 if ( $this->mEditCount
=== null ) {
3464 /* Populate the count, if it has not been populated yet */
3465 $dbr = wfGetDB( DB_REPLICA
);
3466 // check if the user_editcount field has been initialized
3467 $count = $dbr->selectField(
3468 'user', 'user_editcount',
3469 [ 'user_id' => $this->mId
],
3473 if ( $count === null ) {
3474 // it has not been initialized. do so.
3475 $count = $this->initEditCountInternal();
3477 $this->mEditCount
= $count;
3479 return (int)$this->mEditCount
;
3483 * Add the user to the given group. This takes immediate effect.
3484 * If the user is already in the group, the expiry time will be updated to the new
3485 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3488 * @param string $group Name of the group to add
3489 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3490 * wfTimestamp(), or null if the group assignment should not expire
3493 public function addGroup( $group, $expiry = null ) {
3495 $this->loadGroups();
3498 $expiry = wfTimestamp( TS_MW
, $expiry );
3501 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3505 // create the new UserGroupMembership and put it in the DB
3506 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3507 if ( !$ugm->insert( true ) ) {
3511 $this->mGroupMemberships
[$group] = $ugm;
3513 // Refresh the groups caches, and clear the rights cache so it will be
3514 // refreshed on the next call to $this->getRights().
3515 $this->getEffectiveGroups( true );
3516 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3517 $this->invalidateCache();
3523 * Remove the user from the given group.
3524 * This takes immediate effect.
3525 * @param string $group Name of the group to remove
3528 public function removeGroup( $group ) {
3531 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3535 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3536 // delete the membership entry
3537 if ( !$ugm ||
!$ugm->delete() ) {
3541 $this->loadGroups();
3542 unset( $this->mGroupMemberships
[$group] );
3544 // Refresh the groups caches, and clear the rights cache so it will be
3545 // refreshed on the next call to $this->getRights().
3546 $this->getEffectiveGroups( true );
3547 MediaWikiServices
::getInstance()->getPermissionManager()->invalidateUsersRightsCache( $this );
3548 $this->invalidateCache();
3554 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3555 * only this new name and not the old isLoggedIn() variant.
3557 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3558 * anonymous or has no local account (which can happen when importing). This is equivalent to
3559 * getId() != 0 and is provided for code readability.
3562 public function isRegistered() {
3563 return $this->getId() != 0;
3567 * Get whether the user is logged in
3570 public function isLoggedIn() {
3571 return $this->isRegistered();
3575 * Get whether the user is anonymous
3578 public function isAnon() {
3579 return !$this->isRegistered();
3583 * @return bool Whether this user is flagged as being a bot role account
3586 public function isBot() {
3587 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3592 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3598 * Check if user is allowed to access a feature / make an action
3600 * @param string $permissions,... Permissions to test
3601 * @return bool True if user is allowed to perform *any* of the given actions
3603 public function isAllowedAny() {
3604 $permissions = func_get_args();
3605 foreach ( $permissions as $permission ) {
3606 if ( $this->isAllowed( $permission ) ) {
3615 * @param string $permissions,... Permissions to test
3616 * @return bool True if the user is allowed to perform *all* of the given actions
3618 public function isAllowedAll() {
3619 $permissions = func_get_args();
3620 foreach ( $permissions as $permission ) {
3621 if ( !$this->isAllowed( $permission ) ) {
3629 * Internal mechanics of testing a permission
3631 * @deprecated since 1.34, use MediaWikiServices::getInstance()
3632 * ->getPermissionManager()->userHasRight(...) instead
3634 * @param string $action
3638 public function isAllowed( $action = '' ) {
3639 return MediaWikiServices
::getInstance()->getPermissionManager()
3640 ->userHasRight( $this, $action );
3644 * Check whether to enable recent changes patrol features for this user
3645 * @return bool True or false
3647 public function useRCPatrol() {
3648 global $wgUseRCPatrol;
3649 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3653 * Check whether to enable new pages patrol features for this user
3654 * @return bool True or false
3656 public function useNPPatrol() {
3657 global $wgUseRCPatrol, $wgUseNPPatrol;
3659 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3660 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3665 * Check whether to enable new files patrol features for this user
3666 * @return bool True or false
3668 public function useFilePatrol() {
3669 global $wgUseRCPatrol, $wgUseFilePatrol;
3671 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3672 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3677 * Get the WebRequest object to use with this object
3679 * @return WebRequest
3681 public function getRequest() {
3682 if ( $this->mRequest
) {
3683 return $this->mRequest
;
3691 * Check the watched status of an article.
3692 * @since 1.22 $checkRights parameter added
3693 * @param Title $title Title of the article to look at
3694 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3695 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3698 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3699 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3700 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3707 * @since 1.22 $checkRights parameter added
3708 * @param Title $title Title of the article to look at
3709 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3710 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3712 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3713 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3714 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3716 [ $title->getSubjectPage(), $title->getTalkPage() ]
3719 $this->invalidateCache();
3723 * Stop watching an article.
3724 * @since 1.22 $checkRights parameter added
3725 * @param Title $title Title of the article to look at
3726 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3727 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3729 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3730 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3731 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3732 $store->removeWatch( $this, $title->getSubjectPage() );
3733 $store->removeWatch( $this, $title->getTalkPage() );
3735 $this->invalidateCache();
3739 * Clear the user's notification timestamp for the given title.
3740 * If e-notif e-mails are on, they will receive notification mails on
3741 * the next change of the page if it's watched etc.
3742 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3743 * @param Title &$title Title of the article to look at
3744 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3746 public function clearNotification( &$title, $oldid = 0 ) {
3747 global $wgUseEnotif, $wgShowUpdatedMarker;
3749 // Do nothing if the database is locked to writes
3750 if ( wfReadOnly() ) {
3754 // Do nothing if not allowed to edit the watchlist
3755 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3759 // If we're working on user's talk page, we should update the talk page message indicator
3760 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3761 // Avoid PHP 7.1 warning of passing $this by reference
3763 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3767 // Try to update the DB post-send and only if needed...
3768 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3769 if ( !$this->getNewtalk() ) {
3770 return; // no notifications to clear
3773 // Delete the last notifications (they stack up)
3774 $this->setNewtalk( false );
3776 // If there is a new, unseen, revision, use its timestamp
3778 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3781 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3786 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3790 if ( $this->isAnon() ) {
3791 // Nothing else to do...
3795 // Only update the timestamp if the page is being watched.
3796 // The query to find out if it is watched is cached both in memcached and per-invocation,
3797 // and when it does have to be executed, it can be on a replica DB
3798 // If this is the user's newtalk page, we always update the timestamp
3800 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3804 MediaWikiServices
::getInstance()->getWatchedItemStore()
3805 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3809 * Resets all of the given user's page-change notification timestamps.
3810 * If e-notif e-mails are on, they will receive notification mails on
3811 * the next change of any watched page.
3812 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3814 public function clearAllNotifications() {
3815 global $wgUseEnotif, $wgShowUpdatedMarker;
3816 // Do nothing if not allowed to edit the watchlist
3817 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3821 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3822 $this->setNewtalk( false );
3826 $id = $this->getId();
3831 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3832 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3834 // We also need to clear here the "you have new message" notification for the own
3835 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3839 * Compute experienced level based on edit count and registration date.
3841 * @return string 'newcomer', 'learner', or 'experienced'
3843 public function getExperienceLevel() {
3844 global $wgLearnerEdits,
3845 $wgExperiencedUserEdits,
3846 $wgLearnerMemberSince,
3847 $wgExperiencedUserMemberSince;
3849 if ( $this->isAnon() ) {
3853 $editCount = $this->getEditCount();
3854 $registration = $this->getRegistration();
3856 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3857 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3859 if ( $editCount < $wgLearnerEdits ||
3860 $registration > $learnerRegistration ) {
3864 if ( $editCount > $wgExperiencedUserEdits &&
3865 $registration <= $experiencedRegistration
3867 return 'experienced';
3874 * Persist this user's session (e.g. set cookies)
3876 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3878 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3879 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3881 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3883 if ( $this->mId
== 0 ) {
3887 $session = $this->getRequest()->getSession();
3888 if ( $request && $session->getRequest() !== $request ) {
3889 $session = $session->sessionWithRequest( $request );
3891 $delay = $session->delaySave();
3893 if ( !$session->getUser()->equals( $this ) ) {
3894 if ( !$session->canSetUser() ) {
3895 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3896 ->warning( __METHOD__
.
3897 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3901 $session->setUser( $this );
3904 $session->setRememberUser( $rememberMe );
3905 if ( $secure !== null ) {
3906 $session->setForceHTTPS( $secure );
3909 $session->persist();
3911 ScopedCallback
::consume( $delay );
3915 * Log this user out.
3917 public function logout() {
3918 // Avoid PHP 7.1 warning of passing $this by reference
3920 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
3926 * Clear the user's session, and reset the instance cache.
3929 public function doLogout() {
3930 $session = $this->getRequest()->getSession();
3931 if ( !$session->canSetUser() ) {
3932 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3933 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3934 $error = 'immutable';
3935 } elseif ( !$session->getUser()->equals( $this ) ) {
3936 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3937 ->warning( __METHOD__
.
3938 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3940 // But we still may as well make this user object anon
3941 $this->clearInstanceCache( 'defaults' );
3942 $error = 'wronguser';
3944 $this->clearInstanceCache( 'defaults' );
3945 $delay = $session->delaySave();
3946 $session->unpersist(); // Clear cookies (T127436)
3947 $session->setLoggedOutTimestamp( time() );
3948 $session->setUser( new User
);
3949 $session->set( 'wsUserID', 0 ); // Other code expects this
3950 $session->resetAllTokens();
3951 ScopedCallback
::consume( $delay );
3954 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3955 'event' => 'logout',
3956 'successful' => $error === false,
3957 'status' => $error ?
: 'success',
3962 * Save this user's settings into the database.
3963 * @todo Only rarely do all these fields need to be set!
3965 public function saveSettings() {
3966 if ( wfReadOnly() ) {
3967 // @TODO: caller should deal with this instead!
3968 // This should really just be an exception.
3969 MWExceptionHandler
::logException( new DBExpectedError(
3971 "Could not update user with ID '{$this->mId}'; DB is read-only."
3977 if ( $this->mId
== 0 ) {
3981 // Get a new user_touched that is higher than the old one.
3982 // This will be used for a CAS check as a last-resort safety
3983 // check against race conditions and replica DB lag.
3984 $newTouched = $this->newTouchedTimestamp();
3986 $dbw = wfGetDB( DB_MASTER
);
3987 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
3988 global $wgActorTableSchemaMigrationStage;
3990 $dbw->update( 'user',
3992 'user_name' => $this->mName
,
3993 'user_real_name' => $this->mRealName
,
3994 'user_email' => $this->mEmail
,
3995 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3996 'user_touched' => $dbw->timestamp( $newTouched ),
3997 'user_token' => strval( $this->mToken
),
3998 'user_email_token' => $this->mEmailToken
,
3999 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4000 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4001 'user_id' => $this->mId
,
4005 if ( !$dbw->affectedRows() ) {
4006 // Maybe the problem was a missed cache update; clear it to be safe
4007 $this->clearSharedCache( 'refresh' );
4008 // User was changed in the meantime or loaded with stale data
4009 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4010 LoggerFactory
::getInstance( 'preferences' )->warning(
4011 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4012 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4014 throw new MWException( "CAS update failed on user_touched. " .
4015 "The version of the user to be saved is older than the current version."
4019 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4022 [ 'actor_name' => $this->mName
],
4023 [ 'actor_user' => $this->mId
],
4029 $this->mTouched
= $newTouched;
4030 $this->saveOptions();
4032 Hooks
::run( 'UserSaveSettings', [ $this ] );
4033 $this->clearSharedCache( 'changed' );
4034 $this->getUserPage()->purgeSquid();
4038 * If only this user's username is known, and it exists, return the user ID.
4040 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4043 public function idForName( $flags = 0 ) {
4044 $s = trim( $this->getName() );
4049 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4050 ?
wfGetDB( DB_MASTER
)
4051 : wfGetDB( DB_REPLICA
);
4053 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4054 ?
[ 'LOCK IN SHARE MODE' ]
4057 $id = $db->selectField( 'user',
4058 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4064 * Add a user to the database, return the user object
4066 * @param string $name Username to add
4067 * @param array $params Array of Strings Non-default parameters to save to
4068 * the database as user_* fields:
4069 * - email: The user's email address.
4070 * - email_authenticated: The email authentication timestamp.
4071 * - real_name: The user's real name.
4072 * - options: An associative array of non-default options.
4073 * - token: Random authentication token. Do not set.
4074 * - registration: Registration timestamp. Do not set.
4076 * @return User|null User object, or null if the username already exists.
4078 public static function createNew( $name, $params = [] ) {
4079 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4080 if ( isset( $params[$field] ) ) {
4081 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4082 unset( $params[$field] );
4088 $user->setToken(); // init token
4089 if ( isset( $params['options'] ) ) {
4090 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4091 unset( $params['options'] );
4093 $dbw = wfGetDB( DB_MASTER
);
4095 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4098 'user_name' => $name,
4099 'user_password' => $noPass,
4100 'user_newpassword' => $noPass,
4101 'user_email' => $user->mEmail
,
4102 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4103 'user_real_name' => $user->mRealName
,
4104 'user_token' => strval( $user->mToken
),
4105 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4106 'user_editcount' => 0,
4107 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4109 foreach ( $params as $name => $value ) {
4110 $fields["user_$name"] = $value;
4113 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4114 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4115 if ( $dbw->affectedRows() ) {
4116 $newUser = self
::newFromId( $dbw->insertId() );
4117 $newUser->mName
= $fields['user_name'];
4118 $newUser->updateActorId( $dbw );
4119 // Load the user from master to avoid replica lag
4120 $newUser->load( self
::READ_LATEST
);
4129 * Add this existing user object to the database. If the user already
4130 * exists, a fatal status object is returned, and the user object is
4131 * initialised with the data from the database.
4133 * Previously, this function generated a DB error due to a key conflict
4134 * if the user already existed. Many extension callers use this function
4135 * in code along the lines of:
4137 * $user = User::newFromName( $name );
4138 * if ( !$user->isLoggedIn() ) {
4139 * $user->addToDatabase();
4141 * // do something with $user...
4143 * However, this was vulnerable to a race condition (T18020). By
4144 * initialising the user object if the user exists, we aim to support this
4145 * calling sequence as far as possible.
4147 * Note that if the user exists, this function will acquire a write lock,
4148 * so it is still advisable to make the call conditional on isLoggedIn(),
4149 * and to commit the transaction after calling.
4151 * @throws MWException
4154 public function addToDatabase() {
4156 if ( !$this->mToken
) {
4157 $this->setToken(); // init token
4160 if ( !is_string( $this->mName
) ) {
4161 throw new RuntimeException( "User name field is not set." );
4164 $this->mTouched
= $this->newTouchedTimestamp();
4166 $dbw = wfGetDB( DB_MASTER
);
4167 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4168 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4169 $dbw->insert( 'user',
4171 'user_name' => $this->mName
,
4172 'user_password' => $noPass,
4173 'user_newpassword' => $noPass,
4174 'user_email' => $this->mEmail
,
4175 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4176 'user_real_name' => $this->mRealName
,
4177 'user_token' => strval( $this->mToken
),
4178 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4179 'user_editcount' => 0,
4180 'user_touched' => $dbw->timestamp( $this->mTouched
),
4184 if ( !$dbw->affectedRows() ) {
4185 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4186 $this->mId
= $dbw->selectField(
4189 [ 'user_name' => $this->mName
],
4191 [ 'LOCK IN SHARE MODE' ]
4194 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4198 throw new MWException( $fname . ": hit a key conflict attempting " .
4199 "to insert user '{$this->mName}' row, but it was not present in select!" );
4201 return Status
::newFatal( 'userexists' );
4203 $this->mId
= $dbw->insertId();
4204 self
::$idCacheByName[$this->mName
] = $this->mId
;
4205 $this->updateActorId( $dbw );
4207 return Status
::newGood();
4209 if ( !$status->isGood() ) {
4213 // Clear instance cache other than user table data and actor, which is already accurate
4214 $this->clearInstanceCache();
4216 $this->saveOptions();
4217 return Status
::newGood();
4221 * Update the actor ID after an insert
4222 * @param IDatabase $dbw Writable database handle
4224 private function updateActorId( IDatabase
$dbw ) {
4225 global $wgActorTableSchemaMigrationStage;
4227 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4230 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4233 $this->mActorId
= (int)$dbw->insertId();
4238 * If this user is logged-in and blocked,
4239 * block any IP address they've successfully logged in from.
4240 * @return bool A block was spread
4242 public function spreadAnyEditBlock() {
4243 if ( $this->isLoggedIn() && $this->getBlock() ) {
4244 return $this->spreadBlock();
4251 * If this (non-anonymous) user is blocked,
4252 * block the IP address they've successfully logged in from.
4253 * @return bool A block was spread
4255 protected function spreadBlock() {
4256 wfDebug( __METHOD__
. "()\n" );
4258 if ( $this->mId
== 0 ) {
4262 $userblock = DatabaseBlock
::newFromTarget( $this->getName() );
4263 if ( !$userblock ) {
4267 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4271 * Get whether the user is explicitly blocked from account creation.
4272 * @return bool|AbstractBlock
4274 public function isBlockedFromCreateAccount() {
4275 $this->getBlockedStatus();
4276 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4277 return $this->mBlock
;
4280 # T15611: if the IP address the user is trying to create an account from is
4281 # blocked with createaccount disabled, prevent new account creation there even
4282 # when the user is logged in
4283 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4284 $this->mBlockedFromCreateAccount
= DatabaseBlock
::newFromTarget(
4285 null, $this->getRequest()->getIP()
4288 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4289 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4290 ?
$this->mBlockedFromCreateAccount
4295 * Get whether the user is blocked from using Special:Emailuser.
4298 public function isBlockedFromEmailuser() {
4299 $this->getBlockedStatus();
4300 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4304 * Get whether the user is blocked from using Special:Upload
4309 public function isBlockedFromUpload() {
4310 $this->getBlockedStatus();
4311 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4315 * Get whether the user is allowed to create an account.
4318 public function isAllowedToCreateAccount() {
4319 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4323 * Get this user's personal page title.
4325 * @return Title User's personal page title
4327 public function getUserPage() {
4328 return Title
::makeTitle( NS_USER
, $this->getName() );
4332 * Get this user's talk page title.
4334 * @return Title User's talk page title
4336 public function getTalkPage() {
4337 $title = $this->getUserPage();
4338 return $title->getTalkPage();
4342 * Determine whether the user is a newbie. Newbies are either
4343 * anonymous IPs, or the most recently created accounts.
4346 public function isNewbie() {
4347 return !$this->isAllowed( 'autoconfirmed' );
4351 * Check to see if the given clear-text password is one of the accepted passwords
4352 * @deprecated since 1.27, use AuthManager instead
4353 * @param string $password User password
4354 * @return bool True if the given password is correct, otherwise False
4356 public function checkPassword( $password ) {
4357 wfDeprecated( __METHOD__
, '1.27' );
4359 $manager = AuthManager
::singleton();
4360 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4361 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4363 'username' => $this->getName(),
4364 'password' => $password,
4367 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4368 switch ( $res->status
) {
4369 case AuthenticationResponse
::PASS
:
4371 case AuthenticationResponse
::FAIL
:
4372 // Hope it's not a PreAuthenticationProvider that failed...
4373 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4374 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4377 throw new BadMethodCallException(
4378 'AuthManager returned a response unsupported by ' . __METHOD__
4384 * Check if the given clear-text password matches the temporary password
4385 * sent by e-mail for password reset operations.
4387 * @deprecated since 1.27, use AuthManager instead
4388 * @param string $plaintext
4389 * @return bool True if matches, false otherwise
4391 public function checkTemporaryPassword( $plaintext ) {
4392 wfDeprecated( __METHOD__
, '1.27' );
4393 // Can't check the temporary password individually.
4394 return $this->checkPassword( $plaintext );
4398 * Initialize (if necessary) and return a session token value
4399 * which can be used in edit forms to show that the user's
4400 * login credentials aren't being hijacked with a foreign form
4404 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4405 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4406 * @return MediaWiki\Session\Token The new edit token
4408 public function getEditTokenObject( $salt = '', $request = null ) {
4409 if ( $this->isAnon() ) {
4410 return new LoggedOutEditToken();
4414 $request = $this->getRequest();
4416 return $request->getSession()->getToken( $salt );
4420 * Initialize (if necessary) and return a session token value
4421 * which can be used in edit forms to show that the user's
4422 * login credentials aren't being hijacked with a foreign form
4425 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4428 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4429 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4430 * @return string The new edit token
4432 public function getEditToken( $salt = '', $request = null ) {
4433 return $this->getEditTokenObject( $salt, $request )->toString();
4437 * Check given value against the token value stored in the session.
4438 * A match should confirm that the form was submitted from the
4439 * user's own login session, not a form submission from a third-party
4442 * @param string $val Input value to compare
4443 * @param string|array $salt Optional function-specific data for hashing
4444 * @param WebRequest|null $request Object to use or null to use $wgRequest
4445 * @param int|null $maxage Fail tokens older than this, in seconds
4446 * @return bool Whether the token matches
4448 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4449 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4453 * Check given value against the token value stored in the session,
4454 * ignoring the suffix.
4456 * @param string $val Input value to compare
4457 * @param string|array $salt Optional function-specific data for hashing
4458 * @param WebRequest|null $request Object to use or null to use $wgRequest
4459 * @param int|null $maxage Fail tokens older than this, in seconds
4460 * @return bool Whether the token matches
4462 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4463 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4464 return $this->matchEditToken( $val, $salt, $request, $maxage );
4468 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4469 * mail to the user's given address.
4471 * @param string $type Message to send, either "created", "changed" or "set"
4474 public function sendConfirmationMail( $type = 'created' ) {
4476 $expiration = null; // gets passed-by-ref and defined in next line.
4477 $token = $this->confirmationToken( $expiration );
4478 $url = $this->confirmationTokenUrl( $token );
4479 $invalidateURL = $this->invalidationTokenUrl( $token );
4480 $this->saveSettings();
4482 if ( $type == 'created' ||
$type === false ) {
4483 $message = 'confirmemail_body';
4485 } elseif ( $type === true ) {
4486 $message = 'confirmemail_body_changed';
4489 // Messages: confirmemail_body_changed, confirmemail_body_set
4490 $message = 'confirmemail_body_' . $type;
4494 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4495 'body' => wfMessage( $message,
4496 $this->getRequest()->getIP(),
4499 $wgLang->userTimeAndDate( $expiration, $this ),
4501 $wgLang->userDate( $expiration, $this ),
4502 $wgLang->userTime( $expiration, $this ) )->text(),
4508 'ip' => $this->getRequest()->getIP(),
4509 'confirmURL' => $url,
4510 'invalidateURL' => $invalidateURL,
4511 'expiration' => $expiration
4514 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4515 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4519 * Send an e-mail to this user's account. Does not check for
4520 * confirmed status or validity.
4522 * @param string $subject Message subject
4523 * @param string $body Message body
4524 * @param User|null $from Optional sending user; if unspecified, default
4525 * $wgPasswordSender will be used.
4526 * @param MailAddress|null $replyto Reply-To address
4529 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4530 global $wgPasswordSender;
4532 if ( $from instanceof User
) {
4533 $sender = MailAddress
::newFromUser( $from );
4535 $sender = new MailAddress( $wgPasswordSender,
4536 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4538 $to = MailAddress
::newFromUser( $this );
4540 return UserMailer
::send( $to, $sender, $subject, $body, [
4541 'replyTo' => $replyto,
4546 * Generate, store, and return a new e-mail confirmation code.
4547 * A hash (unsalted, since it's used as a key) is stored.
4549 * @note Call saveSettings() after calling this function to commit
4550 * this change to the database.
4552 * @param string &$expiration Accepts the expiration time
4553 * @return string New token
4555 protected function confirmationToken( &$expiration ) {
4556 global $wgUserEmailConfirmationTokenExpiry;
4558 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4559 $expiration = wfTimestamp( TS_MW
, $expires );
4561 $token = MWCryptRand
::generateHex( 32 );
4562 $hash = md5( $token );
4563 $this->mEmailToken
= $hash;
4564 $this->mEmailTokenExpires
= $expiration;
4569 * Return a URL the user can use to confirm their email address.
4570 * @param string $token Accepts the email confirmation token
4571 * @return string New token URL
4573 protected function confirmationTokenUrl( $token ) {
4574 return $this->getTokenUrl( 'ConfirmEmail', $token );
4578 * Return a URL the user can use to invalidate their email address.
4579 * @param string $token Accepts the email confirmation token
4580 * @return string New token URL
4582 protected function invalidationTokenUrl( $token ) {
4583 return $this->getTokenUrl( 'InvalidateEmail', $token );
4587 * Internal function to format the e-mail validation/invalidation URLs.
4588 * This uses a quickie hack to use the
4589 * hardcoded English names of the Special: pages, for ASCII safety.
4591 * @note Since these URLs get dropped directly into emails, using the
4592 * short English names avoids insanely long URL-encoded links, which
4593 * also sometimes can get corrupted in some browsers/mailers
4594 * (T8957 with Gmail and Internet Explorer).
4596 * @param string $page Special page
4597 * @param string $token
4598 * @return string Formatted URL
4600 protected function getTokenUrl( $page, $token ) {
4601 // Hack to bypass localization of 'Special:'
4602 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4603 return $title->getCanonicalURL();
4607 * Mark the e-mail address confirmed.
4609 * @note Call saveSettings() after calling this function to commit the change.
4613 public function confirmEmail() {
4614 // Check if it's already confirmed, so we don't touch the database
4615 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4616 if ( !$this->isEmailConfirmed() ) {
4617 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4618 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4624 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4625 * address if it was already confirmed.
4627 * @note Call saveSettings() after calling this function to commit the change.
4628 * @return bool Returns true
4630 public function invalidateEmail() {
4632 $this->mEmailToken
= null;
4633 $this->mEmailTokenExpires
= null;
4634 $this->setEmailAuthenticationTimestamp( null );
4636 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4641 * Set the e-mail authentication timestamp.
4642 * @param string $timestamp TS_MW timestamp
4644 public function setEmailAuthenticationTimestamp( $timestamp ) {
4646 $this->mEmailAuthenticated
= $timestamp;
4647 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4651 * Is this user allowed to send e-mails within limits of current
4652 * site configuration?
4655 public function canSendEmail() {
4656 global $wgEnableEmail, $wgEnableUserEmail;
4657 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4660 $canSend = $this->isEmailConfirmed();
4661 // Avoid PHP 7.1 warning of passing $this by reference
4663 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4668 * Is this user allowed to receive e-mails within limits of current
4669 * site configuration?
4672 public function canReceiveEmail() {
4673 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4677 * Is this user's e-mail address valid-looking and confirmed within
4678 * limits of the current site configuration?
4680 * @note If $wgEmailAuthentication is on, this may require the user to have
4681 * confirmed their address by returning a code or using a password
4682 * sent to the address from the wiki.
4686 public function isEmailConfirmed() {
4687 global $wgEmailAuthentication;
4689 // Avoid PHP 7.1 warning of passing $this by reference
4692 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4693 if ( $this->isAnon() ) {
4696 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4699 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4709 * Check whether there is an outstanding request for e-mail confirmation.
4712 public function isEmailConfirmationPending() {
4713 global $wgEmailAuthentication;
4714 return $wgEmailAuthentication &&
4715 !$this->isEmailConfirmed() &&
4716 $this->mEmailToken
&&
4717 $this->mEmailTokenExpires
> wfTimestamp();
4721 * Get the timestamp of account creation.
4723 * @return string|bool|null Timestamp of account creation, false for
4724 * non-existent/anonymous user accounts, or null if existing account
4725 * but information is not in database.
4727 public function getRegistration() {
4728 if ( $this->isAnon() ) {
4732 return $this->mRegistration
;
4736 * Get the timestamp of the first edit
4738 * @return string|bool Timestamp of first edit, or false for
4739 * non-existent/anonymous user accounts.
4741 public function getFirstEditTimestamp() {
4742 return $this->getEditTimestamp( true );
4746 * Get the timestamp of the latest edit
4749 * @return string|bool Timestamp of first edit, or false for
4750 * non-existent/anonymous user accounts.
4752 public function getLatestEditTimestamp() {
4753 return $this->getEditTimestamp( false );
4757 * Get the timestamp of the first or latest edit
4759 * @param bool $first True for the first edit, false for the latest one
4760 * @return string|bool Timestamp of first or latest edit, or false for
4761 * non-existent/anonymous user accounts.
4763 private function getEditTimestamp( $first ) {
4764 if ( $this->getId() == 0 ) {
4765 return false; // anons
4767 $dbr = wfGetDB( DB_REPLICA
);
4768 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4769 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4770 ?
'revactor_timestamp' : 'rev_timestamp';
4771 $sortOrder = $first ?
'ASC' : 'DESC';
4772 $time = $dbr->selectField(
4773 [ 'revision' ] +
$actorWhere['tables'],
4775 [ $actorWhere['conds'] ],
4777 [ 'ORDER BY' => "$tsField $sortOrder" ],
4778 $actorWhere['joins']
4781 return false; // no edits
4783 return wfTimestamp( TS_MW
, $time );
4787 * Get the permissions associated with a given list of groups
4789 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4790 * ->getGroupPermissions() instead
4792 * @param array $groups Array of Strings List of internal group names
4793 * @return array Array of Strings List of permission key names for given groups combined
4795 public static function getGroupPermissions( $groups ) {
4796 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4800 * Get all the groups who have a given permission
4802 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4803 * ->getGroupsWithPermission() instead
4805 * @param string $role Role to check
4806 * @return array Array of Strings List of internal group names with the given permission
4808 public static function getGroupsWithPermission( $role ) {
4809 return MediaWikiServices
::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4813 * Check, if the given group has the given permission
4815 * If you're wanting to check whether all users have a permission, use
4816 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4819 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4820 * ->groupHasPermission(..) instead
4823 * @param string $group Group to check
4824 * @param string $role Role to check
4827 public static function groupHasPermission( $group, $role ) {
4828 return MediaWikiServices
::getInstance()->getPermissionManager()
4829 ->groupHasPermission( $group, $role );
4833 * Check if all users may be assumed to have the given permission
4835 * We generally assume so if the right is granted to '*' and isn't revoked
4836 * on any group. It doesn't attempt to take grants or other extension
4837 * limitations on rights into account in the general case, though, as that
4838 * would require it to always return false and defeat the purpose.
4839 * Specifically, session-based rights restrictions (such as OAuth or bot
4840 * passwords) are applied based on the current session.
4842 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4843 * ->isEveryoneAllowed() instead
4845 * @param string $right Right to check
4850 public static function isEveryoneAllowed( $right ) {
4851 return MediaWikiServices
::getInstance()->getPermissionManager()->isEveryoneAllowed( $right );
4855 * Return the set of defined explicit groups.
4856 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4857 * are not included, as they are defined automatically, not in the database.
4858 * @return array Array of internal group names
4860 public static function getAllGroups() {
4861 global $wgGroupPermissions, $wgRevokePermissions;
4862 return array_values( array_diff(
4863 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4864 self
::getImplicitGroups()
4869 * Get a list of all available permissions.
4871 * @deprecated since 1.34, use MediaWikiServices::getInstance()->getPermissionManager()
4872 * ->getAllPermissions() instead
4874 * @return string[] Array of permission names
4876 public static function getAllRights() {
4877 return MediaWikiServices
::getInstance()->getPermissionManager()->getAllPermissions();
4881 * Get a list of implicit groups
4882 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
4884 * @return array Array of Strings Array of internal group names
4886 public static function getImplicitGroups() {
4887 global $wgImplicitGroups;
4888 return $wgImplicitGroups;
4892 * Returns an array of the groups that a particular group can add/remove.
4894 * @param string $group The group to check for whether it can add/remove
4895 * @return array Array( 'add' => array( addablegroups ),
4896 * 'remove' => array( removablegroups ),
4897 * 'add-self' => array( addablegroups to self),
4898 * 'remove-self' => array( removable groups from self) )
4900 public static function changeableByGroup( $group ) {
4901 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4910 if ( empty( $wgAddGroups[$group] ) ) {
4911 // Don't add anything to $groups
4912 } elseif ( $wgAddGroups[$group] === true ) {
4913 // You get everything
4914 $groups['add'] = self
::getAllGroups();
4915 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4916 $groups['add'] = $wgAddGroups[$group];
4919 // Same thing for remove
4920 if ( empty( $wgRemoveGroups[$group] ) ) {
4922 } elseif ( $wgRemoveGroups[$group] === true ) {
4923 $groups['remove'] = self
::getAllGroups();
4924 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4925 $groups['remove'] = $wgRemoveGroups[$group];
4928 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4929 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4930 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4931 if ( is_int( $key ) ) {
4932 $wgGroupsAddToSelf['user'][] = $value;
4937 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4938 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4939 if ( is_int( $key ) ) {
4940 $wgGroupsRemoveFromSelf['user'][] = $value;
4945 // Now figure out what groups the user can add to him/herself
4946 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4948 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4949 // No idea WHY this would be used, but it's there
4950 $groups['add-self'] = self
::getAllGroups();
4951 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4952 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4955 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4957 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4958 $groups['remove-self'] = self
::getAllGroups();
4959 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4960 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4967 * Returns an array of groups that this user can add and remove
4968 * @return array Array( 'add' => array( addablegroups ),
4969 * 'remove' => array( removablegroups ),
4970 * 'add-self' => array( addablegroups to self),
4971 * 'remove-self' => array( removable groups from self) )
4973 public function changeableGroups() {
4974 if ( $this->isAllowed( 'userrights' ) ) {
4975 // This group gives the right to modify everything (reverse-
4976 // compatibility with old "userrights lets you change
4978 // Using array_merge to make the groups reindexed
4979 $all = array_merge( self
::getAllGroups() );
4988 // Okay, it's not so simple, we will have to go through the arrays
4995 $addergroups = $this->getEffectiveGroups();
4997 foreach ( $addergroups as $addergroup ) {
4998 $groups = array_merge_recursive(
4999 $groups, $this->changeableByGroup( $addergroup )
5001 $groups['add'] = array_unique( $groups['add'] );
5002 $groups['remove'] = array_unique( $groups['remove'] );
5003 $groups['add-self'] = array_unique( $groups['add-self'] );
5004 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5010 * Schedule a deferred update to update the user's edit count
5012 public function incEditCount() {
5013 if ( $this->isAnon() ) {
5017 DeferredUpdates
::addUpdate(
5018 new UserEditCountUpdate( $this, 1 ),
5019 DeferredUpdates
::POSTSEND
5024 * This method should not be called outside User/UserEditCountUpdate
5028 public function setEditCountInternal( $count ) {
5029 $this->mEditCount
= $count;
5033 * Initialize user_editcount from data out of the revision table
5035 * This method should not be called outside User/UserEditCountUpdate
5037 * @return int Number of edits
5039 public function initEditCountInternal() {
5040 // Pull from a replica DB to be less cruel to servers
5041 // Accuracy isn't the point anyway here
5042 $dbr = wfGetDB( DB_REPLICA
);
5043 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5044 $count = (int)$dbr->selectField(
5045 [ 'revision' ] +
$actorWhere['tables'],
5047 [ $actorWhere['conds'] ],
5050 $actorWhere['joins']
5053 $dbw = wfGetDB( DB_MASTER
);
5056 [ 'user_editcount' => $count ],
5058 'user_id' => $this->getId(),
5059 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5068 * Get the description of a given right
5071 * @param string $right Right to query
5072 * @return string Localized description of the right
5074 public static function getRightDescription( $right ) {
5075 $key = "right-$right";
5076 $msg = wfMessage( $key );
5077 return $msg->isDisabled() ?
$right : $msg->text();
5081 * Get the name of a given grant
5084 * @param string $grant Grant to query
5085 * @return string Localized name of the grant
5087 public static function getGrantName( $grant ) {
5088 $key = "grant-$grant";
5089 $msg = wfMessage( $key );
5090 return $msg->isDisabled() ?
$grant : $msg->text();
5094 * Add a newuser log entry for this user.
5095 * Before 1.19 the return value was always true.
5097 * @deprecated since 1.27, AuthManager handles logging
5098 * @param string|bool $action Account creation type.
5099 * - String, one of the following values:
5100 * - 'create' for an anonymous user creating an account for himself.
5101 * This will force the action's performer to be the created user itself,
5102 * no matter the value of $wgUser
5103 * - 'create2' for a logged in user creating an account for someone else
5104 * - 'byemail' when the created user will receive its password by e-mail
5105 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5106 * - Boolean means whether the account was created by e-mail (deprecated):
5107 * - true will be converted to 'byemail'
5108 * - false will be converted to 'create' if this object is the same as
5109 * $wgUser and to 'create2' otherwise
5110 * @param string $reason User supplied reason
5113 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5114 return true; // disabled
5118 * Add an autocreate newuser log entry for this user
5119 * Used by things like CentralAuth and perhaps other authplugins.
5120 * Consider calling addNewUserLogEntry() directly instead.
5122 * @deprecated since 1.27, AuthManager handles logging
5125 public function addNewUserLogEntryAutoCreate() {
5126 $this->addNewUserLogEntry( 'autocreate' );
5132 * Load the user options either from cache, the database or an array
5134 * @param array|null $data Rows for the current user out of the user_properties table
5136 protected function loadOptions( $data = null ) {
5139 if ( $this->mOptionsLoaded
) {
5143 $this->mOptions
= self
::getDefaultOptions();
5145 if ( !$this->getId() ) {
5146 // For unlogged-in users, load language/variant options from request.
5147 // There's no need to do it for logged-in users: they can set preferences,
5148 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5149 // so don't override user's choice (especially when the user chooses site default).
5150 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5151 $this->mOptions
['variant'] = $variant;
5152 $this->mOptions
['language'] = $variant;
5153 $this->mOptionsLoaded
= true;
5157 // Maybe load from the object
5158 if ( !is_null( $this->mOptionOverrides
) ) {
5159 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5160 foreach ( $this->mOptionOverrides
as $key => $value ) {
5161 $this->mOptions
[$key] = $value;
5164 if ( !is_array( $data ) ) {
5165 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5166 // Load from database
5167 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5168 ?
wfGetDB( DB_MASTER
)
5169 : wfGetDB( DB_REPLICA
);
5171 $res = $dbr->select(
5173 [ 'up_property', 'up_value' ],
5174 [ 'up_user' => $this->getId() ],
5178 $this->mOptionOverrides
= [];
5180 foreach ( $res as $row ) {
5181 // Convert '0' to 0. PHP's boolean conversion considers them both
5182 // false, but e.g. JavaScript considers the former as true.
5183 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5184 // and convert all values here.
5185 if ( $row->up_value
=== '0' ) {
5188 $data[$row->up_property
] = $row->up_value
;
5192 foreach ( $data as $property => $value ) {
5193 $this->mOptionOverrides
[$property] = $value;
5194 $this->mOptions
[$property] = $value;
5198 // Replace deprecated language codes
5199 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5200 $this->mOptions
['language']
5203 $this->mOptionsLoaded
= true;
5205 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5209 * Saves the non-default options for this user, as previously set e.g. via
5210 * setOption(), in the database's "user_properties" (preferences) table.
5211 * Usually used via saveSettings().
5213 protected function saveOptions() {
5214 $this->loadOptions();
5216 // Not using getOptions(), to keep hidden preferences in database
5217 $saveOptions = $this->mOptions
;
5219 // Allow hooks to abort, for instance to save to a global profile.
5220 // Reset options to default state before saving.
5221 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5225 $userId = $this->getId();
5227 $insert_rows = []; // all the new preference rows
5228 foreach ( $saveOptions as $key => $value ) {
5229 // Don't bother storing default values
5230 $defaultOption = self
::getDefaultOption( $key );
5231 if ( ( $defaultOption === null && $value !== false && $value !== null )
5232 ||
$value != $defaultOption
5235 'up_user' => $userId,
5236 'up_property' => $key,
5237 'up_value' => $value,
5242 $dbw = wfGetDB( DB_MASTER
);
5244 $res = $dbw->select( 'user_properties',
5245 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5247 // Find prior rows that need to be removed or updated. These rows will
5248 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5250 foreach ( $res as $row ) {
5251 if ( !isset( $saveOptions[$row->up_property
] )
5252 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5254 $keysDelete[] = $row->up_property
;
5258 if ( count( $keysDelete ) ) {
5259 // Do the DELETE by PRIMARY KEY for prior rows.
5260 // In the past a very large portion of calls to this function are for setting
5261 // 'rememberpassword' for new accounts (a preference that has since been removed).
5262 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5263 // caused gap locks on [max user ID,+infinity) which caused high contention since
5264 // updates would pile up on each other as they are for higher (newer) user IDs.
5265 // It might not be necessary these days, but it shouldn't hurt either.
5266 $dbw->delete( 'user_properties',
5267 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5269 // Insert the new preference rows
5270 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5274 * Return the list of user fields that should be selected to create
5275 * a new user object.
5276 * @deprecated since 1.31, use self::getQueryInfo() instead.
5279 public static function selectFields() {
5280 wfDeprecated( __METHOD__
, '1.31' );
5288 'user_email_authenticated',
5290 'user_email_token_expires',
5291 'user_registration',
5297 * Return the tables, fields, and join conditions to be selected to create
5298 * a new user object.
5300 * @return array With three keys:
5301 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5302 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5303 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5305 public static function getQueryInfo() {
5306 global $wgActorTableSchemaMigrationStage;
5309 'tables' => [ 'user' ],
5317 'user_email_authenticated',
5319 'user_email_token_expires',
5320 'user_registration',
5326 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5327 // but it does little harm and might be needed for write callers loading a User.
5328 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5329 $ret['tables']['user_actor'] = 'actor';
5330 $ret['fields'][] = 'user_actor.actor_id';
5331 $ret['joins']['user_actor'] = [
5332 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5333 [ 'user_actor.actor_user = user_id' ]
5341 * Factory function for fatal permission-denied errors
5344 * @param string $permission User right required
5347 static function newFatalPermissionDeniedStatus( $permission ) {
5351 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5352 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5356 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5359 return Status
::newFatal( 'badaccess-group0' );
5363 * Get a new instance of this user that was loaded from the master via a locking read
5365 * Use this instead of the main context User when updating that user. This avoids races
5366 * where that user was loaded from a replica DB or even the master but without proper locks.
5368 * @return User|null Returns null if the user was not found in the DB
5371 public function getInstanceForUpdate() {
5372 if ( !$this->getId() ) {
5373 return null; // anon
5376 $user = self
::newFromId( $this->getId() );
5377 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5385 * Checks if two user objects point to the same user.
5387 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5388 * @param UserIdentity $user
5391 public function equals( UserIdentity
$user ) {
5392 // XXX it's not clear whether central ID providers are supposed to obey this
5393 return $this->getName() === $user->getName();
5397 * Checks if usertalk is allowed
5401 public function isAllowUsertalk() {
5402 return $this->mAllowUsertalk
;