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\SystemBlock
;
25 use MediaWiki\MediaWikiServices
;
26 use MediaWiki\Session\SessionManager
;
27 use MediaWiki\Session\Token
;
28 use MediaWiki\Auth\AuthManager
;
29 use MediaWiki\Auth\AuthenticationResponse
;
30 use MediaWiki\Auth\AuthenticationRequest
;
31 use MediaWiki\User\UserIdentity
;
32 use MediaWiki\Logger\LoggerFactory
;
33 use Wikimedia\Assert\Assert
;
35 use Wikimedia\ScopedCallback
;
36 use Wikimedia\Rdbms\Database
;
37 use Wikimedia\Rdbms\DBExpectedError
;
38 use Wikimedia\Rdbms\IDatabase
;
41 * The User object encapsulates all of the user-specific settings (user_id,
42 * name, rights, email address, options, last login time). Client
43 * classes use the getXXX() functions to access these fields. These functions
44 * do all the work of determining whether the user is logged in,
45 * whether the requested option can be satisfied from cookies or
46 * whether a database query is needed. Most of the settings needed
47 * for rendering normal pages are set in the cookie to minimize use
50 class User
implements IDBAccessObject
, UserIdentity
{
53 * Number of characters required for the user_token field.
55 const TOKEN_LENGTH
= 32;
58 * An invalid string value for the user_token field.
60 const INVALID_TOKEN
= '*** INVALID ***';
63 * Version number to tag cached versions of serialized User objects. Should be increased when
64 * {@link $mCacheVars} or one of it's members changes.
69 * Exclude user options that are set to their default value.
72 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
77 const CHECK_USER_RIGHTS
= true;
82 const IGNORE_USER_RIGHTS
= false;
85 * Array of Strings List of member variables which are saved to the
86 * shared cache (memcached). Any operation which changes the
87 * corresponding database fields must call a cache-clearing function.
90 protected static $mCacheVars = [
98 'mEmailAuthenticated',
100 'mEmailTokenExpires',
105 // user_properties table
112 * Array of Strings Core rights.
113 * Each of these should have a corresponding message of the form
117 protected static $mCoreRights = [
165 'move-categorypages',
166 'move-rootuserpages',
170 'override-export-depth',
192 'userrights-interwiki',
200 * String Cached results of getAllRights()
202 protected static $mAllRights = false;
204 /** Cache variables */
217 /** @var string TS_MW timestamp from the DB */
219 /** @var string TS_MW timestamp from cache */
220 protected $mQuickTouched;
224 public $mEmailAuthenticated;
226 protected $mEmailToken;
228 protected $mEmailTokenExpires;
230 protected $mRegistration;
232 protected $mEditCount;
233 /** @var UserGroupMembership[] Associative array of (group name => UserGroupMembership object) */
234 protected $mGroupMemberships;
236 protected $mOptionOverrides;
240 * Bool Whether the cache variables have been loaded.
243 public $mOptionsLoaded;
246 * Array with already loaded items or true if all items have been loaded.
248 protected $mLoadedItems = [];
252 * String Initialization data source if mLoadedItems!==true. May be one of:
253 * - 'defaults' anonymous user initialised from class defaults
254 * - 'name' initialise from mName
255 * - 'id' initialise from mId
256 * - 'actor' initialise from mActorId
257 * - 'session' log in from session if possible
259 * Use the User::newFrom*() family of functions to set this.
264 * Lazy-initialized variables, invalidated with clearInstanceCache
268 protected $mDatePreference;
276 protected $mBlockreason;
278 protected $mEffectiveGroups;
280 protected $mImplicitGroups;
282 protected $mFormerGroups;
283 /** @var AbstractBlock */
284 protected $mGlobalBlock;
292 /** @var WebRequest */
295 /** @var AbstractBlock */
299 protected $mAllowUsertalk;
301 /** @var AbstractBlock */
302 private $mBlockedFromCreateAccount = false;
304 /** @var int User::READ_* constant bitfield used to load data */
305 protected $queryFlagsUsed = self
::READ_NORMAL
;
307 public static $idCacheByName = [];
310 * Lightweight constructor for an anonymous user.
311 * Use the User::newFrom* factory functions for other kinds of users.
315 * @see newFromActorId()
316 * @see newFromConfirmationCode()
317 * @see newFromSession()
320 public function __construct() {
321 $this->clearInstanceCache( 'defaults' );
327 public function __toString() {
328 return (string)$this->getName();
332 * Test if it's safe to load this User object.
334 * You should typically check this before using $wgUser or
335 * RequestContext::getUser in a method that might be called before the
336 * system has been fully initialized. If the object is unsafe, you should
337 * use an anonymous user:
339 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
345 public function isSafeToLoad() {
346 global $wgFullyInitialised;
348 // The user is safe to load if:
349 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
350 // * mLoadedItems === true (already loaded)
351 // * mFrom !== 'session' (sessions not involved at all)
353 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
354 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
358 * Load the user table data for this object from the source given by mFrom.
360 * @param int $flags User::READ_* constant bitfield
362 public function load( $flags = self
::READ_NORMAL
) {
363 global $wgFullyInitialised;
365 if ( $this->mLoadedItems
=== true ) {
369 // Set it now to avoid infinite recursion in accessors
370 $oldLoadedItems = $this->mLoadedItems
;
371 $this->mLoadedItems
= true;
372 $this->queryFlagsUsed
= $flags;
374 // If this is called too early, things are likely to break.
375 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
376 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
377 ->warning( 'User::loadFromSession called before the end of Setup.php', [
378 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
380 $this->loadDefaults();
381 $this->mLoadedItems
= $oldLoadedItems;
385 switch ( $this->mFrom
) {
387 $this->loadDefaults();
390 // Make sure this thread sees its own changes
391 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
392 if ( $lb->hasOrMadeRecentMasterChanges() ) {
393 $flags |
= self
::READ_LATEST
;
394 $this->queryFlagsUsed
= $flags;
397 $this->mId
= self
::idFromName( $this->mName
, $flags );
399 // Nonexistent user placeholder object
400 $this->loadDefaults( $this->mName
);
402 $this->loadFromId( $flags );
406 // Make sure this thread sees its own changes, if the ID isn't 0
407 if ( $this->mId
!= 0 ) {
408 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
409 if ( $lb->hasOrMadeRecentMasterChanges() ) {
410 $flags |
= self
::READ_LATEST
;
411 $this->queryFlagsUsed
= $flags;
415 $this->loadFromId( $flags );
418 // Make sure this thread sees its own changes
419 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
420 if ( $lb->hasOrMadeRecentMasterChanges() ) {
421 $flags |
= self
::READ_LATEST
;
422 $this->queryFlagsUsed
= $flags;
425 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
426 $row = wfGetDB( $index )->selectRow(
428 [ 'actor_user', 'actor_name' ],
429 [ 'actor_id' => $this->mActorId
],
436 $this->loadDefaults();
437 } elseif ( $row->actor_user
) {
438 $this->mId
= $row->actor_user
;
439 $this->loadFromId( $flags );
441 $this->loadDefaults( $row->actor_name
);
445 if ( !$this->loadFromSession() ) {
446 // Loading from session failed. Load defaults.
447 $this->loadDefaults();
449 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
452 throw new UnexpectedValueException(
453 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
458 * Load user table data, given mId has already been set.
459 * @param int $flags User::READ_* constant bitfield
460 * @return bool False if the ID does not exist, true otherwise
462 public function loadFromId( $flags = self
::READ_NORMAL
) {
463 if ( $this->mId
== 0 ) {
464 // Anonymous users are not in the database (don't need cache)
465 $this->loadDefaults();
469 // Try cache (unless this needs data from the master DB).
470 // NOTE: if this thread called saveSettings(), the cache was cleared.
471 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
473 if ( !$this->loadFromDatabase( $flags ) ) {
474 // Can't load from ID
478 $this->loadFromCache();
481 $this->mLoadedItems
= true;
482 $this->queryFlagsUsed
= $flags;
489 * @param string $wikiId
492 public static function purge( $wikiId, $userId ) {
493 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
494 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
495 $cache->delete( $key );
500 * @param WANObjectCache $cache
503 protected function getCacheKey( WANObjectCache
$cache ) {
504 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
506 return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId
);
510 * @param WANObjectCache $cache
514 public function getMutableCacheKeys( WANObjectCache
$cache ) {
515 $id = $this->getId();
517 return $id ?
[ $this->getCacheKey( $cache ) ] : [];
521 * Load user data from shared cache, given mId has already been set.
526 protected function loadFromCache() {
527 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
528 $data = $cache->getWithSetCallback(
529 $this->getCacheKey( $cache ),
531 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
532 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
533 wfDebug( "User: cache miss for user {$this->mId}\n" );
535 $this->loadFromDatabase( self
::READ_NORMAL
);
537 $this->loadOptions();
540 foreach ( self
::$mCacheVars as $name ) {
541 $data[$name] = $this->$name;
544 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
546 // if a user group membership is about to expire, the cache needs to
547 // expire at that time (T163691)
548 foreach ( $this->mGroupMemberships
as $ugm ) {
549 if ( $ugm->getExpiry() ) {
550 $secondsUntilExpiry = wfTimestamp( TS_UNIX
, $ugm->getExpiry() ) - time();
551 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
552 $ttl = $secondsUntilExpiry;
559 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
562 // Restore from cache
563 foreach ( self
::$mCacheVars as $name ) {
564 $this->$name = $data[$name];
570 /** @name newFrom*() static factory methods */
574 * Static factory method for creation from username.
576 * This is slightly less efficient than newFromId(), so use newFromId() if
577 * you have both an ID and a name handy.
579 * @param string $name Username, validated by Title::newFromText()
580 * @param string|bool $validate Validate username. Takes the same parameters as
581 * User::getCanonicalName(), except that true is accepted as an alias
582 * for 'valid', for BC.
584 * @return User|bool User object, or false if the username is invalid
585 * (e.g. if it contains illegal characters or is an IP address). If the
586 * username is not present in the database, the result will be a user object
587 * with a name, zero user ID and default settings.
589 public static function newFromName( $name, $validate = 'valid' ) {
590 if ( $validate === true ) {
593 $name = self
::getCanonicalName( $name, $validate );
594 if ( $name === false ) {
598 // Create unloaded user object
602 $u->setItemLoaded( 'name' );
608 * Static factory method for creation from a given user ID.
610 * @param int $id Valid user ID
611 * @return User The corresponding User object
613 public static function newFromId( $id ) {
617 $u->setItemLoaded( 'id' );
622 * Static factory method for creation from a given actor ID.
625 * @param int $id Valid actor ID
626 * @return User The corresponding User object
628 public static function newFromActorId( $id ) {
629 global $wgActorTableSchemaMigrationStage;
631 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
632 // but it does little harm and might be needed for write callers loading a User.
633 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) ) {
634 throw new BadMethodCallException(
635 'Cannot use ' . __METHOD__
636 . ' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
643 $u->setItemLoaded( 'actor' );
648 * Returns a User object corresponding to the given UserIdentity.
652 * @param UserIdentity $identity
656 public static function newFromIdentity( UserIdentity
$identity ) {
657 if ( $identity instanceof User
) {
661 return self
::newFromAnyId(
662 $identity->getId() === 0 ?
null : $identity->getId(),
663 $identity->getName() === '' ?
null : $identity->getName(),
664 $identity->getActorId() === 0 ?
null : $identity->getActorId()
669 * Static factory method for creation from an ID, name, and/or actor ID
671 * This does not check that the ID, name, and actor ID all correspond to
675 * @param int|null $userId User ID, if known
676 * @param string|null $userName User name, if known
677 * @param int|null $actorId Actor ID, if known
678 * @param bool|string $wikiId remote wiki to which the User/Actor ID applies, or false if none
681 public static function newFromAnyId( $userId, $userName, $actorId, $wikiId = false ) {
682 global $wgActorTableSchemaMigrationStage;
684 // Stop-gap solution for the problem described in T222212.
685 // Force the User ID and Actor ID to zero for users loaded from the database
686 // of another wiki, to prevent subtle data corruption and confusing failure modes.
687 if ( $wikiId !== false ) {
693 $user->mFrom
= 'defaults';
695 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
696 // but it does little harm and might be needed for write callers loading a User.
697 if ( ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) && $actorId !== null ) {
698 $user->mActorId
= (int)$actorId;
699 if ( $user->mActorId
!== 0 ) {
700 $user->mFrom
= 'actor';
702 $user->setItemLoaded( 'actor' );
705 if ( $userName !== null && $userName !== '' ) {
706 $user->mName
= $userName;
707 $user->mFrom
= 'name';
708 $user->setItemLoaded( 'name' );
711 if ( $userId !== null ) {
712 $user->mId
= (int)$userId;
713 if ( $user->mId
!== 0 ) {
716 $user->setItemLoaded( 'id' );
719 if ( $user->mFrom
=== 'defaults' ) {
720 throw new InvalidArgumentException(
721 'Cannot create a user with no name, no ID, and no actor ID'
729 * Factory method to fetch whichever user has a given email confirmation code.
730 * This code is generated when an account is created or its e-mail address
733 * If the code is invalid or has expired, returns NULL.
735 * @param string $code Confirmation code
736 * @param int $flags User::READ_* bitfield
739 public static function newFromConfirmationCode( $code, $flags = 0 ) {
740 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
741 ?
wfGetDB( DB_MASTER
)
742 : wfGetDB( DB_REPLICA
);
744 $id = $db->selectField(
748 'user_email_token' => md5( $code ),
749 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
753 return $id ? self
::newFromId( $id ) : null;
757 * Create a new user object using data from session. If the login
758 * credentials are invalid, the result is an anonymous user.
760 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
763 public static function newFromSession( WebRequest
$request = null ) {
765 $user->mFrom
= 'session';
766 $user->mRequest
= $request;
771 * Create a new user object from a user row.
772 * The row should have the following fields from the user table in it:
773 * - either user_name or user_id to load further data if needed (or both)
775 * - all other fields (email, etc.)
776 * It is useless to provide the remaining fields if either user_id,
777 * user_name and user_real_name are not provided because the whole row
778 * will be loaded once more from the database when accessing them.
780 * @param stdClass $row A row from the user table
781 * @param array|null $data Further data to load into the object
782 * (see User::loadFromRow for valid keys)
785 public static function newFromRow( $row, $data = null ) {
787 $user->loadFromRow( $row, $data );
792 * Static factory method for creation of a "system" user from username.
794 * A "system" user is an account that's used to attribute logged actions
795 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
796 * might include the 'Maintenance script' or 'Conversion script' accounts
797 * used by various scripts in the maintenance/ directory or accounts such
798 * as 'MediaWiki message delivery' used by the MassMessage extension.
800 * This can optionally create the user if it doesn't exist, and "steal" the
801 * account if it does exist.
803 * "Stealing" an existing user is intended to make it impossible for normal
804 * authentication processes to use the account, effectively disabling the
805 * account for normal use:
806 * - Email is invalidated, to prevent account recovery by emailing a
807 * temporary password and to disassociate the account from the existing
809 * - The token is set to a magic invalid value, to kill existing sessions
810 * and to prevent $this->setToken() calls from resetting the token to a
812 * - SessionManager is instructed to prevent new sessions for the user, to
813 * do things like deauthorizing OAuth consumers.
814 * - AuthManager is instructed to revoke access, to invalidate or remove
815 * passwords and other credentials.
817 * @param string $name Username
818 * @param array $options Options are:
819 * - validate: As for User::getCanonicalName(), default 'valid'
820 * - create: Whether to create the user if it doesn't already exist, default true
821 * - steal: Whether to "disable" the account for normal use if it already
822 * exists, default false
826 public static function newSystemUser( $name, $options = [] ) {
828 'validate' => 'valid',
833 $name = self
::getCanonicalName( $name, $options['validate'] );
834 if ( $name === false ) {
838 $dbr = wfGetDB( DB_REPLICA
);
839 $userQuery = self
::getQueryInfo();
840 $row = $dbr->selectRow(
841 $userQuery['tables'],
842 $userQuery['fields'],
843 [ 'user_name' => $name ],
849 // Try the master database...
850 $dbw = wfGetDB( DB_MASTER
);
851 $row = $dbw->selectRow(
852 $userQuery['tables'],
853 $userQuery['fields'],
854 [ 'user_name' => $name ],
862 // No user. Create it?
863 return $options['create']
864 ? self
::createNew( $name, [ 'token' => self
::INVALID_TOKEN
] )
868 $user = self
::newFromRow( $row );
870 // A user is considered to exist as a non-system user if it can
871 // authenticate, or has an email set, or has a non-invalid token.
872 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
873 AuthManager
::singleton()->userCanAuthenticate( $name )
875 // User exists. Steal it?
876 if ( !$options['steal'] ) {
880 AuthManager
::singleton()->revokeAccessForUser( $name );
882 $user->invalidateEmail();
883 $user->mToken
= self
::INVALID_TOKEN
;
884 $user->saveSettings();
885 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
894 * Get the username corresponding to a given user ID
895 * @param int $id User ID
896 * @return string|bool The corresponding username
898 public static function whoIs( $id ) {
899 return UserCache
::singleton()->getProp( $id, 'name' );
903 * Get the real name of a user given their user ID
905 * @param int $id User ID
906 * @return string|bool The corresponding user's real name
908 public static function whoIsReal( $id ) {
909 return UserCache
::singleton()->getProp( $id, 'real_name' );
913 * Get database id given a user name
914 * @param string $name Username
915 * @param int $flags User::READ_* constant bitfield
916 * @return int|null The corresponding user's ID, or null if user is nonexistent
918 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
919 // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
920 $name = (string)$name;
921 $nt = Title
::makeTitleSafe( NS_USER
, $name );
922 if ( is_null( $nt ) ) {
927 if ( !( $flags & self
::READ_LATEST
) && array_key_exists( $name, self
::$idCacheByName ) ) {
928 return is_null( self
::$idCacheByName[$name] ) ?
null : (int)self
::$idCacheByName[$name];
931 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
932 $db = wfGetDB( $index );
937 [ 'user_name' => $nt->getText() ],
942 if ( $s === false ) {
945 $result = (int)$s->user_id
;
948 self
::$idCacheByName[$name] = $result;
950 if ( count( self
::$idCacheByName ) > 1000 ) {
951 self
::$idCacheByName = [];
958 * Reset the cache used in idFromName(). For use in tests.
960 public static function resetIdByNameCache() {
961 self
::$idCacheByName = [];
965 * Does the string match an anonymous IP address?
967 * This function exists for username validation, in order to reject
968 * usernames which are similar in form to IP addresses. Strings such
969 * as 300.300.300.300 will return true because it looks like an IP
970 * address, despite not being strictly valid.
972 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
973 * address because the usemod software would "cloak" anonymous IP
974 * addresses like this, if we allowed accounts like this to be created
975 * new users could get the old edits of these anonymous users.
977 * @param string $name Name to match
980 public static function isIP( $name ) {
981 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
982 || IP
::isIPv6( $name );
986 * Is the user an IP range?
991 public function isIPRange() {
992 return IP
::isValidRange( $this->mName
);
996 * Is the input a valid username?
998 * Checks if the input is a valid username, we don't want an empty string,
999 * an IP address, anything that contains slashes (would mess up subpages),
1000 * is longer than the maximum allowed username size or doesn't begin with
1003 * @param string $name Name to match
1006 public static function isValidUserName( $name ) {
1007 global $wgMaxNameChars;
1010 || self
::isIP( $name )
1011 ||
strpos( $name, '/' ) !== false
1012 ||
strlen( $name ) > $wgMaxNameChars
1013 ||
$name != MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name )
1018 // Ensure that the name can't be misresolved as a different title,
1019 // such as with extra namespace keys at the start.
1020 $parsed = Title
::newFromText( $name );
1021 if ( is_null( $parsed )
1022 ||
$parsed->getNamespace()
1023 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
1027 // Check an additional blacklist of troublemaker characters.
1028 // Should these be merged into the title char list?
1029 $unicodeBlacklist = '/[' .
1030 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1031 '\x{00a0}' . # non-breaking space
1032 '\x{2000}-\x{200f}' . # various whitespace
1033 '\x{2028}-\x{202f}' . # breaks and control chars
1034 '\x{3000}' . # ideographic space
1035 '\x{e000}-\x{f8ff}' . # private use
1037 if ( preg_match( $unicodeBlacklist, $name ) ) {
1045 * Usernames which fail to pass this function will be blocked
1046 * from user login and new account registrations, but may be used
1047 * internally by batch processes.
1049 * If an account already exists in this form, login will be blocked
1050 * by a failure to pass this function.
1052 * @param string $name Name to match
1055 public static function isUsableName( $name ) {
1056 global $wgReservedUsernames;
1057 // Must be a valid username, obviously ;)
1058 if ( !self
::isValidUserName( $name ) ) {
1062 static $reservedUsernames = false;
1063 if ( !$reservedUsernames ) {
1064 $reservedUsernames = $wgReservedUsernames;
1065 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
1068 // Certain names may be reserved for batch processes.
1069 foreach ( $reservedUsernames as $reserved ) {
1070 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
1071 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1073 if ( $reserved == $name ) {
1081 * Return the users who are members of the given group(s). In case of multiple groups,
1082 * users who are members of at least one of them are returned.
1084 * @param string|array $groups A single group name or an array of group names
1085 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
1086 * records; larger values are ignored.
1087 * @param int|null $after ID the user to start after
1088 * @return UserArrayFromResult
1090 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1091 if ( $groups === [] ) {
1092 return UserArrayFromResult
::newFromIDs( [] );
1095 $groups = array_unique( (array)$groups );
1096 $limit = min( 5000, $limit );
1098 $conds = [ 'ug_group' => $groups ];
1099 if ( $after !== null ) {
1100 $conds[] = 'ug_user > ' . (int)$after;
1103 $dbr = wfGetDB( DB_REPLICA
);
1104 $ids = $dbr->selectFieldValues(
1111 'ORDER BY' => 'ug_user',
1115 return UserArray
::newFromIDs( $ids );
1119 * Usernames which fail to pass this function will be blocked
1120 * from new account registrations, but may be used internally
1121 * either by batch processes or by user accounts which have
1122 * already been created.
1124 * Additional blacklisting may be added here rather than in
1125 * isValidUserName() to avoid disrupting existing accounts.
1127 * @param string $name String to match
1130 public static function isCreatableName( $name ) {
1131 global $wgInvalidUsernameCharacters;
1133 // Ensure that the username isn't longer than 235 bytes, so that
1134 // (at least for the builtin skins) user javascript and css files
1135 // will work. (T25080)
1136 if ( strlen( $name ) > 235 ) {
1137 wfDebugLog( 'username', __METHOD__
.
1138 ": '$name' invalid due to length" );
1142 // Preg yells if you try to give it an empty string
1143 if ( $wgInvalidUsernameCharacters !== '' &&
1144 preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name )
1146 wfDebugLog( 'username', __METHOD__
.
1147 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1151 return self
::isUsableName( $name );
1155 * Is the input a valid password for this user?
1157 * @param string $password Desired password
1160 public function isValidPassword( $password ) {
1161 // simple boolean wrapper for checkPasswordValidity
1162 return $this->checkPasswordValidity( $password )->isGood();
1166 * Check if this is a valid password for this user
1168 * Returns a Status object with a set of messages describing
1169 * problems with the password. If the return status is fatal,
1170 * the action should be refused and the password should not be
1171 * checked at all (this is mainly meant for DoS mitigation).
1172 * If the return value is OK but not good, the password can be checked,
1173 * but the user should not be able to set their password to this.
1174 * The value of the returned Status object will be an array which
1175 * can have the following fields:
1176 * - forceChange (bool): if set to true, the user should not be
1177 * allowed to log with this password unless they change it during
1178 * the login process (see ResetPasswordSecondaryAuthenticationProvider).
1179 * - suggestChangeOnLogin (bool): if set to true, the user should be prompted for
1180 * a password change on login.
1182 * @param string $password Desired password
1186 public function checkPasswordValidity( $password ) {
1187 global $wgPasswordPolicy;
1189 $upp = new UserPasswordPolicy(
1190 $wgPasswordPolicy['policies'],
1191 $wgPasswordPolicy['checks']
1194 $status = Status
::newGood( [] );
1195 $result = false; // init $result to false for the internal checks
1197 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1198 $status->error( $result );
1202 if ( $result === false ) {
1203 $status->merge( $upp->checkUserPassword( $this, $password ), true );
1207 if ( $result === true ) {
1211 $status->error( $result );
1212 return $status; // the isValidPassword hook set a string $result and returned true
1216 * Given unvalidated user input, return a canonical username, or false if
1217 * the username is invalid.
1218 * @param string $name User input
1219 * @param string|bool $validate Type of validation to use:
1220 * - false No validation
1221 * - 'valid' Valid for batch processes
1222 * - 'usable' Valid for batch processes and login
1223 * - 'creatable' Valid for batch processes, login and account creation
1225 * @throws InvalidArgumentException
1226 * @return bool|string
1228 public static function getCanonicalName( $name, $validate = 'valid' ) {
1229 // Force usernames to capital
1230 $name = MediaWikiServices
::getInstance()->getContentLanguage()->ucfirst( $name );
1232 # Reject names containing '#'; these will be cleaned up
1233 # with title normalisation, but then it's too late to
1235 if ( strpos( $name, '#' ) !== false ) {
1239 // Clean up name according to title rules,
1240 // but only when validation is requested (T14654)
1241 $t = ( $validate !== false ) ?
1242 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1243 // Check for invalid titles
1244 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1248 $name = $t->getText();
1250 switch ( $validate ) {
1254 if ( !self
::isValidUserName( $name ) ) {
1259 if ( !self
::isUsableName( $name ) ) {
1264 if ( !self
::isCreatableName( $name ) ) {
1269 throw new InvalidArgumentException(
1270 'Invalid parameter value for $validate in ' . __METHOD__
);
1276 * Set cached properties to default.
1278 * @note This no longer clears uncached lazy-initialised properties;
1279 * the constructor does that instead.
1281 * @param string|bool $name
1283 public function loadDefaults( $name = false ) {
1285 $this->mName
= $name;
1286 $this->mActorId
= null;
1287 $this->mRealName
= '';
1289 $this->mOptionOverrides
= null;
1290 $this->mOptionsLoaded
= false;
1292 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1293 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1294 if ( $loggedOut !== 0 ) {
1295 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1297 $this->mTouched
= '1'; # Allow any pages to be cached
1300 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1301 $this->mEmailAuthenticated
= null;
1302 $this->mEmailToken
= '';
1303 $this->mEmailTokenExpires
= null;
1304 $this->mRegistration
= wfTimestamp( TS_MW
);
1305 $this->mGroupMemberships
= [];
1307 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1311 * Return whether an item has been loaded.
1313 * @param string $item Item to check. Current possibilities:
1317 * @param string $all 'all' to check if the whole object has been loaded
1318 * or any other string to check if only the item is available (e.g.
1322 public function isItemLoaded( $item, $all = 'all' ) {
1323 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1324 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1328 * Set that an item has been loaded
1330 * @param string $item
1332 protected function setItemLoaded( $item ) {
1333 if ( is_array( $this->mLoadedItems
) ) {
1334 $this->mLoadedItems
[$item] = true;
1339 * Load user data from the session.
1341 * @return bool True if the user is logged in, false otherwise.
1343 private function loadFromSession() {
1346 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1347 if ( $result !== null ) {
1351 // MediaWiki\Session\Session already did the necessary authentication of the user
1352 // returned here, so just use it if applicable.
1353 $session = $this->getRequest()->getSession();
1354 $user = $session->getUser();
1355 if ( $user->isLoggedIn() ) {
1356 $this->loadFromUserObject( $user );
1357 if ( $user->getBlock() ) {
1358 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1359 // every session load, because an autoblocked editor might not edit again from the same
1360 // IP address after being blocked.
1361 $this->trackBlockWithCookie();
1364 // Other code expects these to be set in the session, so set them.
1365 $session->set( 'wsUserID', $this->getId() );
1366 $session->set( 'wsUserName', $this->getName() );
1367 $session->set( 'wsToken', $this->getToken() );
1376 * Set the 'BlockID' cookie depending on block type and user authentication status.
1378 public function trackBlockWithCookie() {
1379 $block = $this->getBlock();
1381 if ( $block && $this->getRequest()->getCookie( 'BlockID' ) === null
1382 && $block->shouldTrackWithCookie( $this->isAnon() )
1384 $block->setCookie( $this->getRequest()->response() );
1389 * Load user and user_group data from the database.
1390 * $this->mId must be set, this is how the user is identified.
1392 * @param int $flags User::READ_* constant bitfield
1393 * @return bool True if the user exists, false if the user is anonymous
1395 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1397 $this->mId
= intval( $this->mId
);
1399 if ( !$this->mId
) {
1400 // Anonymous users are not in the database
1401 $this->loadDefaults();
1405 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1406 $db = wfGetDB( $index );
1408 $userQuery = self
::getQueryInfo();
1409 $s = $db->selectRow(
1410 $userQuery['tables'],
1411 $userQuery['fields'],
1412 [ 'user_id' => $this->mId
],
1418 $this->queryFlagsUsed
= $flags;
1419 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1421 if ( $s !== false ) {
1422 // Initialise user table data
1423 $this->loadFromRow( $s );
1424 $this->mGroupMemberships
= null; // deferred
1425 $this->getEditCount(); // revalidation for nulls
1431 $this->loadDefaults();
1437 * Initialize this object from a row from the user table.
1439 * @param stdClass $row Row from the user table to load.
1440 * @param array|null $data Further user data to load into the object
1442 * user_groups Array of arrays or stdClass result rows out of the user_groups
1443 * table. Previously you were supposed to pass an array of strings
1444 * here, but we also need expiry info nowadays, so an array of
1445 * strings is ignored.
1446 * user_properties Array with properties out of the user_properties table
1448 protected function loadFromRow( $row, $data = null ) {
1449 global $wgActorTableSchemaMigrationStage;
1451 if ( !is_object( $row ) ) {
1452 throw new InvalidArgumentException( '$row must be an object' );
1457 $this->mGroupMemberships
= null; // deferred
1459 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
1460 // but it does little harm and might be needed for write callers loading a User.
1461 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
1462 if ( isset( $row->actor_id
) ) {
1463 $this->mActorId
= (int)$row->actor_id
;
1464 if ( $this->mActorId
!== 0 ) {
1465 $this->mFrom
= 'actor';
1467 $this->setItemLoaded( 'actor' );
1473 if ( isset( $row->user_name
) && $row->user_name
!== '' ) {
1474 $this->mName
= $row->user_name
;
1475 $this->mFrom
= 'name';
1476 $this->setItemLoaded( 'name' );
1481 if ( isset( $row->user_real_name
) ) {
1482 $this->mRealName
= $row->user_real_name
;
1483 $this->setItemLoaded( 'realname' );
1488 if ( isset( $row->user_id
) ) {
1489 $this->mId
= intval( $row->user_id
);
1490 if ( $this->mId
!== 0 ) {
1491 $this->mFrom
= 'id';
1493 $this->setItemLoaded( 'id' );
1498 if ( isset( $row->user_id
) && isset( $row->user_name
) && $row->user_name
!== '' ) {
1499 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1502 if ( isset( $row->user_editcount
) ) {
1503 $this->mEditCount
= $row->user_editcount
;
1508 if ( isset( $row->user_touched
) ) {
1509 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1514 if ( isset( $row->user_token
) ) {
1515 // The definition for the column is binary(32), so trim the NULs
1516 // that appends. The previous definition was char(32), so trim
1518 $this->mToken
= rtrim( $row->user_token
, " \0" );
1519 if ( $this->mToken
=== '' ) {
1520 $this->mToken
= null;
1526 if ( isset( $row->user_email
) ) {
1527 $this->mEmail
= $row->user_email
;
1528 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1529 $this->mEmailToken
= $row->user_email_token
;
1530 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1531 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1537 $this->mLoadedItems
= true;
1540 if ( is_array( $data ) ) {
1541 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1542 if ( $data['user_groups'] === [] ) {
1543 $this->mGroupMemberships
= [];
1545 $firstGroup = reset( $data['user_groups'] );
1546 if ( is_array( $firstGroup ) ||
is_object( $firstGroup ) ) {
1547 $this->mGroupMemberships
= [];
1548 foreach ( $data['user_groups'] as $row ) {
1549 $ugm = UserGroupMembership
::newFromRow( (object)$row );
1550 $this->mGroupMemberships
[$ugm->getGroup()] = $ugm;
1555 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1556 $this->loadOptions( $data['user_properties'] );
1562 * Load the data for this user object from another user object.
1566 protected function loadFromUserObject( $user ) {
1568 foreach ( self
::$mCacheVars as $var ) {
1569 $this->$var = $user->$var;
1574 * Load the groups from the database if they aren't already loaded.
1576 private function loadGroups() {
1577 if ( is_null( $this->mGroupMemberships
) ) {
1578 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1579 ?
wfGetDB( DB_MASTER
)
1580 : wfGetDB( DB_REPLICA
);
1581 $this->mGroupMemberships
= UserGroupMembership
::getMembershipsForUser(
1587 * Add the user to the group if he/she meets given criteria.
1589 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1590 * possible to remove manually via Special:UserRights. In such case it
1591 * will not be re-added automatically. The user will also not lose the
1592 * group if they no longer meet the criteria.
1594 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1596 * @return array Array of groups the user has been promoted to.
1598 * @see $wgAutopromoteOnce
1600 public function addAutopromoteOnceGroups( $event ) {
1601 global $wgAutopromoteOnceLogInRC;
1603 if ( wfReadOnly() ||
!$this->getId() ) {
1607 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1608 if ( $toPromote === [] ) {
1612 if ( !$this->checkAndSetTouched() ) {
1613 return []; // raced out (bug T48834)
1616 $oldGroups = $this->getGroups(); // previous groups
1617 $oldUGMs = $this->getGroupMemberships();
1618 foreach ( $toPromote as $group ) {
1619 $this->addGroup( $group );
1621 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1622 $newUGMs = $this->getGroupMemberships();
1624 // update groups in external authentication database
1625 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false, $oldUGMs, $newUGMs ] );
1627 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1628 $logEntry->setPerformer( $this );
1629 $logEntry->setTarget( $this->getUserPage() );
1630 $logEntry->setParameters( [
1631 '4::oldgroups' => $oldGroups,
1632 '5::newgroups' => $newGroups,
1634 $logid = $logEntry->insert();
1635 if ( $wgAutopromoteOnceLogInRC ) {
1636 $logEntry->publish( $logid );
1643 * Builds update conditions. Additional conditions may be added to $conditions to
1644 * protected against race conditions using a compare-and-set (CAS) mechanism
1645 * based on comparing $this->mTouched with the user_touched field.
1647 * @param IDatabase $db
1648 * @param array $conditions WHERE conditions for use with Database::update
1649 * @return array WHERE conditions for use with Database::update
1651 protected function makeUpdateConditions( IDatabase
$db, array $conditions ) {
1652 if ( $this->mTouched
) {
1653 // CAS check: only update if the row wasn't changed sicne it was loaded.
1654 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1661 * Bump user_touched if it didn't change since this object was loaded
1663 * On success, the mTouched field is updated.
1664 * The user serialization cache is always cleared.
1666 * @return bool Whether user_touched was actually updated
1669 protected function checkAndSetTouched() {
1672 if ( !$this->mId
) {
1673 return false; // anon
1676 // Get a new user_touched that is higher than the old one
1677 $newTouched = $this->newTouchedTimestamp();
1679 $dbw = wfGetDB( DB_MASTER
);
1680 $dbw->update( 'user',
1681 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1682 $this->makeUpdateConditions( $dbw, [
1683 'user_id' => $this->mId
,
1687 $success = ( $dbw->affectedRows() > 0 );
1690 $this->mTouched
= $newTouched;
1691 $this->clearSharedCache( 'changed' );
1693 // Clears on failure too since that is desired if the cache is stale
1694 $this->clearSharedCache( 'refresh' );
1701 * Clear various cached data stored in this object. The cache of the user table
1702 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1704 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1705 * given source. May be "name", "id", "actor", "defaults", "session", or false for no reload.
1707 public function clearInstanceCache( $reloadFrom = false ) {
1708 $this->mNewtalk
= -1;
1709 $this->mDatePreference
= null;
1710 $this->mBlockedby
= -1; # Unset
1711 $this->mHash
= false;
1712 $this->mRights
= null;
1713 $this->mEffectiveGroups
= null;
1714 $this->mImplicitGroups
= null;
1715 $this->mGroupMemberships
= null;
1716 $this->mOptions
= null;
1717 $this->mOptionsLoaded
= false;
1718 $this->mEditCount
= null;
1720 if ( $reloadFrom ) {
1721 $this->mLoadedItems
= [];
1722 $this->mFrom
= $reloadFrom;
1726 /** @var array|null */
1727 private static $defOpt = null;
1728 /** @var string|null */
1729 private static $defOptLang = null;
1732 * Reset the process cache of default user options. This is only necessary
1733 * if the wiki configuration has changed since defaults were calculated,
1734 * and as such should only be performed inside the testing suite that
1735 * regularly changes wiki configuration.
1737 public static function resetGetDefaultOptionsForTestsOnly() {
1738 Assert
::invariant( defined( 'MW_PHPUNIT_TEST' ), 'Unit tests only' );
1739 self
::$defOpt = null;
1740 self
::$defOptLang = null;
1744 * Combine the language default options with any site-specific options
1745 * and add the default language variants.
1747 * @return array Array of String options
1749 public static function getDefaultOptions() {
1750 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgDefaultSkin;
1752 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
1753 if ( self
::$defOpt !== null && self
::$defOptLang === $contLang->getCode() ) {
1754 // The content language does not change (and should not change) mid-request, but the
1755 // unit tests change it anyway, and expect this method to return values relevant to the
1756 // current content language.
1757 return self
::$defOpt;
1760 self
::$defOpt = $wgDefaultUserOptions;
1761 // Default language setting
1762 self
::$defOptLang = $contLang->getCode();
1763 self
::$defOpt['language'] = self
::$defOptLang;
1764 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1765 if ( $langCode === $contLang->getCode() ) {
1766 self
::$defOpt['variant'] = $langCode;
1768 self
::$defOpt["variant-$langCode"] = $langCode;
1772 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1773 // since extensions may change the set of searchable namespaces depending
1774 // on user groups/permissions.
1775 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1776 self
::$defOpt['searchNs' . $nsnum] = (bool)$val;
1778 self
::$defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1780 Hooks
::run( 'UserGetDefaultOptions', [ &self
::$defOpt ] );
1782 return self
::$defOpt;
1786 * Get a given default option value.
1788 * @param string $opt Name of option to retrieve
1789 * @return string Default option value
1791 public static function getDefaultOption( $opt ) {
1792 $defOpts = self
::getDefaultOptions();
1793 return $defOpts[$opt] ??
null;
1797 * Get blocking information
1799 * TODO: Move this into the BlockManager, along with block-related properties.
1801 * @param bool $fromReplica Whether to check the replica DB first.
1802 * To improve performance, non-critical checks are done against replica DBs.
1803 * Check when actually saving should be done against master.
1805 private function getBlockedStatus( $fromReplica = true ) {
1806 if ( $this->mBlockedby
!= -1 ) {
1810 wfDebug( __METHOD__
. ": checking...\n" );
1812 // Initialize data...
1813 // Otherwise something ends up stomping on $this->mBlockedby when
1814 // things get lazy-loaded later, causing false positive block hits
1815 // due to -1 !== 0. Probably session-related... Nothing should be
1816 // overwriting mBlockedby, surely?
1819 $block = MediaWikiServices
::getInstance()->getBlockManager()->getUserBlock(
1824 if ( $block instanceof AbstractBlock
) {
1825 wfDebug( __METHOD__
. ": Found block.\n" );
1826 $this->mBlock
= $block;
1827 $this->mBlockedby
= $block->getByName();
1828 $this->mBlockreason
= $block->getReason();
1829 $this->mHideName
= $block->getHideName();
1830 $this->mAllowUsertalk
= $block->isUsertalkEditAllowed();
1832 $this->mBlock
= null;
1833 $this->mBlockedby
= '';
1834 $this->mBlockreason
= '';
1835 $this->mHideName
= 0;
1836 $this->mAllowUsertalk
= false;
1839 // Avoid PHP 7.1 warning of passing $this by reference
1842 Hooks
::run( 'GetBlockedStatus', [ &$thisUser ] );
1846 * Whether the given IP is in a DNS blacklist.
1848 * @deprecated since 1.34 Use BlockManager::isDnsBlacklisted.
1849 * @param string $ip IP to check
1850 * @param bool $checkWhitelist Whether to check the whitelist first
1851 * @return bool True if blacklisted.
1853 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1854 return MediaWikiServices
::getInstance()->getBlockManager()
1855 ->isDnsBlacklisted( $ip, $checkWhitelist );
1859 * Whether the given IP is in a given DNS blacklist.
1861 * @deprecated since 1.34 Check via BlockManager::isDnsBlacklisted instead.
1862 * @param string $ip IP to check
1863 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1864 * @return bool True if blacklisted.
1866 public function inDnsBlacklist( $ip, $bases ) {
1867 wfDeprecated( __METHOD__
, '1.34' );
1870 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1871 if ( IP
::isIPv4( $ip ) ) {
1872 // Reverse IP, T23255
1873 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1875 foreach ( (array)$bases as $base ) {
1877 // If we have an access key, use that too (ProjectHoneypot, etc.)
1879 if ( is_array( $base ) ) {
1880 if ( count( $base ) >= 2 ) {
1881 // Access key is 1, base URL is 0
1882 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1884 $host = "$ipReversed.{$base[0]}";
1886 $basename = $base[0];
1888 $host = "$ipReversed.$base";
1892 $ipList = gethostbynamel( $host );
1895 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1900 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1908 * Check if an IP address is in the local proxy list
1910 * @deprecated since 1.34 Use BlockManager::getUserBlock instead.
1914 public static function isLocallyBlockedProxy( $ip ) {
1915 wfDeprecated( __METHOD__
, '1.34' );
1917 global $wgProxyList;
1919 if ( !$wgProxyList ) {
1923 if ( !is_array( $wgProxyList ) ) {
1924 // Load values from the specified file
1925 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1928 $resultProxyList = [];
1929 $deprecatedIPEntries = [];
1931 // backward compatibility: move all ip addresses in keys to values
1932 foreach ( $wgProxyList as $key => $value ) {
1933 $keyIsIP = IP
::isIPAddress( $key );
1934 $valueIsIP = IP
::isIPAddress( $value );
1935 if ( $keyIsIP && !$valueIsIP ) {
1936 $deprecatedIPEntries[] = $key;
1937 $resultProxyList[] = $key;
1938 } elseif ( $keyIsIP && $valueIsIP ) {
1939 $deprecatedIPEntries[] = $key;
1940 $resultProxyList[] = $key;
1941 $resultProxyList[] = $value;
1943 $resultProxyList[] = $value;
1947 if ( $deprecatedIPEntries ) {
1949 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
1950 implode( ', ', $deprecatedIPEntries ) . ', please move them to values)', '1.30' );
1953 $proxyListIPSet = new IPSet( $resultProxyList );
1954 return $proxyListIPSet->match( $ip );
1958 * Is this user subject to rate limiting?
1960 * @return bool True if rate limited
1962 public function isPingLimitable() {
1963 global $wgRateLimitsExcludedIPs;
1964 if ( IP
::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1965 // No other good way currently to disable rate limits
1966 // for specific IPs. :P
1967 // But this is a crappy hack and should die.
1970 return !$this->isAllowed( 'noratelimit' );
1974 * Primitive rate limits: enforce maximum actions per time period
1975 * to put a brake on flooding.
1977 * The method generates both a generic profiling point and a per action one
1978 * (suffix being "-$action".
1980 * @note When using a shared cache like memcached, IP-address
1981 * last-hit counters will be shared across wikis.
1983 * @param string $action Action to enforce; 'edit' if unspecified
1984 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1985 * @return bool True if a rate limiter was tripped
1987 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1988 // Avoid PHP 7.1 warning of passing $this by reference
1990 // Call the 'PingLimiter' hook
1992 if ( !Hooks
::run( 'PingLimiter', [ &$user, $action, &$result, $incrBy ] ) ) {
1996 global $wgRateLimits;
1997 if ( !isset( $wgRateLimits[$action] ) ) {
2001 $limits = array_merge(
2002 [ '&can-bypass' => true ],
2003 $wgRateLimits[$action]
2006 // Some groups shouldn't trigger the ping limiter, ever
2007 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
2012 $id = $this->getId();
2014 $isNewbie = $this->isNewbie();
2015 $cache = ObjectCache
::getLocalClusterInstance();
2019 if ( isset( $limits['anon'] ) ) {
2020 $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
2022 } elseif ( isset( $limits['user'] ) ) {
2023 // limits for logged-in users
2024 $userLimit = $limits['user'];
2027 // limits for anons and for newbie logged-in users
2030 if ( isset( $limits['ip'] ) ) {
2031 $ip = $this->getRequest()->getIP();
2032 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
2034 // subnet-based limits
2035 if ( isset( $limits['subnet'] ) ) {
2036 $ip = $this->getRequest()->getIP();
2037 $subnet = IP
::getSubnet( $ip );
2038 if ( $subnet !== false ) {
2039 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
2044 // Check for group-specific permissions
2045 // If more than one group applies, use the group with the highest limit ratio (max/period)
2046 foreach ( $this->getGroups() as $group ) {
2047 if ( isset( $limits[$group] ) ) {
2048 if ( $userLimit === false
2049 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2051 $userLimit = $limits[$group];
2056 // limits for newbie logged-in users (override all the normal user limits)
2057 if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
2058 $userLimit = $limits['newbie'];
2061 // Set the user limit key
2062 if ( $userLimit !== false ) {
2063 // phan is confused because &can-bypass's value is a bool, so it assumes
2064 // that $userLimit is also a bool here.
2065 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2066 list( $max, $period ) = $userLimit;
2067 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
2068 $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
2071 // ip-based limits for all ping-limitable users
2072 if ( isset( $limits['ip-all'] ) ) {
2073 $ip = $this->getRequest()->getIP();
2074 // ignore if user limit is more permissive
2075 if ( $isNewbie ||
$userLimit === false
2076 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2077 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
2081 // subnet-based limits for all ping-limitable users
2082 if ( isset( $limits['subnet-all'] ) ) {
2083 $ip = $this->getRequest()->getIP();
2084 $subnet = IP
::getSubnet( $ip );
2085 if ( $subnet !== false ) {
2086 // ignore if user limit is more permissive
2087 if ( $isNewbie ||
$userLimit === false
2088 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
2089 > $userLimit[0] / $userLimit[1] ) {
2090 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
2096 foreach ( $keys as $key => $limit ) {
2097 // phan is confused because &can-bypass's value is a bool, so it assumes
2098 // that $userLimit is also a bool here.
2099 // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
2100 list( $max, $period ) = $limit;
2101 $summary = "(limit $max in {$period}s)";
2102 $count = $cache->get( $key );
2105 if ( $count >= $max ) {
2106 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
2107 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2110 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
2113 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
2114 if ( $incrBy > 0 ) {
2115 $cache->add( $key, 0, intval( $period ) ); // first ping
2118 if ( $incrBy > 0 ) {
2119 $cache->incr( $key, $incrBy );
2127 * Check if user is blocked
2129 * @deprecated since 1.34, use User::getBlock() or
2130 * PermissionManager::isBlockedFrom() or
2131 * PermissionManager::userCan() instead.
2133 * @param bool $fromReplica Whether to check the replica DB instead of
2134 * the master. Hacked from false due to horrible probs on site.
2135 * @return bool True if blocked, false otherwise
2137 public function isBlocked( $fromReplica = true ) {
2138 return $this->getBlock( $fromReplica ) instanceof AbstractBlock
&&
2139 $this->getBlock()->appliesToRight( 'edit' );
2143 * Get the block affecting the user, or null if the user is not blocked
2145 * @param bool $fromReplica Whether to check the replica DB instead of the master
2146 * @return AbstractBlock|null
2148 public function getBlock( $fromReplica = true ) {
2149 $this->getBlockedStatus( $fromReplica );
2150 return $this->mBlock
instanceof AbstractBlock ?
$this->mBlock
: null;
2154 * Check if user is blocked from editing a particular article
2156 * @param Title $title Title to check
2157 * @param bool $fromReplica Whether to check the replica DB instead of the master
2159 * @throws MWException
2161 * @deprecated since 1.33,
2162 * use MediaWikiServices::getInstance()->getPermissionManager()->isBlockedFrom(..)
2165 public function isBlockedFrom( $title, $fromReplica = false ) {
2166 return MediaWikiServices
::getInstance()->getPermissionManager()
2167 ->isBlockedFrom( $this, $title, $fromReplica );
2171 * If user is blocked, return the name of the user who placed the block
2172 * @return string Name of blocker
2174 public function blockedBy() {
2175 $this->getBlockedStatus();
2176 return $this->mBlockedby
;
2180 * If user is blocked, return the specified reason for the block
2181 * @return string Blocking reason
2183 public function blockedFor() {
2184 $this->getBlockedStatus();
2185 return $this->mBlockreason
;
2189 * If user is blocked, return the ID for the block
2190 * @return int Block ID
2192 public function getBlockId() {
2193 $this->getBlockedStatus();
2194 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2198 * Check if user is blocked on all wikis.
2199 * Do not use for actual edit permission checks!
2200 * This is intended for quick UI checks.
2202 * @param string $ip IP address, uses current client if none given
2203 * @return bool True if blocked, false otherwise
2205 public function isBlockedGlobally( $ip = '' ) {
2206 return $this->getGlobalBlock( $ip ) instanceof AbstractBlock
;
2210 * Check if user is blocked on all wikis.
2211 * Do not use for actual edit permission checks!
2212 * This is intended for quick UI checks.
2214 * @param string $ip IP address, uses current client if none given
2215 * @return AbstractBlock|null Block object if blocked, null otherwise
2216 * @throws FatalError
2217 * @throws MWException
2219 public function getGlobalBlock( $ip = '' ) {
2220 if ( $this->mGlobalBlock
!== null ) {
2221 return $this->mGlobalBlock ?
: null;
2223 // User is already an IP?
2224 if ( IP
::isIPAddress( $this->getName() ) ) {
2225 $ip = $this->getName();
2227 $ip = $this->getRequest()->getIP();
2229 // Avoid PHP 7.1 warning of passing $this by reference
2233 Hooks
::run( 'UserIsBlockedGlobally', [ &$user, $ip, &$blocked, &$block ] );
2235 if ( $blocked && $block === null ) {
2236 // back-compat: UserIsBlockedGlobally didn't have $block param first
2237 $block = new SystemBlock( [
2239 'systemBlock' => 'global-block'
2243 $this->mGlobalBlock
= $blocked ?
$block : false;
2244 return $this->mGlobalBlock ?
: null;
2248 * Check if user account is locked
2250 * @return bool True if locked, false otherwise
2252 public function isLocked() {
2253 if ( $this->mLocked
!== null ) {
2254 return $this->mLocked
;
2257 $this->mLocked
= false;
2258 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2259 return $this->mLocked
;
2263 * Check if user account is hidden
2265 * @return bool True if hidden, false otherwise
2267 public function isHidden() {
2268 if ( $this->mHideName
!== null ) {
2269 return (bool)$this->mHideName
;
2271 $this->getBlockedStatus();
2272 if ( !$this->mHideName
) {
2274 $this->mHideName
= false;
2275 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2277 return (bool)$this->mHideName
;
2281 * Get the user's ID.
2282 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2284 public function getId() {
2285 if ( $this->mId
=== null && $this->mName
!== null && self
::isIP( $this->mName
) ) {
2286 // Special case, we know the user is anonymous
2290 if ( !$this->isItemLoaded( 'id' ) ) {
2291 // Don't load if this was initialized from an ID
2295 return (int)$this->mId
;
2299 * Set the user and reload all fields according to a given ID
2300 * @param int $v User ID to reload
2302 public function setId( $v ) {
2304 $this->clearInstanceCache( 'id' );
2308 * Get the user name, or the IP of an anonymous user
2309 * @return string User's name or IP address
2311 public function getName() {
2312 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2313 // Special case optimisation
2314 return $this->mName
;
2318 if ( $this->mName
=== false ) {
2320 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2323 return $this->mName
;
2327 * Set the user name.
2329 * This does not reload fields from the database according to the given
2330 * name. Rather, it is used to create a temporary "nonexistent user" for
2331 * later addition to the database. It can also be used to set the IP
2332 * address for an anonymous user to something other than the current
2335 * @note User::newFromName() has roughly the same function, when the named user
2337 * @param string $str New user name to set
2339 public function setName( $str ) {
2341 $this->mName
= $str;
2345 * Get the user's actor ID.
2347 * @param IDatabase|null $dbw Assign a new actor ID, using this DB handle, if none exists
2348 * @return int The actor's ID, or 0 if no actor ID exists and $dbw was null
2350 public function getActorId( IDatabase
$dbw = null ) {
2351 global $wgActorTableSchemaMigrationStage;
2353 // Technically we should always return 0 without SCHEMA_COMPAT_READ_NEW,
2354 // but it does little harm and might be needed for write callers loading a User.
2355 if ( !( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) ) {
2359 if ( !$this->isItemLoaded( 'actor' ) ) {
2363 // Currently $this->mActorId might be null if $this was loaded from a
2364 // cache entry that was written when $wgActorTableSchemaMigrationStage
2365 // was SCHEMA_COMPAT_OLD. Once that is no longer a possibility (i.e. when
2366 // User::VERSION is incremented after $wgActorTableSchemaMigrationStage
2367 // has been removed), that condition may be removed.
2368 if ( $this->mActorId
=== null ||
!$this->mActorId
&& $dbw ) {
2370 'actor_user' => $this->getId() ?
: null,
2371 'actor_name' => (string)$this->getName(),
2374 if ( $q['actor_user'] === null && self
::isUsableName( $q['actor_name'] ) ) {
2375 throw new CannotCreateActorException(
2376 'Cannot create an actor for a usable name that is not an existing user'
2379 if ( $q['actor_name'] === '' ) {
2380 throw new CannotCreateActorException( 'Cannot create an actor for a user with no name' );
2382 $dbw->insert( 'actor', $q, __METHOD__
, [ 'IGNORE' ] );
2383 if ( $dbw->affectedRows() ) {
2384 $this->mActorId
= (int)$dbw->insertId();
2387 // Use LOCK IN SHARE MODE to bypass any MySQL REPEATABLE-READ snapshot.
2388 $this->mActorId
= (int)$dbw->selectField(
2393 [ 'LOCK IN SHARE MODE' ]
2395 if ( !$this->mActorId
) {
2396 throw new CannotCreateActorException(
2397 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2401 $this->invalidateCache();
2403 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $this->queryFlagsUsed
);
2404 $db = wfGetDB( $index );
2405 $this->mActorId
= (int)$db->selectField( 'actor', 'actor_id', $q, __METHOD__
, $options );
2407 $this->setItemLoaded( 'actor' );
2410 return (int)$this->mActorId
;
2414 * Get the user's name escaped by underscores.
2415 * @return string Username escaped by underscores.
2417 public function getTitleKey() {
2418 return str_replace( ' ', '_', $this->getName() );
2422 * Check if the user has new messages.
2423 * @return bool True if the user has new messages
2425 public function getNewtalk() {
2428 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2429 if ( $this->mNewtalk
=== -1 ) {
2430 $this->mNewtalk
= false; # reset talk page status
2432 // Check memcached separately for anons, who have no
2433 // entire User object stored in there.
2434 if ( !$this->mId
) {
2435 global $wgDisableAnonTalk;
2436 if ( $wgDisableAnonTalk ) {
2437 // Anon newtalk disabled by configuration.
2438 $this->mNewtalk
= false;
2440 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2443 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2447 return (bool)$this->mNewtalk
;
2451 * Return the data needed to construct links for new talk page message
2452 * alerts. If there are new messages, this will return an associative array
2453 * with the following data:
2454 * wiki: The database name of the wiki
2455 * link: Root-relative link to the user's talk page
2456 * rev: The last talk page revision that the user has seen or null. This
2457 * is useful for building diff links.
2458 * If there are no new messages, it returns an empty array.
2459 * @note This function was designed to accomodate multiple talk pages, but
2460 * currently only returns a single link and revision.
2463 public function getNewMessageLinks() {
2464 // Avoid PHP 7.1 warning of passing $this by reference
2467 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$user, &$talks ] ) ) {
2471 if ( !$this->getNewtalk() ) {
2474 $utp = $this->getTalkPage();
2475 $dbr = wfGetDB( DB_REPLICA
);
2476 // Get the "last viewed rev" timestamp from the oldest message notification
2477 $timestamp = $dbr->selectField( 'user_newtalk',
2478 'MIN(user_last_timestamp)',
2479 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2481 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2484 'wiki' => WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() ),
2485 'link' => $utp->getLocalURL(),
2492 * Get the revision ID for the last talk page revision viewed by the talk
2494 * @return int|null Revision ID or null
2496 public function getNewMessageRevisionId() {
2497 $newMessageRevisionId = null;
2498 $newMessageLinks = $this->getNewMessageLinks();
2500 // Note: getNewMessageLinks() never returns more than a single link
2501 // and it is always for the same wiki, but we double-check here in
2502 // case that changes some time in the future.
2503 if ( $newMessageLinks && count( $newMessageLinks ) === 1
2504 && WikiMap
::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2505 && $newMessageLinks[0]['rev']
2507 /** @var Revision $newMessageRevision */
2508 $newMessageRevision = $newMessageLinks[0]['rev'];
2509 $newMessageRevisionId = $newMessageRevision->getId();
2512 return $newMessageRevisionId;
2516 * Internal uncached check for new messages
2519 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2520 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2521 * @return bool True if the user has new messages
2523 protected function checkNewtalk( $field, $id ) {
2524 $dbr = wfGetDB( DB_REPLICA
);
2526 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2528 return $ok !== false;
2532 * Add or update the new messages flag
2533 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2534 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2535 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2536 * @return bool True if successful, false otherwise
2538 protected function updateNewtalk( $field, $id, $curRev = null ) {
2539 // Get timestamp of the talk page revision prior to the current one
2540 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2541 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2542 // Mark the user as having new messages since this revision
2543 $dbw = wfGetDB( DB_MASTER
);
2544 $dbw->insert( 'user_newtalk',
2545 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2548 if ( $dbw->affectedRows() ) {
2549 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2553 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2558 * Clear the new messages flag for the given user
2559 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2560 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2561 * @return bool True if successful, false otherwise
2563 protected function deleteNewtalk( $field, $id ) {
2564 $dbw = wfGetDB( DB_MASTER
);
2565 $dbw->delete( 'user_newtalk',
2568 if ( $dbw->affectedRows() ) {
2569 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2573 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2578 * Update the 'You have new messages!' status.
2579 * @param bool $val Whether the user has new messages
2580 * @param Revision|null $curRev New, as yet unseen revision of the user talk
2581 * page. Ignored if null or !$val.
2583 public function setNewtalk( $val, $curRev = null ) {
2584 if ( wfReadOnly() ) {
2589 $this->mNewtalk
= $val;
2591 if ( $this->isAnon() ) {
2593 $id = $this->getName();
2596 $id = $this->getId();
2600 $changed = $this->updateNewtalk( $field, $id, $curRev );
2602 $changed = $this->deleteNewtalk( $field, $id );
2606 $this->invalidateCache();
2611 * Generate a current or new-future timestamp to be stored in the
2612 * user_touched field when we update things.
2614 * @return string Timestamp in TS_MW format
2616 private function newTouchedTimestamp() {
2618 if ( $this->mTouched
) {
2619 $time = max( $time, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2622 return wfTimestamp( TS_MW
, $time );
2626 * Clear user data from memcached
2628 * Use after applying updates to the database; caller's
2629 * responsibility to update user_touched if appropriate.
2631 * Called implicitly from invalidateCache() and saveSettings().
2633 * @param string $mode Use 'refresh' to clear now or 'changed' to clear before DB commit
2635 public function clearSharedCache( $mode = 'refresh' ) {
2636 if ( !$this->getId() ) {
2640 $lb = MediaWikiServices
::getInstance()->getDBLoadBalancer();
2641 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2642 $key = $this->getCacheKey( $cache );
2644 if ( $mode === 'refresh' ) {
2645 $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2647 $lb->getConnection( DB_MASTER
)->onTransactionPreCommitOrIdle(
2648 function () use ( $cache, $key ) {
2649 $cache->delete( $key );
2657 * Immediately touch the user data cache for this account
2659 * Calls touch() and removes account data from memcached
2661 public function invalidateCache() {
2663 $this->clearSharedCache( 'changed' );
2667 * Update the "touched" timestamp for the user
2669 * This is useful on various login/logout events when making sure that
2670 * a browser or proxy that has multiple tenants does not suffer cache
2671 * pollution where the new user sees the old users content. The value
2672 * of getTouched() is checked when determining 304 vs 200 responses.
2673 * Unlike invalidateCache(), this preserves the User object cache and
2674 * avoids database writes.
2678 public function touch() {
2679 $id = $this->getId();
2681 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2682 $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2683 $cache->touchCheckKey( $key );
2684 $this->mQuickTouched
= null;
2689 * Validate the cache for this account.
2690 * @param string $timestamp A timestamp in TS_MW format
2693 public function validateCache( $timestamp ) {
2694 return ( $timestamp >= $this->getTouched() );
2698 * Get the user touched timestamp
2700 * Use this value only to validate caches via inequalities
2701 * such as in the case of HTTP If-Modified-Since response logic
2703 * @return string TS_MW Timestamp
2705 public function getTouched() {
2709 if ( $this->mQuickTouched
=== null ) {
2710 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2711 $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId
);
2713 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2716 return max( $this->mTouched
, $this->mQuickTouched
);
2719 return $this->mTouched
;
2723 * Get the user_touched timestamp field (time of last DB updates)
2724 * @return string TS_MW Timestamp
2727 public function getDBTouched() {
2730 return $this->mTouched
;
2734 * Set the password and reset the random token.
2735 * Calls through to authentication plugin if necessary;
2736 * will have no effect if the auth plugin refuses to
2737 * pass the change through or if the legal password
2740 * As a special case, setting the password to null
2741 * wipes it, so the account cannot be logged in until
2742 * a new password is set, for instance via e-mail.
2744 * @deprecated since 1.27, use AuthManager instead
2745 * @param string $str New password to set
2746 * @throws PasswordError On failure
2749 public function setPassword( $str ) {
2750 wfDeprecated( __METHOD__
, '1.27' );
2751 return $this->setPasswordInternal( $str );
2755 * Set the password and reset the random token unconditionally.
2757 * @deprecated since 1.27, use AuthManager instead
2758 * @param string|null $str New password to set or null to set an invalid
2759 * password hash meaning that the user will not be able to log in
2760 * through the web interface.
2762 public function setInternalPassword( $str ) {
2763 wfDeprecated( __METHOD__
, '1.27' );
2764 $this->setPasswordInternal( $str );
2768 * Actually set the password and such
2769 * @since 1.27 cannot set a password for a user not in the database
2770 * @param string|null $str New password to set or null to set an invalid
2771 * password hash meaning that the user will not be able to log in
2772 * through the web interface.
2773 * @return bool Success
2775 private function setPasswordInternal( $str ) {
2776 $manager = AuthManager
::singleton();
2778 // If the user doesn't exist yet, fail
2779 if ( !$manager->userExists( $this->getName() ) ) {
2780 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2783 $status = $this->changeAuthenticationData( [
2784 'username' => $this->getName(),
2788 if ( !$status->isGood() ) {
2789 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2790 ->info( __METHOD__
. ': Password change rejected: '
2791 . $status->getWikiText( null, null, 'en' ) );
2795 $this->setOption( 'watchlisttoken', false );
2796 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2802 * Changes credentials of the user.
2804 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2805 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2806 * e.g. when no provider handled the change.
2808 * @param array $data A set of authentication data in fieldname => value format. This is the
2809 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2813 public function changeAuthenticationData( array $data ) {
2814 $manager = AuthManager
::singleton();
2815 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2816 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2818 $status = Status
::newGood( 'ignored' );
2819 foreach ( $reqs as $req ) {
2820 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2822 if ( $status->getValue() === 'ignored' ) {
2823 $status->warning( 'authenticationdatachange-ignored' );
2826 if ( $status->isGood() ) {
2827 foreach ( $reqs as $req ) {
2828 $manager->changeAuthenticationData( $req );
2835 * Get the user's current token.
2836 * @param bool $forceCreation Force the generation of a new token if the
2837 * user doesn't have one (default=true for backwards compatibility).
2838 * @return string|null Token
2840 public function getToken( $forceCreation = true ) {
2841 global $wgAuthenticationTokenVersion;
2844 if ( !$this->mToken
&& $forceCreation ) {
2848 if ( !$this->mToken
) {
2849 // The user doesn't have a token, return null to indicate that.
2853 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2854 // We return a random value here so existing token checks are very
2856 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2859 if ( $wgAuthenticationTokenVersion === null ) {
2860 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2861 return $this->mToken
;
2864 // $wgAuthenticationTokenVersion in use, so hmac it.
2865 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2867 // The raw hash can be overly long. Shorten it up.
2868 $len = max( 32, self
::TOKEN_LENGTH
);
2869 if ( strlen( $ret ) < $len ) {
2870 // Should never happen, even md5 is 128 bits
2871 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2874 return substr( $ret, -$len );
2878 * Set the random token (used for persistent authentication)
2879 * Called from loadDefaults() among other places.
2881 * @param string|bool $token If specified, set the token to this value
2883 public function setToken( $token = false ) {
2885 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2886 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2887 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2888 } elseif ( !$token ) {
2889 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2891 $this->mToken
= $token;
2896 * Set the password for a password reminder or new account email
2898 * @deprecated Removed in 1.27. Use PasswordReset instead.
2899 * @param string $str New password to set or null to set an invalid
2900 * password hash meaning that the user will not be able to use it
2901 * @param bool $throttle If true, reset the throttle timestamp to the present
2903 public function setNewpassword( $str, $throttle = true ) {
2904 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2908 * Get the user's e-mail address
2909 * @return string User's email address
2911 public function getEmail() {
2913 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2914 return $this->mEmail
;
2918 * Get the timestamp of the user's e-mail authentication
2919 * @return string TS_MW timestamp
2921 public function getEmailAuthenticationTimestamp() {
2923 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2924 return $this->mEmailAuthenticated
;
2928 * Set the user's e-mail address
2929 * @param string $str New e-mail address
2931 public function setEmail( $str ) {
2933 if ( $str == $this->mEmail
) {
2936 $this->invalidateEmail();
2937 $this->mEmail
= $str;
2938 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2942 * Set the user's e-mail address and a confirmation mail if needed.
2945 * @param string $str New e-mail address
2948 public function setEmailWithConfirmation( $str ) {
2949 global $wgEnableEmail, $wgEmailAuthentication;
2951 if ( !$wgEnableEmail ) {
2952 return Status
::newFatal( 'emaildisabled' );
2955 $oldaddr = $this->getEmail();
2956 if ( $str === $oldaddr ) {
2957 return Status
::newGood( true );
2960 $type = $oldaddr != '' ?
'changed' : 'set';
2961 $notificationResult = null;
2963 if ( $wgEmailAuthentication && $type === 'changed' ) {
2964 // Send the user an email notifying the user of the change in registered
2965 // email address on their previous email address
2966 $change = $str != '' ?
'changed' : 'removed';
2967 $notificationResult = $this->sendMail(
2968 wfMessage( 'notificationemail_subject_' . $change )->text(),
2969 wfMessage( 'notificationemail_body_' . $change,
2970 $this->getRequest()->getIP(),
2976 $this->setEmail( $str );
2978 if ( $str !== '' && $wgEmailAuthentication ) {
2979 // Send a confirmation request to the new address if needed
2980 $result = $this->sendConfirmationMail( $type );
2982 if ( $notificationResult !== null ) {
2983 $result->merge( $notificationResult );
2986 if ( $result->isGood() ) {
2987 // Say to the caller that a confirmation and notification mail has been sent
2988 $result->value
= 'eauth';
2991 $result = Status
::newGood( true );
2998 * Get the user's real name
2999 * @return string User's real name
3001 public function getRealName() {
3002 if ( !$this->isItemLoaded( 'realname' ) ) {
3006 return $this->mRealName
;
3010 * Set the user's real name
3011 * @param string $str New real name
3013 public function setRealName( $str ) {
3015 $this->mRealName
= $str;
3019 * Get the user's current setting for a given option.
3021 * @param string $oname The option to check
3022 * @param string|array|null $defaultOverride A default value returned if the option does not exist
3023 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
3024 * @return string|array|int|null User's current value for the option
3025 * @see getBoolOption()
3026 * @see getIntOption()
3028 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
3029 global $wgHiddenPrefs;
3030 $this->loadOptions();
3032 # We want 'disabled' preferences to always behave as the default value for
3033 # users, even if they have set the option explicitly in their settings (ie they
3034 # set it, and then it was disabled removing their ability to change it). But
3035 # we don't want to erase the preferences in the database in case the preference
3036 # is re-enabled again. So don't touch $mOptions, just override the returned value
3037 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
3038 return self
::getDefaultOption( $oname );
3041 if ( array_key_exists( $oname, $this->mOptions
) ) {
3042 return $this->mOptions
[$oname];
3045 return $defaultOverride;
3049 * Get all user's options
3051 * @param int $flags Bitwise combination of:
3052 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
3053 * to the default value. (Since 1.25)
3056 public function getOptions( $flags = 0 ) {
3057 global $wgHiddenPrefs;
3058 $this->loadOptions();
3059 $options = $this->mOptions
;
3061 # We want 'disabled' preferences to always behave as the default value for
3062 # users, even if they have set the option explicitly in their settings (ie they
3063 # set it, and then it was disabled removing their ability to change it). But
3064 # we don't want to erase the preferences in the database in case the preference
3065 # is re-enabled again. So don't touch $mOptions, just override the returned value
3066 foreach ( $wgHiddenPrefs as $pref ) {
3067 $default = self
::getDefaultOption( $pref );
3068 if ( $default !== null ) {
3069 $options[$pref] = $default;
3073 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
3074 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
3081 * Get the user's current setting for a given option, as a boolean value.
3083 * @param string $oname The option to check
3084 * @return bool User's current value for the option
3087 public function getBoolOption( $oname ) {
3088 return (bool)$this->getOption( $oname );
3092 * Get the user's current setting for a given option, as an integer value.
3094 * @param string $oname The option to check
3095 * @param int $defaultOverride A default value returned if the option does not exist
3096 * @return int User's current value for the option
3099 public function getIntOption( $oname, $defaultOverride = 0 ) {
3100 $val = $this->getOption( $oname );
3102 $val = $defaultOverride;
3104 return intval( $val );
3108 * Set the given option for a user.
3110 * You need to call saveSettings() to actually write to the database.
3112 * @param string $oname The option to set
3113 * @param mixed $val New value to set
3115 public function setOption( $oname, $val ) {
3116 $this->loadOptions();
3118 // Explicitly NULL values should refer to defaults
3119 if ( is_null( $val ) ) {
3120 $val = self
::getDefaultOption( $oname );
3123 $this->mOptions
[$oname] = $val;
3127 * Get a token stored in the preferences (like the watchlist one),
3128 * resetting it if it's empty (and saving changes).
3130 * @param string $oname The option name to retrieve the token from
3131 * @return string|bool User's current value for the option, or false if this option is disabled.
3132 * @see resetTokenFromOption()
3134 * @deprecated since 1.26 Applications should use the OAuth extension
3136 public function getTokenFromOption( $oname ) {
3137 global $wgHiddenPrefs;
3139 $id = $this->getId();
3140 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
3144 $token = $this->getOption( $oname );
3146 // Default to a value based on the user token to avoid space
3147 // wasted on storing tokens for all users. When this option
3148 // is set manually by the user, only then is it stored.
3149 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
3156 * Reset a token stored in the preferences (like the watchlist one).
3157 * *Does not* save user's preferences (similarly to setOption()).
3159 * @param string $oname The option name to reset the token in
3160 * @return string|bool New token value, or false if this option is disabled.
3161 * @see getTokenFromOption()
3164 public function resetTokenFromOption( $oname ) {
3165 global $wgHiddenPrefs;
3166 if ( in_array( $oname, $wgHiddenPrefs ) ) {
3170 $token = MWCryptRand
::generateHex( 40 );
3171 $this->setOption( $oname, $token );
3176 * Return a list of the types of user options currently returned by
3177 * User::getOptionKinds().
3179 * Currently, the option kinds are:
3180 * - 'registered' - preferences which are registered in core MediaWiki or
3181 * by extensions using the UserGetDefaultOptions hook.
3182 * - 'registered-multiselect' - as above, using the 'multiselect' type.
3183 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
3184 * - 'userjs' - preferences with names starting with 'userjs-', intended to
3185 * be used by user scripts.
3186 * - 'special' - "preferences" that are not accessible via User::getOptions
3187 * or User::setOptions.
3188 * - 'unused' - preferences about which MediaWiki doesn't know anything.
3189 * These are usually legacy options, removed in newer versions.
3191 * The API (and possibly others) use this function to determine the possible
3192 * option types for validation purposes, so make sure to update this when a
3193 * new option kind is added.
3195 * @see User::getOptionKinds
3196 * @return array Option kinds
3198 public static function listOptionKinds() {
3201 'registered-multiselect',
3202 'registered-checkmatrix',
3210 * Return an associative array mapping preferences keys to the kind of a preference they're
3211 * used for. Different kinds are handled differently when setting or reading preferences.
3213 * See User::listOptionKinds for the list of valid option types that can be provided.
3215 * @see User::listOptionKinds
3216 * @param IContextSource $context
3217 * @param array|null $options Assoc. array with options keys to check as keys.
3218 * Defaults to $this->mOptions.
3219 * @return array The key => kind mapping data
3221 public function getOptionKinds( IContextSource
$context, $options = null ) {
3222 $this->loadOptions();
3223 if ( $options === null ) {
3224 $options = $this->mOptions
;
3227 $preferencesFactory = MediaWikiServices
::getInstance()->getPreferencesFactory();
3228 $prefs = $preferencesFactory->getFormDescriptor( $this, $context );
3231 // Pull out the "special" options, so they don't get converted as
3232 // multiselect or checkmatrix.
3233 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(), true );
3234 foreach ( $specialOptions as $name => $value ) {
3235 unset( $prefs[$name] );
3238 // Multiselect and checkmatrix options are stored in the database with
3239 // one key per option, each having a boolean value. Extract those keys.
3240 $multiselectOptions = [];
3241 foreach ( $prefs as $name => $info ) {
3242 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3243 ( isset( $info['class'] ) && $info['class'] == HTMLMultiSelectField
::class ) ) {
3244 $opts = HTMLFormField
::flattenOptions( $info['options'] );
3245 $prefix = $info['prefix'] ??
$name;
3247 foreach ( $opts as $value ) {
3248 $multiselectOptions["$prefix$value"] = true;
3251 unset( $prefs[$name] );
3254 $checkmatrixOptions = [];
3255 foreach ( $prefs as $name => $info ) {
3256 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3257 ( isset( $info['class'] ) && $info['class'] == HTMLCheckMatrix
::class ) ) {
3258 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
3259 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
3260 $prefix = $info['prefix'] ??
$name;
3262 foreach ( $columns as $column ) {
3263 foreach ( $rows as $row ) {
3264 $checkmatrixOptions["$prefix$column-$row"] = true;
3268 unset( $prefs[$name] );
3272 // $value is ignored
3273 foreach ( $options as $key => $value ) {
3274 if ( isset( $prefs[$key] ) ) {
3275 $mapping[$key] = 'registered';
3276 } elseif ( isset( $multiselectOptions[$key] ) ) {
3277 $mapping[$key] = 'registered-multiselect';
3278 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3279 $mapping[$key] = 'registered-checkmatrix';
3280 } elseif ( isset( $specialOptions[$key] ) ) {
3281 $mapping[$key] = 'special';
3282 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3283 $mapping[$key] = 'userjs';
3285 $mapping[$key] = 'unused';
3293 * Reset certain (or all) options to the site defaults
3295 * The optional parameter determines which kinds of preferences will be reset.
3296 * Supported values are everything that can be reported by getOptionKinds()
3297 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3299 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3300 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3301 * for backwards-compatibility.
3302 * @param IContextSource|null $context Context source used when $resetKinds
3303 * does not contain 'all', passed to getOptionKinds().
3304 * Defaults to RequestContext::getMain() when null.
3306 public function resetOptions(
3307 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3308 IContextSource
$context = null
3311 $defaultOptions = self
::getDefaultOptions();
3313 if ( !is_array( $resetKinds ) ) {
3314 $resetKinds = [ $resetKinds ];
3317 if ( in_array( 'all', $resetKinds ) ) {
3318 $newOptions = $defaultOptions;
3320 if ( $context === null ) {
3321 $context = RequestContext
::getMain();
3324 $optionKinds = $this->getOptionKinds( $context );
3325 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3328 // Use default values for the options that should be deleted, and
3329 // copy old values for the ones that shouldn't.
3330 foreach ( $this->mOptions
as $key => $value ) {
3331 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3332 if ( array_key_exists( $key, $defaultOptions ) ) {
3333 $newOptions[$key] = $defaultOptions[$key];
3336 $newOptions[$key] = $value;
3341 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3343 $this->mOptions
= $newOptions;
3344 $this->mOptionsLoaded
= true;
3348 * Get the user's preferred date format.
3349 * @return string User's preferred date format
3351 public function getDatePreference() {
3352 // Important migration for old data rows
3353 if ( is_null( $this->mDatePreference
) ) {
3355 $value = $this->getOption( 'date' );
3356 $map = $wgLang->getDatePreferenceMigrationMap();
3357 if ( isset( $map[$value] ) ) {
3358 $value = $map[$value];
3360 $this->mDatePreference
= $value;
3362 return $this->mDatePreference
;
3366 * Determine based on the wiki configuration and the user's options,
3367 * whether this user must be over HTTPS no matter what.
3371 public function requiresHTTPS() {
3372 global $wgSecureLogin;
3373 if ( !$wgSecureLogin ) {
3377 $https = $this->getBoolOption( 'prefershttps' );
3378 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3380 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3387 * Get the user preferred stub threshold
3391 public function getStubThreshold() {
3392 global $wgMaxArticleSize; # Maximum article size, in Kb
3393 $threshold = $this->getIntOption( 'stubthreshold' );
3394 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3395 // If they have set an impossible value, disable the preference
3396 // so we can use the parser cache again.
3403 * Get the permissions this user has.
3404 * @return string[] permission names
3406 public function getRights() {
3407 if ( is_null( $this->mRights
) ) {
3408 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3409 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3411 // Deny any rights denied by the user's session, unless this
3412 // endpoint has no sessions.
3413 if ( !defined( 'MW_NO_SESSION' ) ) {
3414 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3415 if ( $allowedRights !== null ) {
3416 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3420 Hooks
::run( 'UserGetRightsRemove', [ $this, &$this->mRights
] );
3421 // Force reindexation of rights when a hook has unset one of them
3422 $this->mRights
= array_values( array_unique( $this->mRights
) );
3424 // If block disables login, we should also remove any
3425 // extra rights blocked users might have, in case the
3426 // blocked user has a pre-existing session (T129738).
3427 // This is checked here for cases where people only call
3428 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3429 // to give a better error message in the common case.
3430 $config = RequestContext
::getMain()->getConfig();
3431 // @TODO Partial blocks should not prevent the user from logging in.
3432 // see: https://phabricator.wikimedia.org/T208895
3434 $this->isLoggedIn() &&
3435 $config->get( 'BlockDisablesLogin' ) &&
3439 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3442 return $this->mRights
;
3446 * Get the list of explicit group memberships this user has.
3447 * The implicit * and user groups are not included.
3449 * @return string[] Array of internal group names (sorted since 1.33)
3451 public function getGroups() {
3453 $this->loadGroups();
3454 return array_keys( $this->mGroupMemberships
);
3458 * Get the list of explicit group memberships this user has, stored as
3459 * UserGroupMembership objects. Implicit groups are not included.
3461 * @return UserGroupMembership[] Associative array of (group name => UserGroupMembership object)
3464 public function getGroupMemberships() {
3466 $this->loadGroups();
3467 return $this->mGroupMemberships
;
3471 * Get the list of implicit group memberships this user has.
3472 * This includes all explicit groups, plus 'user' if logged in,
3473 * '*' for all accounts, and autopromoted groups
3474 * @param bool $recache Whether to avoid the cache
3475 * @return array Array of String internal group names
3477 public function getEffectiveGroups( $recache = false ) {
3478 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3479 $this->mEffectiveGroups
= array_unique( array_merge(
3480 $this->getGroups(), // explicit groups
3481 $this->getAutomaticGroups( $recache ) // implicit groups
3483 // Avoid PHP 7.1 warning of passing $this by reference
3485 // Hook for additional groups
3486 Hooks
::run( 'UserEffectiveGroups', [ &$user, &$this->mEffectiveGroups
] );
3487 // Force reindexation of groups when a hook has unset one of them
3488 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3490 return $this->mEffectiveGroups
;
3494 * Get the list of implicit group memberships this user has.
3495 * This includes 'user' if logged in, '*' for all accounts,
3496 * and autopromoted groups
3497 * @param bool $recache Whether to avoid the cache
3498 * @return array Array of String internal group names
3500 public function getAutomaticGroups( $recache = false ) {
3501 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3502 $this->mImplicitGroups
= [ '*' ];
3503 if ( $this->getId() ) {
3504 $this->mImplicitGroups
[] = 'user';
3506 $this->mImplicitGroups
= array_unique( array_merge(
3507 $this->mImplicitGroups
,
3508 Autopromote
::getAutopromoteGroups( $this )
3512 // Assure data consistency with rights/groups,
3513 // as getEffectiveGroups() depends on this function
3514 $this->mEffectiveGroups
= null;
3517 return $this->mImplicitGroups
;
3521 * Returns the groups the user has belonged to.
3523 * The user may still belong to the returned groups. Compare with getGroups().
3525 * The function will not return groups the user had belonged to before MW 1.17
3527 * @return array Names of the groups the user has belonged to.
3529 public function getFormerGroups() {
3532 if ( is_null( $this->mFormerGroups
) ) {
3533 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3534 ?
wfGetDB( DB_MASTER
)
3535 : wfGetDB( DB_REPLICA
);
3536 $res = $db->select( 'user_former_groups',
3538 [ 'ufg_user' => $this->mId
],
3540 $this->mFormerGroups
= [];
3541 foreach ( $res as $row ) {
3542 $this->mFormerGroups
[] = $row->ufg_group
;
3546 return $this->mFormerGroups
;
3550 * Get the user's edit count.
3551 * @return int|null Null for anonymous users
3553 public function getEditCount() {
3554 if ( !$this->getId() ) {
3558 if ( $this->mEditCount
=== null ) {
3559 /* Populate the count, if it has not been populated yet */
3560 $dbr = wfGetDB( DB_REPLICA
);
3561 // check if the user_editcount field has been initialized
3562 $count = $dbr->selectField(
3563 'user', 'user_editcount',
3564 [ 'user_id' => $this->mId
],
3568 if ( $count === null ) {
3569 // it has not been initialized. do so.
3570 $count = $this->initEditCountInternal();
3572 $this->mEditCount
= $count;
3574 return (int)$this->mEditCount
;
3578 * Add the user to the given group. This takes immediate effect.
3579 * If the user is already in the group, the expiry time will be updated to the new
3580 * expiry time. (If $expiry is omitted or null, the membership will be altered to
3583 * @param string $group Name of the group to add
3584 * @param string|null $expiry Optional expiry timestamp in any format acceptable to
3585 * wfTimestamp(), or null if the group assignment should not expire
3588 public function addGroup( $group, $expiry = null ) {
3590 $this->loadGroups();
3593 $expiry = wfTimestamp( TS_MW
, $expiry );
3596 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3600 // create the new UserGroupMembership and put it in the DB
3601 $ugm = new UserGroupMembership( $this->mId
, $group, $expiry );
3602 if ( !$ugm->insert( true ) ) {
3606 $this->mGroupMemberships
[$group] = $ugm;
3608 // Refresh the groups caches, and clear the rights cache so it will be
3609 // refreshed on the next call to $this->getRights().
3610 $this->getEffectiveGroups( true );
3611 $this->mRights
= null;
3613 $this->invalidateCache();
3619 * Remove the user from the given group.
3620 * This takes immediate effect.
3621 * @param string $group Name of the group to remove
3624 public function removeGroup( $group ) {
3627 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3631 $ugm = UserGroupMembership
::getMembership( $this->mId
, $group );
3632 // delete the membership entry
3633 if ( !$ugm ||
!$ugm->delete() ) {
3637 $this->loadGroups();
3638 unset( $this->mGroupMemberships
[$group] );
3640 // Refresh the groups caches, and clear the rights cache so it will be
3641 // refreshed on the next call to $this->getRights().
3642 $this->getEffectiveGroups( true );
3643 $this->mRights
= null;
3645 $this->invalidateCache();
3651 * Alias of isLoggedIn() with a name that describes its actual functionality. UserIdentity has
3652 * only this new name and not the old isLoggedIn() variant.
3654 * @return bool True if user is registered on this wiki, i.e., has a user ID. False if user is
3655 * anonymous or has no local account (which can happen when importing). This is equivalent to
3656 * getId() != 0 and is provided for code readability.
3659 public function isRegistered() {
3660 return $this->getId() != 0;
3664 * Get whether the user is logged in
3667 public function isLoggedIn() {
3668 return $this->isRegistered();
3672 * Get whether the user is anonymous
3675 public function isAnon() {
3676 return !$this->isRegistered();
3680 * @return bool Whether this user is flagged as being a bot role account
3683 public function isBot() {
3684 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3689 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3695 * Check if user is allowed to access a feature / make an action
3697 * @param string $permissions,... Permissions to test
3698 * @return bool True if user is allowed to perform *any* of the given actions
3700 public function isAllowedAny() {
3701 $permissions = func_get_args();
3702 foreach ( $permissions as $permission ) {
3703 if ( $this->isAllowed( $permission ) ) {
3712 * @param string $permissions,... Permissions to test
3713 * @return bool True if the user is allowed to perform *all* of the given actions
3715 public function isAllowedAll() {
3716 $permissions = func_get_args();
3717 foreach ( $permissions as $permission ) {
3718 if ( !$this->isAllowed( $permission ) ) {
3726 * Internal mechanics of testing a permission
3727 * @param string $action
3730 public function isAllowed( $action = '' ) {
3731 if ( $action === '' ) {
3732 return true; // In the spirit of DWIM
3734 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3735 // by misconfiguration: 0 == 'foo'
3736 return in_array( $action, $this->getRights(), true );
3740 * Check whether to enable recent changes patrol features for this user
3741 * @return bool True or false
3743 public function useRCPatrol() {
3744 global $wgUseRCPatrol;
3745 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3749 * Check whether to enable new pages patrol features for this user
3750 * @return bool True or false
3752 public function useNPPatrol() {
3753 global $wgUseRCPatrol, $wgUseNPPatrol;
3755 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3756 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3761 * Check whether to enable new files patrol features for this user
3762 * @return bool True or false
3764 public function useFilePatrol() {
3765 global $wgUseRCPatrol, $wgUseFilePatrol;
3767 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3768 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3773 * Get the WebRequest object to use with this object
3775 * @return WebRequest
3777 public function getRequest() {
3778 if ( $this->mRequest
) {
3779 return $this->mRequest
;
3787 * Check the watched status of an article.
3788 * @since 1.22 $checkRights parameter added
3789 * @param Title $title Title of the article to look at
3790 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3791 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3794 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3795 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3796 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3803 * @since 1.22 $checkRights parameter added
3804 * @param Title $title Title of the article to look at
3805 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3806 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3808 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3809 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3810 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3812 [ $title->getSubjectPage(), $title->getTalkPage() ]
3815 $this->invalidateCache();
3819 * Stop watching an article.
3820 * @since 1.22 $checkRights parameter added
3821 * @param Title $title Title of the article to look at
3822 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3823 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3825 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3826 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3827 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3828 $store->removeWatch( $this, $title->getSubjectPage() );
3829 $store->removeWatch( $this, $title->getTalkPage() );
3831 $this->invalidateCache();
3835 * Clear the user's notification timestamp for the given title.
3836 * If e-notif e-mails are on, they will receive notification mails on
3837 * the next change of the page if it's watched etc.
3838 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3839 * @param Title &$title Title of the article to look at
3840 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3842 public function clearNotification( &$title, $oldid = 0 ) {
3843 global $wgUseEnotif, $wgShowUpdatedMarker;
3845 // Do nothing if the database is locked to writes
3846 if ( wfReadOnly() ) {
3850 // Do nothing if not allowed to edit the watchlist
3851 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3855 // If we're working on user's talk page, we should update the talk page message indicator
3856 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3857 // Avoid PHP 7.1 warning of passing $this by reference
3859 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$user, $oldid ] ) ) {
3863 // Try to update the DB post-send and only if needed...
3864 DeferredUpdates
::addCallableUpdate( function () use ( $title, $oldid ) {
3865 if ( !$this->getNewtalk() ) {
3866 return; // no notifications to clear
3869 // Delete the last notifications (they stack up)
3870 $this->setNewtalk( false );
3872 // If there is a new, unseen, revision, use its timestamp
3874 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3877 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3882 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3886 if ( $this->isAnon() ) {
3887 // Nothing else to do...
3891 // Only update the timestamp if the page is being watched.
3892 // The query to find out if it is watched is cached both in memcached and per-invocation,
3893 // and when it does have to be executed, it can be on a replica DB
3894 // If this is the user's newtalk page, we always update the timestamp
3896 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3900 MediaWikiServices
::getInstance()->getWatchedItemStore()
3901 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3905 * Resets all of the given user's page-change notification timestamps.
3906 * If e-notif e-mails are on, they will receive notification mails on
3907 * the next change of any watched page.
3908 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3910 public function clearAllNotifications() {
3911 global $wgUseEnotif, $wgShowUpdatedMarker;
3912 // Do nothing if not allowed to edit the watchlist
3913 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3917 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3918 $this->setNewtalk( false );
3922 $id = $this->getId();
3927 $watchedItemStore = MediaWikiServices
::getInstance()->getWatchedItemStore();
3928 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
3930 // We also need to clear here the "you have new message" notification for the own
3931 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3935 * Compute experienced level based on edit count and registration date.
3937 * @return string 'newcomer', 'learner', or 'experienced'
3939 public function getExperienceLevel() {
3940 global $wgLearnerEdits,
3941 $wgExperiencedUserEdits,
3942 $wgLearnerMemberSince,
3943 $wgExperiencedUserMemberSince;
3945 if ( $this->isAnon() ) {
3949 $editCount = $this->getEditCount();
3950 $registration = $this->getRegistration();
3952 $learnerRegistration = wfTimestamp( TS_MW
, $now - $wgLearnerMemberSince * 86400 );
3953 $experiencedRegistration = wfTimestamp( TS_MW
, $now - $wgExperiencedUserMemberSince * 86400 );
3955 if ( $editCount < $wgLearnerEdits ||
3956 $registration > $learnerRegistration ) {
3960 if ( $editCount > $wgExperiencedUserEdits &&
3961 $registration <= $experiencedRegistration
3963 return 'experienced';
3970 * Persist this user's session (e.g. set cookies)
3972 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3974 * @param bool|null $secure Whether to force secure/insecure cookies or use default
3975 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3977 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3979 if ( $this->mId
== 0 ) {
3983 $session = $this->getRequest()->getSession();
3984 if ( $request && $session->getRequest() !== $request ) {
3985 $session = $session->sessionWithRequest( $request );
3987 $delay = $session->delaySave();
3989 if ( !$session->getUser()->equals( $this ) ) {
3990 if ( !$session->canSetUser() ) {
3991 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3992 ->warning( __METHOD__
.
3993 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3997 $session->setUser( $this );
4000 $session->setRememberUser( $rememberMe );
4001 if ( $secure !== null ) {
4002 $session->setForceHTTPS( $secure );
4005 $session->persist();
4007 ScopedCallback
::consume( $delay );
4011 * Log this user out.
4013 public function logout() {
4014 // Avoid PHP 7.1 warning of passing $this by reference
4016 if ( Hooks
::run( 'UserLogout', [ &$user ] ) ) {
4022 * Clear the user's session, and reset the instance cache.
4025 public function doLogout() {
4026 $session = $this->getRequest()->getSession();
4027 if ( !$session->canSetUser() ) {
4028 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4029 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
4030 $error = 'immutable';
4031 } elseif ( !$session->getUser()->equals( $this ) ) {
4032 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
4033 ->warning( __METHOD__
.
4034 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4036 // But we still may as well make this user object anon
4037 $this->clearInstanceCache( 'defaults' );
4038 $error = 'wronguser';
4040 $this->clearInstanceCache( 'defaults' );
4041 $delay = $session->delaySave();
4042 $session->unpersist(); // Clear cookies (T127436)
4043 $session->setLoggedOutTimestamp( time() );
4044 $session->setUser( new User
);
4045 $session->set( 'wsUserID', 0 ); // Other code expects this
4046 $session->resetAllTokens();
4047 ScopedCallback
::consume( $delay );
4050 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
4051 'event' => 'logout',
4052 'successful' => $error === false,
4053 'status' => $error ?
: 'success',
4058 * Save this user's settings into the database.
4059 * @todo Only rarely do all these fields need to be set!
4061 public function saveSettings() {
4062 if ( wfReadOnly() ) {
4063 // @TODO: caller should deal with this instead!
4064 // This should really just be an exception.
4065 MWExceptionHandler
::logException( new DBExpectedError(
4067 "Could not update user with ID '{$this->mId}'; DB is read-only."
4073 if ( $this->mId
== 0 ) {
4077 // Get a new user_touched that is higher than the old one.
4078 // This will be used for a CAS check as a last-resort safety
4079 // check against race conditions and replica DB lag.
4080 $newTouched = $this->newTouchedTimestamp();
4082 $dbw = wfGetDB( DB_MASTER
);
4083 $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $newTouched ) {
4084 global $wgActorTableSchemaMigrationStage;
4086 $dbw->update( 'user',
4088 'user_name' => $this->mName
,
4089 'user_real_name' => $this->mRealName
,
4090 'user_email' => $this->mEmail
,
4091 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4092 'user_touched' => $dbw->timestamp( $newTouched ),
4093 'user_token' => strval( $this->mToken
),
4094 'user_email_token' => $this->mEmailToken
,
4095 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
4096 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
4097 'user_id' => $this->mId
,
4101 if ( !$dbw->affectedRows() ) {
4102 // Maybe the problem was a missed cache update; clear it to be safe
4103 $this->clearSharedCache( 'refresh' );
4104 // User was changed in the meantime or loaded with stale data
4105 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
4106 LoggerFactory
::getInstance( 'preferences' )->warning(
4107 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4108 [ 'user_id' => $this->mId
, 'db_flag' => $from ]
4110 throw new MWException( "CAS update failed on user_touched. " .
4111 "The version of the user to be saved is older than the current version."
4115 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4118 [ 'actor_name' => $this->mName
],
4119 [ 'actor_user' => $this->mId
],
4125 $this->mTouched
= $newTouched;
4126 $this->saveOptions();
4128 Hooks
::run( 'UserSaveSettings', [ $this ] );
4129 $this->clearSharedCache( 'changed' );
4130 $this->getUserPage()->purgeSquid();
4134 * If only this user's username is known, and it exists, return the user ID.
4136 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
4139 public function idForName( $flags = 0 ) {
4140 $s = trim( $this->getName() );
4145 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
4146 ?
wfGetDB( DB_MASTER
)
4147 : wfGetDB( DB_REPLICA
);
4149 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
4150 ?
[ 'LOCK IN SHARE MODE' ]
4153 $id = $db->selectField( 'user',
4154 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
4160 * Add a user to the database, return the user object
4162 * @param string $name Username to add
4163 * @param array $params Array of Strings Non-default parameters to save to
4164 * the database as user_* fields:
4165 * - email: The user's email address.
4166 * - email_authenticated: The email authentication timestamp.
4167 * - real_name: The user's real name.
4168 * - options: An associative array of non-default options.
4169 * - token: Random authentication token. Do not set.
4170 * - registration: Registration timestamp. Do not set.
4172 * @return User|null User object, or null if the username already exists.
4174 public static function createNew( $name, $params = [] ) {
4175 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
4176 if ( isset( $params[$field] ) ) {
4177 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
4178 unset( $params[$field] );
4184 $user->setToken(); // init token
4185 if ( isset( $params['options'] ) ) {
4186 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
4187 unset( $params['options'] );
4189 $dbw = wfGetDB( DB_MASTER
);
4191 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4194 'user_name' => $name,
4195 'user_password' => $noPass,
4196 'user_newpassword' => $noPass,
4197 'user_email' => $user->mEmail
,
4198 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
4199 'user_real_name' => $user->mRealName
,
4200 'user_token' => strval( $user->mToken
),
4201 'user_registration' => $dbw->timestamp( $user->mRegistration
),
4202 'user_editcount' => 0,
4203 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4205 foreach ( $params as $name => $value ) {
4206 $fields["user_$name"] = $value;
4209 return $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) use ( $fields ) {
4210 $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
4211 if ( $dbw->affectedRows() ) {
4212 $newUser = self
::newFromId( $dbw->insertId() );
4213 $newUser->mName
= $fields['user_name'];
4214 $newUser->updateActorId( $dbw );
4215 // Load the user from master to avoid replica lag
4216 $newUser->load( self
::READ_LATEST
);
4225 * Add this existing user object to the database. If the user already
4226 * exists, a fatal status object is returned, and the user object is
4227 * initialised with the data from the database.
4229 * Previously, this function generated a DB error due to a key conflict
4230 * if the user already existed. Many extension callers use this function
4231 * in code along the lines of:
4233 * $user = User::newFromName( $name );
4234 * if ( !$user->isLoggedIn() ) {
4235 * $user->addToDatabase();
4237 * // do something with $user...
4239 * However, this was vulnerable to a race condition (T18020). By
4240 * initialising the user object if the user exists, we aim to support this
4241 * calling sequence as far as possible.
4243 * Note that if the user exists, this function will acquire a write lock,
4244 * so it is still advisable to make the call conditional on isLoggedIn(),
4245 * and to commit the transaction after calling.
4247 * @throws MWException
4250 public function addToDatabase() {
4252 if ( !$this->mToken
) {
4253 $this->setToken(); // init token
4256 if ( !is_string( $this->mName
) ) {
4257 throw new RuntimeException( "User name field is not set." );
4260 $this->mTouched
= $this->newTouchedTimestamp();
4262 $dbw = wfGetDB( DB_MASTER
);
4263 $status = $dbw->doAtomicSection( __METHOD__
, function ( IDatabase
$dbw, $fname ) {
4264 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4265 $dbw->insert( 'user',
4267 'user_name' => $this->mName
,
4268 'user_password' => $noPass,
4269 'user_newpassword' => $noPass,
4270 'user_email' => $this->mEmail
,
4271 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4272 'user_real_name' => $this->mRealName
,
4273 'user_token' => strval( $this->mToken
),
4274 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4275 'user_editcount' => 0,
4276 'user_touched' => $dbw->timestamp( $this->mTouched
),
4280 if ( !$dbw->affectedRows() ) {
4281 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4282 $this->mId
= $dbw->selectField(
4285 [ 'user_name' => $this->mName
],
4287 [ 'LOCK IN SHARE MODE' ]
4290 if ( $this->mId
&& $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4294 throw new MWException( $fname . ": hit a key conflict attempting " .
4295 "to insert user '{$this->mName}' row, but it was not present in select!" );
4297 return Status
::newFatal( 'userexists' );
4299 $this->mId
= $dbw->insertId();
4300 self
::$idCacheByName[$this->mName
] = $this->mId
;
4301 $this->updateActorId( $dbw );
4303 return Status
::newGood();
4305 if ( !$status->isGood() ) {
4309 // Clear instance cache other than user table data and actor, which is already accurate
4310 $this->clearInstanceCache();
4312 $this->saveOptions();
4313 return Status
::newGood();
4317 * Update the actor ID after an insert
4318 * @param IDatabase $dbw Writable database handle
4320 private function updateActorId( IDatabase
$dbw ) {
4321 global $wgActorTableSchemaMigrationStage;
4323 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_WRITE_NEW
) {
4326 [ 'actor_user' => $this->mId
, 'actor_name' => $this->mName
],
4329 $this->mActorId
= (int)$dbw->insertId();
4334 * If this user is logged-in and blocked,
4335 * block any IP address they've successfully logged in from.
4336 * @return bool A block was spread
4338 public function spreadAnyEditBlock() {
4339 if ( $this->isLoggedIn() && $this->getBlock() ) {
4340 return $this->spreadBlock();
4347 * If this (non-anonymous) user is blocked,
4348 * block the IP address they've successfully logged in from.
4349 * @return bool A block was spread
4351 protected function spreadBlock() {
4352 wfDebug( __METHOD__
. "()\n" );
4354 if ( $this->mId
== 0 ) {
4358 $userblock = Block
::newFromTarget( $this->getName() );
4359 if ( !$userblock ) {
4363 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4367 * Get whether the user is explicitly blocked from account creation.
4368 * @return bool|AbstractBlock
4370 public function isBlockedFromCreateAccount() {
4371 $this->getBlockedStatus();
4372 if ( $this->mBlock
&& $this->mBlock
->appliesToRight( 'createaccount' ) ) {
4373 return $this->mBlock
;
4376 # T15611: if the IP address the user is trying to create an account from is
4377 # blocked with createaccount disabled, prevent new account creation there even
4378 # when the user is logged in
4379 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4380 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4382 return $this->mBlockedFromCreateAccount
instanceof AbstractBlock
4383 && $this->mBlockedFromCreateAccount
->appliesToRight( 'createaccount' )
4384 ?
$this->mBlockedFromCreateAccount
4389 * Get whether the user is blocked from using Special:Emailuser.
4392 public function isBlockedFromEmailuser() {
4393 $this->getBlockedStatus();
4394 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'sendemail' );
4398 * Get whether the user is blocked from using Special:Upload
4403 public function isBlockedFromUpload() {
4404 $this->getBlockedStatus();
4405 return $this->mBlock
&& $this->mBlock
->appliesToRight( 'upload' );
4409 * Get whether the user is allowed to create an account.
4412 public function isAllowedToCreateAccount() {
4413 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4417 * Get this user's personal page title.
4419 * @return Title User's personal page title
4421 public function getUserPage() {
4422 return Title
::makeTitle( NS_USER
, $this->getName() );
4426 * Get this user's talk page title.
4428 * @return Title User's talk page title
4430 public function getTalkPage() {
4431 $title = $this->getUserPage();
4432 return $title->getTalkPage();
4436 * Determine whether the user is a newbie. Newbies are either
4437 * anonymous IPs, or the most recently created accounts.
4440 public function isNewbie() {
4441 return !$this->isAllowed( 'autoconfirmed' );
4445 * Check to see if the given clear-text password is one of the accepted passwords
4446 * @deprecated since 1.27, use AuthManager instead
4447 * @param string $password User password
4448 * @return bool True if the given password is correct, otherwise False
4450 public function checkPassword( $password ) {
4451 wfDeprecated( __METHOD__
, '1.27' );
4453 $manager = AuthManager
::singleton();
4454 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4455 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4457 'username' => $this->getName(),
4458 'password' => $password,
4461 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4462 switch ( $res->status
) {
4463 case AuthenticationResponse
::PASS
:
4465 case AuthenticationResponse
::FAIL
:
4466 // Hope it's not a PreAuthenticationProvider that failed...
4467 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4468 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4471 throw new BadMethodCallException(
4472 'AuthManager returned a response unsupported by ' . __METHOD__
4478 * Check if the given clear-text password matches the temporary password
4479 * sent by e-mail for password reset operations.
4481 * @deprecated since 1.27, use AuthManager instead
4482 * @param string $plaintext
4483 * @return bool True if matches, false otherwise
4485 public function checkTemporaryPassword( $plaintext ) {
4486 wfDeprecated( __METHOD__
, '1.27' );
4487 // Can't check the temporary password individually.
4488 return $this->checkPassword( $plaintext );
4492 * Initialize (if necessary) and return a session token value
4493 * which can be used in edit forms to show that the user's
4494 * login credentials aren't being hijacked with a foreign form
4498 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4499 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4500 * @return MediaWiki\Session\Token The new edit token
4502 public function getEditTokenObject( $salt = '', $request = null ) {
4503 if ( $this->isAnon() ) {
4504 return new LoggedOutEditToken();
4508 $request = $this->getRequest();
4510 return $request->getSession()->getToken( $salt );
4514 * Initialize (if necessary) and return a session token value
4515 * which can be used in edit forms to show that the user's
4516 * login credentials aren't being hijacked with a foreign form
4519 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4522 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4523 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4524 * @return string The new edit token
4526 public function getEditToken( $salt = '', $request = null ) {
4527 return $this->getEditTokenObject( $salt, $request )->toString();
4531 * Check given value against the token value stored in the session.
4532 * A match should confirm that the form was submitted from the
4533 * user's own login session, not a form submission from a third-party
4536 * @param string $val Input value to compare
4537 * @param string|array $salt Optional function-specific data for hashing
4538 * @param WebRequest|null $request Object to use or null to use $wgRequest
4539 * @param int|null $maxage Fail tokens older than this, in seconds
4540 * @return bool Whether the token matches
4542 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4543 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4547 * Check given value against the token value stored in the session,
4548 * ignoring the suffix.
4550 * @param string $val Input value to compare
4551 * @param string|array $salt Optional function-specific data for hashing
4552 * @param WebRequest|null $request Object to use or null to use $wgRequest
4553 * @param int|null $maxage Fail tokens older than this, in seconds
4554 * @return bool Whether the token matches
4556 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4557 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4558 return $this->matchEditToken( $val, $salt, $request, $maxage );
4562 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4563 * mail to the user's given address.
4565 * @param string $type Message to send, either "created", "changed" or "set"
4568 public function sendConfirmationMail( $type = 'created' ) {
4570 $expiration = null; // gets passed-by-ref and defined in next line.
4571 $token = $this->confirmationToken( $expiration );
4572 $url = $this->confirmationTokenUrl( $token );
4573 $invalidateURL = $this->invalidationTokenUrl( $token );
4574 $this->saveSettings();
4576 if ( $type == 'created' ||
$type === false ) {
4577 $message = 'confirmemail_body';
4579 } elseif ( $type === true ) {
4580 $message = 'confirmemail_body_changed';
4583 // Messages: confirmemail_body_changed, confirmemail_body_set
4584 $message = 'confirmemail_body_' . $type;
4588 'subject' => wfMessage( 'confirmemail_subject' )->text(),
4589 'body' => wfMessage( $message,
4590 $this->getRequest()->getIP(),
4593 $wgLang->userTimeAndDate( $expiration, $this ),
4595 $wgLang->userDate( $expiration, $this ),
4596 $wgLang->userTime( $expiration, $this ) )->text(),
4602 'ip' => $this->getRequest()->getIP(),
4603 'confirmURL' => $url,
4604 'invalidateURL' => $invalidateURL,
4605 'expiration' => $expiration
4608 Hooks
::run( 'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4609 return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
4613 * Send an e-mail to this user's account. Does not check for
4614 * confirmed status or validity.
4616 * @param string $subject Message subject
4617 * @param string $body Message body
4618 * @param User|null $from Optional sending user; if unspecified, default
4619 * $wgPasswordSender will be used.
4620 * @param MailAddress|null $replyto Reply-To address
4623 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4624 global $wgPasswordSender;
4626 if ( $from instanceof User
) {
4627 $sender = MailAddress
::newFromUser( $from );
4629 $sender = new MailAddress( $wgPasswordSender,
4630 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4632 $to = MailAddress
::newFromUser( $this );
4634 return UserMailer
::send( $to, $sender, $subject, $body, [
4635 'replyTo' => $replyto,
4640 * Generate, store, and return a new e-mail confirmation code.
4641 * A hash (unsalted, since it's used as a key) is stored.
4643 * @note Call saveSettings() after calling this function to commit
4644 * this change to the database.
4646 * @param string &$expiration Accepts the expiration time
4647 * @return string New token
4649 protected function confirmationToken( &$expiration ) {
4650 global $wgUserEmailConfirmationTokenExpiry;
4652 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4653 $expiration = wfTimestamp( TS_MW
, $expires );
4655 $token = MWCryptRand
::generateHex( 32 );
4656 $hash = md5( $token );
4657 $this->mEmailToken
= $hash;
4658 $this->mEmailTokenExpires
= $expiration;
4663 * Return a URL the user can use to confirm their email address.
4664 * @param string $token Accepts the email confirmation token
4665 * @return string New token URL
4667 protected function confirmationTokenUrl( $token ) {
4668 return $this->getTokenUrl( 'ConfirmEmail', $token );
4672 * Return a URL the user can use to invalidate their email address.
4673 * @param string $token Accepts the email confirmation token
4674 * @return string New token URL
4676 protected function invalidationTokenUrl( $token ) {
4677 return $this->getTokenUrl( 'InvalidateEmail', $token );
4681 * Internal function to format the e-mail validation/invalidation URLs.
4682 * This uses a quickie hack to use the
4683 * hardcoded English names of the Special: pages, for ASCII safety.
4685 * @note Since these URLs get dropped directly into emails, using the
4686 * short English names avoids insanely long URL-encoded links, which
4687 * also sometimes can get corrupted in some browsers/mailers
4688 * (T8957 with Gmail and Internet Explorer).
4690 * @param string $page Special page
4691 * @param string $token
4692 * @return string Formatted URL
4694 protected function getTokenUrl( $page, $token ) {
4695 // Hack to bypass localization of 'Special:'
4696 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4697 return $title->getCanonicalURL();
4701 * Mark the e-mail address confirmed.
4703 * @note Call saveSettings() after calling this function to commit the change.
4707 public function confirmEmail() {
4708 // Check if it's already confirmed, so we don't touch the database
4709 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4710 if ( !$this->isEmailConfirmed() ) {
4711 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4712 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4718 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4719 * address if it was already confirmed.
4721 * @note Call saveSettings() after calling this function to commit the change.
4722 * @return bool Returns true
4724 public function invalidateEmail() {
4726 $this->mEmailToken
= null;
4727 $this->mEmailTokenExpires
= null;
4728 $this->setEmailAuthenticationTimestamp( null );
4730 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4735 * Set the e-mail authentication timestamp.
4736 * @param string $timestamp TS_MW timestamp
4738 public function setEmailAuthenticationTimestamp( $timestamp ) {
4740 $this->mEmailAuthenticated
= $timestamp;
4741 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4745 * Is this user allowed to send e-mails within limits of current
4746 * site configuration?
4749 public function canSendEmail() {
4750 global $wgEnableEmail, $wgEnableUserEmail;
4751 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4754 $canSend = $this->isEmailConfirmed();
4755 // Avoid PHP 7.1 warning of passing $this by reference
4757 Hooks
::run( 'UserCanSendEmail', [ &$user, &$canSend ] );
4762 * Is this user allowed to receive e-mails within limits of current
4763 * site configuration?
4766 public function canReceiveEmail() {
4767 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4771 * Is this user's e-mail address valid-looking and confirmed within
4772 * limits of the current site configuration?
4774 * @note If $wgEmailAuthentication is on, this may require the user to have
4775 * confirmed their address by returning a code or using a password
4776 * sent to the address from the wiki.
4780 public function isEmailConfirmed() {
4781 global $wgEmailAuthentication;
4783 // Avoid PHP 7.1 warning of passing $this by reference
4786 if ( Hooks
::run( 'EmailConfirmed', [ &$user, &$confirmed ] ) ) {
4787 if ( $this->isAnon() ) {
4790 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4793 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4803 * Check whether there is an outstanding request for e-mail confirmation.
4806 public function isEmailConfirmationPending() {
4807 global $wgEmailAuthentication;
4808 return $wgEmailAuthentication &&
4809 !$this->isEmailConfirmed() &&
4810 $this->mEmailToken
&&
4811 $this->mEmailTokenExpires
> wfTimestamp();
4815 * Get the timestamp of account creation.
4817 * @return string|bool|null Timestamp of account creation, false for
4818 * non-existent/anonymous user accounts, or null if existing account
4819 * but information is not in database.
4821 public function getRegistration() {
4822 if ( $this->isAnon() ) {
4826 return $this->mRegistration
;
4830 * Get the timestamp of the first edit
4832 * @return string|bool Timestamp of first edit, or false for
4833 * non-existent/anonymous user accounts.
4835 public function getFirstEditTimestamp() {
4836 return $this->getEditTimestamp( true );
4840 * Get the timestamp of the latest edit
4843 * @return string|bool Timestamp of first edit, or false for
4844 * non-existent/anonymous user accounts.
4846 public function getLatestEditTimestamp() {
4847 return $this->getEditTimestamp( false );
4851 * Get the timestamp of the first or latest edit
4853 * @param bool $first True for the first edit, false for the latest one
4854 * @return string|bool Timestamp of first or latest edit, or false for
4855 * non-existent/anonymous user accounts.
4857 private function getEditTimestamp( $first ) {
4858 if ( $this->getId() == 0 ) {
4859 return false; // anons
4861 $dbr = wfGetDB( DB_REPLICA
);
4862 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
4863 $tsField = isset( $actorWhere['tables']['temp_rev_user'] )
4864 ?
'revactor_timestamp' : 'rev_timestamp';
4865 $sortOrder = $first ?
'ASC' : 'DESC';
4866 $time = $dbr->selectField(
4867 [ 'revision' ] +
$actorWhere['tables'],
4869 [ $actorWhere['conds'] ],
4871 [ 'ORDER BY' => "$tsField $sortOrder" ],
4872 $actorWhere['joins']
4875 return false; // no edits
4877 return wfTimestamp( TS_MW
, $time );
4881 * Get the permissions associated with a given list of groups
4883 * @param array $groups Array of Strings List of internal group names
4884 * @return array Array of Strings List of permission key names for given groups combined
4886 public static function getGroupPermissions( $groups ) {
4887 global $wgGroupPermissions, $wgRevokePermissions;
4889 // grant every granted permission first
4890 foreach ( $groups as $group ) {
4891 if ( isset( $wgGroupPermissions[$group] ) ) {
4892 $rights = array_merge( $rights,
4893 // array_filter removes empty items
4894 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4897 // now revoke the revoked permissions
4898 foreach ( $groups as $group ) {
4899 if ( isset( $wgRevokePermissions[$group] ) ) {
4900 $rights = array_diff( $rights,
4901 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4904 return array_unique( $rights );
4908 * Get all the groups who have a given permission
4910 * @param string $role Role to check
4911 * @return array Array of Strings List of internal group names with the given permission
4913 public static function getGroupsWithPermission( $role ) {
4914 global $wgGroupPermissions;
4915 $allowedGroups = [];
4916 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4917 if ( self
::groupHasPermission( $group, $role ) ) {
4918 $allowedGroups[] = $group;
4921 return $allowedGroups;
4925 * Check, if the given group has the given permission
4927 * If you're wanting to check whether all users have a permission, use
4928 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4932 * @param string $group Group to check
4933 * @param string $role Role to check
4936 public static function groupHasPermission( $group, $role ) {
4937 global $wgGroupPermissions, $wgRevokePermissions;
4938 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4939 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4943 * Check if all users may be assumed to have the given permission
4945 * We generally assume so if the right is granted to '*' and isn't revoked
4946 * on any group. It doesn't attempt to take grants or other extension
4947 * limitations on rights into account in the general case, though, as that
4948 * would require it to always return false and defeat the purpose.
4949 * Specifically, session-based rights restrictions (such as OAuth or bot
4950 * passwords) are applied based on the current session.
4953 * @param string $right Right to check
4956 public static function isEveryoneAllowed( $right ) {
4957 global $wgGroupPermissions, $wgRevokePermissions;
4960 // Use the cached results, except in unit tests which rely on
4961 // being able change the permission mid-request
4962 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4963 return $cache[$right];
4966 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4967 $cache[$right] = false;
4971 // If it's revoked anywhere, then everyone doesn't have it
4972 foreach ( $wgRevokePermissions as $rights ) {
4973 if ( isset( $rights[$right] ) && $rights[$right] ) {
4974 $cache[$right] = false;
4979 // Remove any rights that aren't allowed to the global-session user,
4980 // unless there are no sessions for this endpoint.
4981 if ( !defined( 'MW_NO_SESSION' ) ) {
4982 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4983 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4984 $cache[$right] = false;
4989 // Allow extensions to say false
4990 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4991 $cache[$right] = false;
4995 $cache[$right] = true;
5000 * Return the set of defined explicit groups.
5001 * The implicit groups (by default *, 'user' and 'autoconfirmed')
5002 * are not included, as they are defined automatically, not in the database.
5003 * @return array Array of internal group names
5005 public static function getAllGroups() {
5006 global $wgGroupPermissions, $wgRevokePermissions;
5007 return array_values( array_diff(
5008 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
5009 self
::getImplicitGroups()
5014 * Get a list of all available permissions.
5015 * @return string[] Array of permission names
5017 public static function getAllRights() {
5018 if ( self
::$mAllRights === false ) {
5019 global $wgAvailableRights;
5020 if ( count( $wgAvailableRights ) ) {
5021 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
5023 self
::$mAllRights = self
::$mCoreRights;
5025 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
5027 return self
::$mAllRights;
5031 * Get a list of implicit groups
5032 * TODO: Should we deprecate this? It's trivial, but we don't want to encourage use of globals.
5034 * @return array Array of Strings Array of internal group names
5036 public static function getImplicitGroups() {
5037 global $wgImplicitGroups;
5038 return $wgImplicitGroups;
5042 * Returns an array of the groups that a particular group can add/remove.
5044 * @param string $group The group to check for whether it can add/remove
5045 * @return array Array( 'add' => array( addablegroups ),
5046 * 'remove' => array( removablegroups ),
5047 * 'add-self' => array( addablegroups to self),
5048 * 'remove-self' => array( removable groups from self) )
5050 public static function changeableByGroup( $group ) {
5051 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
5060 if ( empty( $wgAddGroups[$group] ) ) {
5061 // Don't add anything to $groups
5062 } elseif ( $wgAddGroups[$group] === true ) {
5063 // You get everything
5064 $groups['add'] = self
::getAllGroups();
5065 } elseif ( is_array( $wgAddGroups[$group] ) ) {
5066 $groups['add'] = $wgAddGroups[$group];
5069 // Same thing for remove
5070 if ( empty( $wgRemoveGroups[$group] ) ) {
5072 } elseif ( $wgRemoveGroups[$group] === true ) {
5073 $groups['remove'] = self
::getAllGroups();
5074 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
5075 $groups['remove'] = $wgRemoveGroups[$group];
5078 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
5079 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
5080 foreach ( $wgGroupsAddToSelf as $key => $value ) {
5081 if ( is_int( $key ) ) {
5082 $wgGroupsAddToSelf['user'][] = $value;
5087 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
5088 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
5089 if ( is_int( $key ) ) {
5090 $wgGroupsRemoveFromSelf['user'][] = $value;
5095 // Now figure out what groups the user can add to him/herself
5096 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
5098 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
5099 // No idea WHY this would be used, but it's there
5100 $groups['add-self'] = self
::getAllGroups();
5101 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
5102 $groups['add-self'] = $wgGroupsAddToSelf[$group];
5105 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
5107 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
5108 $groups['remove-self'] = self
::getAllGroups();
5109 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
5110 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
5117 * Returns an array of groups that this user can add and remove
5118 * @return array Array( 'add' => array( addablegroups ),
5119 * 'remove' => array( removablegroups ),
5120 * 'add-self' => array( addablegroups to self),
5121 * 'remove-self' => array( removable groups from self) )
5123 public function changeableGroups() {
5124 if ( $this->isAllowed( 'userrights' ) ) {
5125 // This group gives the right to modify everything (reverse-
5126 // compatibility with old "userrights lets you change
5128 // Using array_merge to make the groups reindexed
5129 $all = array_merge( self
::getAllGroups() );
5138 // Okay, it's not so simple, we will have to go through the arrays
5145 $addergroups = $this->getEffectiveGroups();
5147 foreach ( $addergroups as $addergroup ) {
5148 $groups = array_merge_recursive(
5149 $groups, $this->changeableByGroup( $addergroup )
5151 $groups['add'] = array_unique( $groups['add'] );
5152 $groups['remove'] = array_unique( $groups['remove'] );
5153 $groups['add-self'] = array_unique( $groups['add-self'] );
5154 $groups['remove-self'] = array_unique( $groups['remove-self'] );
5160 * Schedule a deferred update to update the user's edit count
5162 public function incEditCount() {
5163 if ( $this->isAnon() ) {
5167 DeferredUpdates
::addUpdate(
5168 new UserEditCountUpdate( $this, 1 ),
5169 DeferredUpdates
::POSTSEND
5174 * This method should not be called outside User/UserEditCountUpdate
5178 public function setEditCountInternal( $count ) {
5179 $this->mEditCount
= $count;
5183 * Initialize user_editcount from data out of the revision table
5185 * This method should not be called outside User/UserEditCountUpdate
5187 * @return int Number of edits
5189 public function initEditCountInternal() {
5190 // Pull from a replica DB to be less cruel to servers
5191 // Accuracy isn't the point anyway here
5192 $dbr = wfGetDB( DB_REPLICA
);
5193 $actorWhere = ActorMigration
::newMigration()->getWhere( $dbr, 'rev_user', $this );
5194 $count = (int)$dbr->selectField(
5195 [ 'revision' ] +
$actorWhere['tables'],
5197 [ $actorWhere['conds'] ],
5200 $actorWhere['joins']
5203 $dbw = wfGetDB( DB_MASTER
);
5206 [ 'user_editcount' => $count ],
5208 'user_id' => $this->getId(),
5209 'user_editcount IS NULL OR user_editcount < ' . (int)$count
5218 * Get the description of a given right
5221 * @param string $right Right to query
5222 * @return string Localized description of the right
5224 public static function getRightDescription( $right ) {
5225 $key = "right-$right";
5226 $msg = wfMessage( $key );
5227 return $msg->isDisabled() ?
$right : $msg->text();
5231 * Get the name of a given grant
5234 * @param string $grant Grant to query
5235 * @return string Localized name of the grant
5237 public static function getGrantName( $grant ) {
5238 $key = "grant-$grant";
5239 $msg = wfMessage( $key );
5240 return $msg->isDisabled() ?
$grant : $msg->text();
5244 * Add a newuser log entry for this user.
5245 * Before 1.19 the return value was always true.
5247 * @deprecated since 1.27, AuthManager handles logging
5248 * @param string|bool $action Account creation type.
5249 * - String, one of the following values:
5250 * - 'create' for an anonymous user creating an account for himself.
5251 * This will force the action's performer to be the created user itself,
5252 * no matter the value of $wgUser
5253 * - 'create2' for a logged in user creating an account for someone else
5254 * - 'byemail' when the created user will receive its password by e-mail
5255 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5256 * - Boolean means whether the account was created by e-mail (deprecated):
5257 * - true will be converted to 'byemail'
5258 * - false will be converted to 'create' if this object is the same as
5259 * $wgUser and to 'create2' otherwise
5260 * @param string $reason User supplied reason
5263 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5264 return true; // disabled
5268 * Add an autocreate newuser log entry for this user
5269 * Used by things like CentralAuth and perhaps other authplugins.
5270 * Consider calling addNewUserLogEntry() directly instead.
5272 * @deprecated since 1.27, AuthManager handles logging
5275 public function addNewUserLogEntryAutoCreate() {
5276 $this->addNewUserLogEntry( 'autocreate' );
5282 * Load the user options either from cache, the database or an array
5284 * @param array|null $data Rows for the current user out of the user_properties table
5286 protected function loadOptions( $data = null ) {
5289 if ( $this->mOptionsLoaded
) {
5293 $this->mOptions
= self
::getDefaultOptions();
5295 if ( !$this->getId() ) {
5296 // For unlogged-in users, load language/variant options from request.
5297 // There's no need to do it for logged-in users: they can set preferences,
5298 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5299 // so don't override user's choice (especially when the user chooses site default).
5300 $variant = MediaWikiServices
::getInstance()->getContentLanguage()->getDefaultVariant();
5301 $this->mOptions
['variant'] = $variant;
5302 $this->mOptions
['language'] = $variant;
5303 $this->mOptionsLoaded
= true;
5307 // Maybe load from the object
5308 if ( !is_null( $this->mOptionOverrides
) ) {
5309 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5310 foreach ( $this->mOptionOverrides
as $key => $value ) {
5311 $this->mOptions
[$key] = $value;
5314 if ( !is_array( $data ) ) {
5315 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5316 // Load from database
5317 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5318 ?
wfGetDB( DB_MASTER
)
5319 : wfGetDB( DB_REPLICA
);
5321 $res = $dbr->select(
5323 [ 'up_property', 'up_value' ],
5324 [ 'up_user' => $this->getId() ],
5328 $this->mOptionOverrides
= [];
5330 foreach ( $res as $row ) {
5331 // Convert '0' to 0. PHP's boolean conversion considers them both
5332 // false, but e.g. JavaScript considers the former as true.
5333 // @todo: T54542 Somehow determine the desired type (string/int/bool)
5334 // and convert all values here.
5335 if ( $row->up_value
=== '0' ) {
5338 $data[$row->up_property
] = $row->up_value
;
5342 foreach ( $data as $property => $value ) {
5343 $this->mOptionOverrides
[$property] = $value;
5344 $this->mOptions
[$property] = $value;
5348 // Replace deprecated language codes
5349 $this->mOptions
['language'] = LanguageCode
::replaceDeprecatedCodes(
5350 $this->mOptions
['language']
5353 $this->mOptionsLoaded
= true;
5355 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5359 * Saves the non-default options for this user, as previously set e.g. via
5360 * setOption(), in the database's "user_properties" (preferences) table.
5361 * Usually used via saveSettings().
5363 protected function saveOptions() {
5364 $this->loadOptions();
5366 // Not using getOptions(), to keep hidden preferences in database
5367 $saveOptions = $this->mOptions
;
5369 // Allow hooks to abort, for instance to save to a global profile.
5370 // Reset options to default state before saving.
5371 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5375 $userId = $this->getId();
5377 $insert_rows = []; // all the new preference rows
5378 foreach ( $saveOptions as $key => $value ) {
5379 // Don't bother storing default values
5380 $defaultOption = self
::getDefaultOption( $key );
5381 if ( ( $defaultOption === null && $value !== false && $value !== null )
5382 ||
$value != $defaultOption
5385 'up_user' => $userId,
5386 'up_property' => $key,
5387 'up_value' => $value,
5392 $dbw = wfGetDB( DB_MASTER
);
5394 $res = $dbw->select( 'user_properties',
5395 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5397 // Find prior rows that need to be removed or updated. These rows will
5398 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5400 foreach ( $res as $row ) {
5401 if ( !isset( $saveOptions[$row->up_property
] )
5402 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5404 $keysDelete[] = $row->up_property
;
5408 if ( count( $keysDelete ) ) {
5409 // Do the DELETE by PRIMARY KEY for prior rows.
5410 // In the past a very large portion of calls to this function are for setting
5411 // 'rememberpassword' for new accounts (a preference that has since been removed).
5412 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5413 // caused gap locks on [max user ID,+infinity) which caused high contention since
5414 // updates would pile up on each other as they are for higher (newer) user IDs.
5415 // It might not be necessary these days, but it shouldn't hurt either.
5416 $dbw->delete( 'user_properties',
5417 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5419 // Insert the new preference rows
5420 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5424 * Return the list of user fields that should be selected to create
5425 * a new user object.
5426 * @deprecated since 1.31, use self::getQueryInfo() instead.
5429 public static function selectFields() {
5430 wfDeprecated( __METHOD__
, '1.31' );
5438 'user_email_authenticated',
5440 'user_email_token_expires',
5441 'user_registration',
5447 * Return the tables, fields, and join conditions to be selected to create
5448 * a new user object.
5450 * @return array With three keys:
5451 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
5452 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
5453 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
5455 public static function getQueryInfo() {
5456 global $wgActorTableSchemaMigrationStage;
5459 'tables' => [ 'user' ],
5467 'user_email_authenticated',
5469 'user_email_token_expires',
5470 'user_registration',
5476 // Technically we shouldn't allow this without SCHEMA_COMPAT_READ_NEW,
5477 // but it does little harm and might be needed for write callers loading a User.
5478 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_NEW
) {
5479 $ret['tables']['user_actor'] = 'actor';
5480 $ret['fields'][] = 'user_actor.actor_id';
5481 $ret['joins']['user_actor'] = [
5482 ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW
) ?
'JOIN' : 'LEFT JOIN',
5483 [ 'user_actor.actor_user = user_id' ]
5491 * Factory function for fatal permission-denied errors
5494 * @param string $permission User right required
5497 static function newFatalPermissionDeniedStatus( $permission ) {
5501 foreach ( self
::getGroupsWithPermission( $permission ) as $group ) {
5502 $groups[] = UserGroupMembership
::getLink( $group, RequestContext
::getMain(), 'wiki' );
5506 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5509 return Status
::newFatal( 'badaccess-group0' );
5513 * Get a new instance of this user that was loaded from the master via a locking read
5515 * Use this instead of the main context User when updating that user. This avoids races
5516 * where that user was loaded from a replica DB or even the master but without proper locks.
5518 * @return User|null Returns null if the user was not found in the DB
5521 public function getInstanceForUpdate() {
5522 if ( !$this->getId() ) {
5523 return null; // anon
5526 $user = self
::newFromId( $this->getId() );
5527 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5535 * Checks if two user objects point to the same user.
5537 * @since 1.25 ; takes a UserIdentity instead of a User since 1.32
5538 * @param UserIdentity $user
5541 public function equals( UserIdentity
$user ) {
5542 // XXX it's not clear whether central ID providers are supposed to obey this
5543 return $this->getName() === $user->getName();
5547 * Checks if usertalk is allowed
5551 public function isAllowUsertalk() {
5552 return $this->mAllowUsertalk
;